X86: When combining shuffles just remove shuffles that are completely redundant.
[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> ExperimentalVectorShuffleLowering(
62     "x86-experimental-vector-shuffle-lowering", cl::init(false),
63     cl::desc("Enable an experimental vector shuffle lowering code path."),
64     cl::Hidden);
65
66 // Forward declarations.
67 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
68                        SDValue V2);
69
70 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
71                                 SelectionDAG &DAG, SDLoc dl,
72                                 unsigned vectorWidth) {
73   assert((vectorWidth == 128 || vectorWidth == 256) &&
74          "Unsupported vector width");
75   EVT VT = Vec.getValueType();
76   EVT ElVT = VT.getVectorElementType();
77   unsigned Factor = VT.getSizeInBits()/vectorWidth;
78   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
79                                   VT.getVectorNumElements()/Factor);
80
81   // Extract from UNDEF is UNDEF.
82   if (Vec.getOpcode() == ISD::UNDEF)
83     return DAG.getUNDEF(ResultVT);
84
85   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
86   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
87
88   // This is the index of the first element of the vectorWidth-bit chunk
89   // we want.
90   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
91                                * ElemsPerChunk);
92
93   // If the input is a buildvector just emit a smaller one.
94   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
95     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
96                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
97                                     ElemsPerChunk));
98
99   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
100   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
101                                VecIdx);
102
103   return Result;
104
105 }
106 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
107 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
108 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
109 /// instructions or a simple subregister reference. Idx is an index in the
110 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
111 /// lowering EXTRACT_VECTOR_ELT operations easier.
112 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
113                                    SelectionDAG &DAG, SDLoc dl) {
114   assert((Vec.getValueType().is256BitVector() ||
115           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
117 }
118
119 /// Generate a DAG to grab 256-bits from a 512-bit vector.
120 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
121                                    SelectionDAG &DAG, SDLoc dl) {
122   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
123   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
124 }
125
126 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
127                                unsigned IdxVal, SelectionDAG &DAG,
128                                SDLoc dl, unsigned vectorWidth) {
129   assert((vectorWidth == 128 || vectorWidth == 256) &&
130          "Unsupported vector width");
131   // Inserting UNDEF is Result
132   if (Vec.getOpcode() == ISD::UNDEF)
133     return Result;
134   EVT VT = Vec.getValueType();
135   EVT ElVT = VT.getVectorElementType();
136   EVT ResultVT = Result.getValueType();
137
138   // Insert the relevant vectorWidth bits.
139   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
140
141   // This is the index of the first element of the vectorWidth-bit chunk
142   // we want.
143   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
144                                * ElemsPerChunk);
145
146   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
147   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
148                      VecIdx);
149 }
150 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
151 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
152 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
153 /// simple superregister reference.  Idx is an index in the 128 bits
154 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
155 /// lowering INSERT_VECTOR_ELT operations easier.
156 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
161 }
162
163 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
164                                   unsigned IdxVal, SelectionDAG &DAG,
165                                   SDLoc dl) {
166   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
167   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
168 }
169
170 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
171 /// instructions. This is used because creating CONCAT_VECTOR nodes of
172 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
173 /// large BUILD_VECTORS.
174 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
182                                    unsigned NumElems, SelectionDAG &DAG,
183                                    SDLoc dl) {
184   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
186 }
187
188 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
189   if (TT.isOSBinFormatMachO()) {
190     if (TT.getArch() == Triple::x86_64)
191       return new X86_64MachoTargetObjectFile();
192     return new TargetLoweringObjectFileMachO();
193   }
194
195   if (TT.isOSLinux())
196     return new X86LinuxTargetObjectFile();
197   if (TT.isOSBinFormatELF())
198     return new TargetLoweringObjectFileELF();
199   if (TT.isKnownWindowsMSVCEnvironment())
200     return new X86WindowsTargetObjectFile();
201   if (TT.isOSBinFormatCOFF())
202     return new TargetLoweringObjectFileCOFF();
203   llvm_unreachable("unknown subtarget type");
204 }
205
206 // FIXME: This should stop caching the target machine as soon as
207 // we can remove resetOperationActions et al.
208 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
209   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
210   Subtarget = &TM.getSubtarget<X86Subtarget>();
211   X86ScalarSSEf64 = Subtarget->hasSSE2();
212   X86ScalarSSEf32 = Subtarget->hasSSE1();
213   TD = getDataLayout();
214
215   resetOperationActions();
216 }
217
218 void X86TargetLowering::resetOperationActions() {
219   const TargetMachine &TM = getTargetMachine();
220   static bool FirstTimeThrough = true;
221
222   // If none of the target options have changed, then we don't need to reset the
223   // operation actions.
224   if (!FirstTimeThrough && TO == TM.Options) return;
225
226   if (!FirstTimeThrough) {
227     // Reinitialize the actions.
228     initActions();
229     FirstTimeThrough = false;
230   }
231
232   TO = TM.Options;
233
234   // Set up the TargetLowering object.
235   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
236
237   // X86 is weird, it always uses i8 for shift amounts and setcc results.
238   setBooleanContents(ZeroOrOneBooleanContent);
239   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
240   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
241
242   // For 64-bit since we have so many registers use the ILP scheduler, for
243   // 32-bit code use the register pressure specific scheduling.
244   // For Atom, always use ILP scheduling.
245   if (Subtarget->isAtom())
246     setSchedulingPreference(Sched::ILP);
247   else if (Subtarget->is64Bit())
248     setSchedulingPreference(Sched::ILP);
249   else
250     setSchedulingPreference(Sched::RegPressure);
251   const X86RegisterInfo *RegInfo =
252     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
253   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
254
255   // Bypass expensive divides on Atom when compiling with O2
256   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
257     addBypassSlowDiv(32, 8);
258     if (Subtarget->is64Bit())
259       addBypassSlowDiv(64, 16);
260   }
261
262   if (Subtarget->isTargetKnownWindowsMSVC()) {
263     // Setup Windows compiler runtime calls.
264     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
265     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
266     setLibcallName(RTLIB::SREM_I64, "_allrem");
267     setLibcallName(RTLIB::UREM_I64, "_aullrem");
268     setLibcallName(RTLIB::MUL_I64, "_allmul");
269     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
270     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
271     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
272     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
273     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
274
275     // The _ftol2 runtime function has an unusual calling conv, which
276     // is modeled by a special pseudo-instruction.
277     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
278     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
279     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
280     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
281   }
282
283   if (Subtarget->isTargetDarwin()) {
284     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
285     setUseUnderscoreSetJmp(false);
286     setUseUnderscoreLongJmp(false);
287   } else if (Subtarget->isTargetWindowsGNU()) {
288     // MS runtime is weird: it exports _setjmp, but longjmp!
289     setUseUnderscoreSetJmp(true);
290     setUseUnderscoreLongJmp(false);
291   } else {
292     setUseUnderscoreSetJmp(true);
293     setUseUnderscoreLongJmp(true);
294   }
295
296   // Set up the register classes.
297   addRegisterClass(MVT::i8, &X86::GR8RegClass);
298   addRegisterClass(MVT::i16, &X86::GR16RegClass);
299   addRegisterClass(MVT::i32, &X86::GR32RegClass);
300   if (Subtarget->is64Bit())
301     addRegisterClass(MVT::i64, &X86::GR64RegClass);
302
303   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
304
305   // We don't accept any truncstore of integer registers.
306   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
307   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
308   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
309   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
310   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
311   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
312
313   // SETOEQ and SETUNE require checking two conditions.
314   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
315   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
316   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
317   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
318   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
319   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
320
321   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
322   // operation.
323   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
324   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
325   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
326
327   if (Subtarget->is64Bit()) {
328     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
329     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
330   } else if (!TM.Options.UseSoftFloat) {
331     // We have an algorithm for SSE2->double, and we turn this into a
332     // 64-bit FILD followed by conditional FADD for other targets.
333     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
334     // We have an algorithm for SSE2, and we turn this into a 64-bit
335     // FILD for other targets.
336     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
337   }
338
339   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
340   // this operation.
341   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
342   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
343
344   if (!TM.Options.UseSoftFloat) {
345     // SSE has no i16 to fp conversion, only i32
346     if (X86ScalarSSEf32) {
347       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
348       // f32 and f64 cases are Legal, f80 case is not
349       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
350     } else {
351       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
352       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
353     }
354   } else {
355     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
356     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
357   }
358
359   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
360   // are Legal, f80 is custom lowered.
361   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
362   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
363
364   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
365   // this operation.
366   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
367   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
368
369   if (X86ScalarSSEf32) {
370     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
371     // f32 and f64 cases are Legal, f80 case is not
372     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
373   } else {
374     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
375     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
376   }
377
378   // Handle FP_TO_UINT by promoting the destination to a larger signed
379   // conversion.
380   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
381   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
382   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
383
384   if (Subtarget->is64Bit()) {
385     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
386     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
387   } else if (!TM.Options.UseSoftFloat) {
388     // Since AVX is a superset of SSE3, only check for SSE here.
389     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
390       // Expand FP_TO_UINT into a select.
391       // FIXME: We would like to use a Custom expander here eventually to do
392       // the optimal thing for SSE vs. the default expansion in the legalizer.
393       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
394     else
395       // With SSE3 we can use fisttpll to convert to a signed i64; without
396       // SSE, we're stuck with a fistpll.
397       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
398   }
399
400   if (isTargetFTOL()) {
401     // Use the _ftol2 runtime function, which has a pseudo-instruction
402     // to handle its weird calling convention.
403     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
404   }
405
406   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
407   if (!X86ScalarSSEf64) {
408     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
409     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
410     if (Subtarget->is64Bit()) {
411       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
412       // Without SSE, i64->f64 goes through memory.
413       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
414     }
415   }
416
417   // Scalar integer divide and remainder are lowered to use operations that
418   // produce two results, to match the available instructions. This exposes
419   // the two-result form to trivial CSE, which is able to combine x/y and x%y
420   // into a single instruction.
421   //
422   // Scalar integer multiply-high is also lowered to use two-result
423   // operations, to match the available instructions. However, plain multiply
424   // (low) operations are left as Legal, as there are single-result
425   // instructions for this in x86. Using the two-result multiply instructions
426   // when both high and low results are needed must be arranged by dagcombine.
427   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
428     MVT VT = IntVTs[i];
429     setOperationAction(ISD::MULHS, VT, Expand);
430     setOperationAction(ISD::MULHU, VT, Expand);
431     setOperationAction(ISD::SDIV, VT, Expand);
432     setOperationAction(ISD::UDIV, VT, Expand);
433     setOperationAction(ISD::SREM, VT, Expand);
434     setOperationAction(ISD::UREM, VT, Expand);
435
436     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
437     setOperationAction(ISD::ADDC, VT, Custom);
438     setOperationAction(ISD::ADDE, VT, Custom);
439     setOperationAction(ISD::SUBC, VT, Custom);
440     setOperationAction(ISD::SUBE, VT, Custom);
441   }
442
443   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
444   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
445   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
446   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
447   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
448   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
449   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
450   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
451   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
452   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
453   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
454   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
455   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
456   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
457   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
459   if (Subtarget->is64Bit())
460     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
461   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
462   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
463   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
464   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
465   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
466   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
467   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
468   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
469
470   // Promote the i8 variants and force them on up to i32 which has a shorter
471   // encoding.
472   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
473   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
474   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
475   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
476   if (Subtarget->hasBMI()) {
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
479     if (Subtarget->is64Bit())
480       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
481   } else {
482     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
483     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
484     if (Subtarget->is64Bit())
485       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
486   }
487
488   if (Subtarget->hasLZCNT()) {
489     // When promoting the i8 variants, force them to i32 for a shorter
490     // encoding.
491     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
492     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
493     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
494     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
495     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
496     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
497     if (Subtarget->is64Bit())
498       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
499   } else {
500     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
501     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
502     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
503     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
504     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
505     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
506     if (Subtarget->is64Bit()) {
507       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
508       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
509     }
510   }
511
512   if (Subtarget->hasPOPCNT()) {
513     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
514   } else {
515     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
516     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
517     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
518     if (Subtarget->is64Bit())
519       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
520   }
521
522   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
523
524   if (!Subtarget->hasMOVBE())
525     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
526
527   // These should be promoted to a larger select which is supported.
528   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
529   // X86 wants to expand cmov itself.
530   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
531   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
532   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
533   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
534   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
535   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
536   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
537   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
538   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
539   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
540   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
541   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
542   if (Subtarget->is64Bit()) {
543     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
544     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
545   }
546   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
547   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
548   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
549   // support continuation, user-level threading, and etc.. As a result, no
550   // other SjLj exception interfaces are implemented and please don't build
551   // your own exception handling based on them.
552   // LLVM/Clang supports zero-cost DWARF exception handling.
553   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
554   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
555
556   // Darwin ABI issue.
557   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
558   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
559   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
560   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
561   if (Subtarget->is64Bit())
562     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
563   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
564   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
565   if (Subtarget->is64Bit()) {
566     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
567     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
568     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
569     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
570     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
571   }
572   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
573   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
574   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
575   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
576   if (Subtarget->is64Bit()) {
577     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
578     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
579     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
580   }
581
582   if (Subtarget->hasSSE1())
583     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
584
585   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
586
587   // Expand certain atomics
588   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
589     MVT VT = IntVTs[i];
590     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
592     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
593   }
594
595   if (Subtarget->hasCmpxchg16b()) {
596     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
597   }
598
599   // FIXME - use subtarget debug flags
600   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
601       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
602     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
603   }
604
605   if (Subtarget->is64Bit()) {
606     setExceptionPointerRegister(X86::RAX);
607     setExceptionSelectorRegister(X86::RDX);
608   } else {
609     setExceptionPointerRegister(X86::EAX);
610     setExceptionSelectorRegister(X86::EDX);
611   }
612   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
613   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
614
615   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
616   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
617
618   setOperationAction(ISD::TRAP, MVT::Other, Legal);
619   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
620
621   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
622   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
623   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
624   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
625     // TargetInfo::X86_64ABIBuiltinVaList
626     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
627     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
628   } else {
629     // TargetInfo::CharPtrBuiltinVaList
630     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
631     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
632   }
633
634   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
635   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
636
637   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
638                      MVT::i64 : MVT::i32, Custom);
639
640   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
641     // f32 and f64 use SSE.
642     // Set up the FP register classes.
643     addRegisterClass(MVT::f32, &X86::FR32RegClass);
644     addRegisterClass(MVT::f64, &X86::FR64RegClass);
645
646     // Use ANDPD to simulate FABS.
647     setOperationAction(ISD::FABS , MVT::f64, Custom);
648     setOperationAction(ISD::FABS , MVT::f32, Custom);
649
650     // Use XORP to simulate FNEG.
651     setOperationAction(ISD::FNEG , MVT::f64, Custom);
652     setOperationAction(ISD::FNEG , MVT::f32, Custom);
653
654     // Use ANDPD and ORPD to simulate FCOPYSIGN.
655     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
656     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
657
658     // Lower this to FGETSIGNx86 plus an AND.
659     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
660     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
661
662     // We don't support sin/cos/fmod
663     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
664     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
665     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
666     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
667     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
668     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
669
670     // Expand FP immediates into loads from the stack, except for the special
671     // cases we handle.
672     addLegalFPImmediate(APFloat(+0.0)); // xorpd
673     addLegalFPImmediate(APFloat(+0.0f)); // xorps
674   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
675     // Use SSE for f32, x87 for f64.
676     // Set up the FP register classes.
677     addRegisterClass(MVT::f32, &X86::FR32RegClass);
678     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
679
680     // Use ANDPS to simulate FABS.
681     setOperationAction(ISD::FABS , MVT::f32, Custom);
682
683     // Use XORP to simulate FNEG.
684     setOperationAction(ISD::FNEG , MVT::f32, Custom);
685
686     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
687
688     // Use ANDPS and ORPS to simulate FCOPYSIGN.
689     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
690     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
691
692     // We don't support sin/cos/fmod
693     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
694     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
695     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
696
697     // Special cases we handle for FP constants.
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699     addLegalFPImmediate(APFloat(+0.0)); // FLD0
700     addLegalFPImmediate(APFloat(+1.0)); // FLD1
701     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
702     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
703
704     if (!TM.Options.UnsafeFPMath) {
705       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
706       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
707       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
708     }
709   } else if (!TM.Options.UseSoftFloat) {
710     // f32 and f64 in x87.
711     // Set up the FP register classes.
712     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
713     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
714
715     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
716     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
717     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
718     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
719
720     if (!TM.Options.UnsafeFPMath) {
721       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
722       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
723       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
724       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
725       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
726       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
727     }
728     addLegalFPImmediate(APFloat(+0.0)); // FLD0
729     addLegalFPImmediate(APFloat(+1.0)); // FLD1
730     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
731     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
732     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
733     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
734     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
735     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
736   }
737
738   // We don't support FMA.
739   setOperationAction(ISD::FMA, MVT::f64, Expand);
740   setOperationAction(ISD::FMA, MVT::f32, Expand);
741
742   // Long double always uses X87.
743   if (!TM.Options.UseSoftFloat) {
744     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
745     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
746     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
747     {
748       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
749       addLegalFPImmediate(TmpFlt);  // FLD0
750       TmpFlt.changeSign();
751       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
752
753       bool ignored;
754       APFloat TmpFlt2(+1.0);
755       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
756                       &ignored);
757       addLegalFPImmediate(TmpFlt2);  // FLD1
758       TmpFlt2.changeSign();
759       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
760     }
761
762     if (!TM.Options.UnsafeFPMath) {
763       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
764       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
765       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
766     }
767
768     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
769     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
770     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
771     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
772     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
773     setOperationAction(ISD::FMA, MVT::f80, Expand);
774   }
775
776   // Always use a library call for pow.
777   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
778   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
779   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
780
781   setOperationAction(ISD::FLOG, MVT::f80, Expand);
782   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
783   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
784   setOperationAction(ISD::FEXP, MVT::f80, Expand);
785   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
786
787   // First set operation action for all vector types to either promote
788   // (for widening) or expand (for scalarization). Then we will selectively
789   // turn on ones that can be effectively codegen'd.
790   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
791            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
792     MVT VT = (MVT::SimpleValueType)i;
793     setOperationAction(ISD::ADD , VT, Expand);
794     setOperationAction(ISD::SUB , VT, Expand);
795     setOperationAction(ISD::FADD, VT, Expand);
796     setOperationAction(ISD::FNEG, VT, Expand);
797     setOperationAction(ISD::FSUB, VT, Expand);
798     setOperationAction(ISD::MUL , VT, Expand);
799     setOperationAction(ISD::FMUL, VT, Expand);
800     setOperationAction(ISD::SDIV, VT, Expand);
801     setOperationAction(ISD::UDIV, VT, Expand);
802     setOperationAction(ISD::FDIV, VT, Expand);
803     setOperationAction(ISD::SREM, VT, Expand);
804     setOperationAction(ISD::UREM, VT, Expand);
805     setOperationAction(ISD::LOAD, VT, Expand);
806     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
807     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
808     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
809     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
810     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
811     setOperationAction(ISD::FABS, VT, Expand);
812     setOperationAction(ISD::FSIN, VT, Expand);
813     setOperationAction(ISD::FSINCOS, VT, Expand);
814     setOperationAction(ISD::FCOS, VT, Expand);
815     setOperationAction(ISD::FSINCOS, VT, Expand);
816     setOperationAction(ISD::FREM, VT, Expand);
817     setOperationAction(ISD::FMA,  VT, Expand);
818     setOperationAction(ISD::FPOWI, VT, Expand);
819     setOperationAction(ISD::FSQRT, VT, Expand);
820     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
821     setOperationAction(ISD::FFLOOR, VT, Expand);
822     setOperationAction(ISD::FCEIL, VT, Expand);
823     setOperationAction(ISD::FTRUNC, VT, Expand);
824     setOperationAction(ISD::FRINT, VT, Expand);
825     setOperationAction(ISD::FNEARBYINT, VT, Expand);
826     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
827     setOperationAction(ISD::MULHS, VT, Expand);
828     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
829     setOperationAction(ISD::MULHU, VT, Expand);
830     setOperationAction(ISD::SDIVREM, VT, Expand);
831     setOperationAction(ISD::UDIVREM, VT, Expand);
832     setOperationAction(ISD::FPOW, VT, Expand);
833     setOperationAction(ISD::CTPOP, VT, Expand);
834     setOperationAction(ISD::CTTZ, VT, Expand);
835     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
836     setOperationAction(ISD::CTLZ, VT, Expand);
837     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::SHL, VT, Expand);
839     setOperationAction(ISD::SRA, VT, Expand);
840     setOperationAction(ISD::SRL, VT, Expand);
841     setOperationAction(ISD::ROTL, VT, Expand);
842     setOperationAction(ISD::ROTR, VT, Expand);
843     setOperationAction(ISD::BSWAP, VT, Expand);
844     setOperationAction(ISD::SETCC, VT, Expand);
845     setOperationAction(ISD::FLOG, VT, Expand);
846     setOperationAction(ISD::FLOG2, VT, Expand);
847     setOperationAction(ISD::FLOG10, VT, Expand);
848     setOperationAction(ISD::FEXP, VT, Expand);
849     setOperationAction(ISD::FEXP2, VT, Expand);
850     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
851     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
852     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
853     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
854     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
855     setOperationAction(ISD::TRUNCATE, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
857     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
858     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
859     setOperationAction(ISD::VSELECT, VT, Expand);
860     setOperationAction(ISD::SELECT_CC, VT, Expand);
861     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
862              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
863       setTruncStoreAction(VT,
864                           (MVT::SimpleValueType)InnerVT, Expand);
865     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
866     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
868   }
869
870   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
871   // with -msoft-float, disable use of MMX as well.
872   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
873     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
874     // No operations on x86mmx supported, everything uses intrinsics.
875   }
876
877   // MMX-sized vectors (other than x86mmx) are expected to be expanded
878   // into smaller operations.
879   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
880   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
881   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
883   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
884   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
885   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
886   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
887   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
888   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
889   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
890   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
891   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
892   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
893   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
894   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
895   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
899   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
900   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
901   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
902   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
904   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
908
909   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
910     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
911
912     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
913     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
917     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
918     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
919     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
920     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
921     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
922     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
923     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
924   }
925
926   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
927     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
928
929     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
930     // registers cannot be used even for integer operations.
931     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
932     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
933     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
934     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
935
936     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
937     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
938     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
939     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
940     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
941     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
942     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
943     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
944     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
945     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
946     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
947     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
948     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
949     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
950     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
951     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
956     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
957     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
958
959     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
961     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
962     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
963
964     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
965     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
969
970     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972       MVT VT = (MVT::SimpleValueType)i;
973       // Do not attempt to custom lower non-power-of-2 vectors
974       if (!isPowerOf2_32(VT.getVectorNumElements()))
975         continue;
976       // Do not attempt to custom lower non-128-bit vectors
977       if (!VT.is128BitVector())
978         continue;
979       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
980       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
981       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
982     }
983
984     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
985     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
986     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
987     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
990
991     if (Subtarget->is64Bit()) {
992       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
993       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
994     }
995
996     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998       MVT VT = (MVT::SimpleValueType)i;
999
1000       // Do not attempt to promote non-128-bit vectors
1001       if (!VT.is128BitVector())
1002         continue;
1003
1004       setOperationAction(ISD::AND,    VT, Promote);
1005       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1006       setOperationAction(ISD::OR,     VT, Promote);
1007       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1008       setOperationAction(ISD::XOR,    VT, Promote);
1009       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1010       setOperationAction(ISD::LOAD,   VT, Promote);
1011       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1012       setOperationAction(ISD::SELECT, VT, Promote);
1013       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1014     }
1015
1016     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1017
1018     // Custom lower v2i64 and v2f64 selects.
1019     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1020     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1021     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1022     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1023
1024     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1025     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1026
1027     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1028     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1029     // As there is no 64-bit GPR available, we need build a special custom
1030     // sequence to convert from v2i32 to v2f32.
1031     if (!Subtarget->is64Bit())
1032       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1033
1034     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1035     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1036
1037     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1038
1039     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1040     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1041     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1042   }
1043
1044   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1045     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1046     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1047     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1048     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1049     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1050     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1051     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1052     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1053     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1054     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1055
1056     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1061     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1062     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1063     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1064     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1065     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1066
1067     // FIXME: Do we need to handle scalar-to-vector here?
1068     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1069
1070     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1071     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1072     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1073     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1074     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1075     // There is no BLENDI for byte vectors. We don't need to custom lower
1076     // some vselects for now.
1077     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1078
1079     // i8 and i16 vectors are custom , because the source register and source
1080     // source memory operand types are not the same width.  f32 vectors are
1081     // custom since the immediate controlling the insert encodes additional
1082     // information.
1083     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1084     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1085     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1086     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1087
1088     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1089     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1090     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1091     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1092
1093     // FIXME: these should be Legal but thats only for the case where
1094     // the index is constant.  For now custom expand to deal with that.
1095     if (Subtarget->is64Bit()) {
1096       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1097       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1098     }
1099   }
1100
1101   if (Subtarget->hasSSE2()) {
1102     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1103     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1104
1105     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1106     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1107
1108     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1109     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1110
1111     // In the customized shift lowering, the legal cases in AVX2 will be
1112     // recognized.
1113     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1114     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1115
1116     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1117     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1118
1119     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1120   }
1121
1122   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1123     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1124     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1125     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1126     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1127     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1128     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1129
1130     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1132     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1133
1134     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1135     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1136     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1137     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1138     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1139     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1140     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1141     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1142     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1143     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1144     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1145     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1146
1147     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1148     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1149     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1150     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1151     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1152     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1153     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1154     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1155     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1156     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1157     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1158     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1159
1160     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1161     // even though v8i16 is a legal type.
1162     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1163     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1164     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1165
1166     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1167     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1168     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1169
1170     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1171     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1172
1173     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1174
1175     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1179     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1180
1181     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1182     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1183
1184     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1185     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1186     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1187     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1188
1189     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1190     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1191     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1192
1193     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1194     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1195     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1196     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1197
1198     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1199     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1200     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1201     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1202     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1203     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1204     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1205     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1206     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1207     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1208     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1209     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1210
1211     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1212       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1213       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1214       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1215       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1216       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1217       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1218     }
1219
1220     if (Subtarget->hasInt256()) {
1221       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1222       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1223       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1224       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1225
1226       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1227       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1228       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1229       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1230
1231       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1232       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1233       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1234       // Don't lower v32i8 because there is no 128-bit byte mul
1235
1236       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1237       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1238       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1239       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1240
1241       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1242       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1243     } else {
1244       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1245       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1246       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1247       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1248
1249       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1250       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1251       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1252       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1253
1254       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1255       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1256       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1257       // Don't lower v32i8 because there is no 128-bit byte mul
1258     }
1259
1260     // In the customized shift lowering, the legal cases in AVX2 will be
1261     // recognized.
1262     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1263     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1264
1265     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1266     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1267
1268     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1269
1270     // Custom lower several nodes for 256-bit types.
1271     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1272              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1273       MVT VT = (MVT::SimpleValueType)i;
1274
1275       // Extract subvector is special because the value type
1276       // (result) is 128-bit but the source is 256-bit wide.
1277       if (VT.is128BitVector())
1278         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1279
1280       // Do not attempt to custom lower other non-256-bit vectors
1281       if (!VT.is256BitVector())
1282         continue;
1283
1284       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1285       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1286       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1287       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1288       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1289       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1290       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1291     }
1292
1293     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1295       MVT VT = (MVT::SimpleValueType)i;
1296
1297       // Do not attempt to promote non-256-bit vectors
1298       if (!VT.is256BitVector())
1299         continue;
1300
1301       setOperationAction(ISD::AND,    VT, Promote);
1302       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1303       setOperationAction(ISD::OR,     VT, Promote);
1304       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1305       setOperationAction(ISD::XOR,    VT, Promote);
1306       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1307       setOperationAction(ISD::LOAD,   VT, Promote);
1308       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1309       setOperationAction(ISD::SELECT, VT, Promote);
1310       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1311     }
1312   }
1313
1314   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1315     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1316     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1317     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1318     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1319
1320     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1321     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1322     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1323
1324     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1325     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1326     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1327     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1328     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1329     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1330     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1331     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1333     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1334     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1335
1336     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1337     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1338     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1339     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1340     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1341     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1342
1343     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1344     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1345     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1348     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1349     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1350     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1351
1352     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1353     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1356     if (Subtarget->is64Bit()) {
1357       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1358       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1359       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1360       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1361     }
1362     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1363     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1364     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1365     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1366     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1367     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1368     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1369     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1370     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1371     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1372
1373     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1374     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1375     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1376     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1377     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1378     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1379     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1380     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1381     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1382     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1383     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1384     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1385     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1386
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1390     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1391     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1392     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1393
1394     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1395     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1396
1397     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1398
1399     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1400     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1401     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1402     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1403     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1404     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1405     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1406     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1407     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1408
1409     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1410     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1411
1412     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1413     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1414
1415     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1416
1417     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1418     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1419
1420     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1421     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1422
1423     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1424     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1425
1426     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1427     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1428     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1429     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1430     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1431     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1432
1433     if (Subtarget->hasCDI()) {
1434       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1435       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1436     }
1437
1438     // Custom lower several nodes.
1439     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1440              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1441       MVT VT = (MVT::SimpleValueType)i;
1442
1443       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1444       // Extract subvector is special because the value type
1445       // (result) is 256/128-bit but the source is 512-bit wide.
1446       if (VT.is128BitVector() || VT.is256BitVector())
1447         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1448
1449       if (VT.getVectorElementType() == MVT::i1)
1450         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1451
1452       // Do not attempt to custom lower other non-512-bit vectors
1453       if (!VT.is512BitVector())
1454         continue;
1455
1456       if ( EltSize >= 32) {
1457         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1458         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1459         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1460         setOperationAction(ISD::VSELECT,             VT, Legal);
1461         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1462         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1463         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1464       }
1465     }
1466     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1467       MVT VT = (MVT::SimpleValueType)i;
1468
1469       // Do not attempt to promote non-256-bit vectors
1470       if (!VT.is512BitVector())
1471         continue;
1472
1473       setOperationAction(ISD::SELECT, VT, Promote);
1474       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1475     }
1476   }// has  AVX-512
1477
1478   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1479   // of this type with custom code.
1480   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1481            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1482     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1483                        Custom);
1484   }
1485
1486   // We want to custom lower some of our intrinsics.
1487   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1488   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1489   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1490   if (!Subtarget->is64Bit())
1491     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1492
1493   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1494   // handle type legalization for these operations here.
1495   //
1496   // FIXME: We really should do custom legalization for addition and
1497   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1498   // than generic legalization for 64-bit multiplication-with-overflow, though.
1499   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1500     // Add/Sub/Mul with overflow operations are custom lowered.
1501     MVT VT = IntVTs[i];
1502     setOperationAction(ISD::SADDO, VT, Custom);
1503     setOperationAction(ISD::UADDO, VT, Custom);
1504     setOperationAction(ISD::SSUBO, VT, Custom);
1505     setOperationAction(ISD::USUBO, VT, Custom);
1506     setOperationAction(ISD::SMULO, VT, Custom);
1507     setOperationAction(ISD::UMULO, VT, Custom);
1508   }
1509
1510   // There are no 8-bit 3-address imul/mul instructions
1511   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1512   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1513
1514   if (!Subtarget->is64Bit()) {
1515     // These libcalls are not available in 32-bit.
1516     setLibcallName(RTLIB::SHL_I128, nullptr);
1517     setLibcallName(RTLIB::SRL_I128, nullptr);
1518     setLibcallName(RTLIB::SRA_I128, nullptr);
1519   }
1520
1521   // Combine sin / cos into one node or libcall if possible.
1522   if (Subtarget->hasSinCos()) {
1523     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1524     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1525     if (Subtarget->isTargetDarwin()) {
1526       // For MacOSX, we don't want to the normal expansion of a libcall to
1527       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1528       // traffic.
1529       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1530       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1531     }
1532   }
1533
1534   if (Subtarget->isTargetWin64()) {
1535     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1536     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1537     setOperationAction(ISD::SREM, MVT::i128, Custom);
1538     setOperationAction(ISD::UREM, MVT::i128, Custom);
1539     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1540     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1541   }
1542
1543   // We have target-specific dag combine patterns for the following nodes:
1544   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1545   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1546   setTargetDAGCombine(ISD::VSELECT);
1547   setTargetDAGCombine(ISD::SELECT);
1548   setTargetDAGCombine(ISD::SHL);
1549   setTargetDAGCombine(ISD::SRA);
1550   setTargetDAGCombine(ISD::SRL);
1551   setTargetDAGCombine(ISD::OR);
1552   setTargetDAGCombine(ISD::AND);
1553   setTargetDAGCombine(ISD::ADD);
1554   setTargetDAGCombine(ISD::FADD);
1555   setTargetDAGCombine(ISD::FSUB);
1556   setTargetDAGCombine(ISD::FMA);
1557   setTargetDAGCombine(ISD::SUB);
1558   setTargetDAGCombine(ISD::LOAD);
1559   setTargetDAGCombine(ISD::STORE);
1560   setTargetDAGCombine(ISD::ZERO_EXTEND);
1561   setTargetDAGCombine(ISD::ANY_EXTEND);
1562   setTargetDAGCombine(ISD::SIGN_EXTEND);
1563   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1564   setTargetDAGCombine(ISD::TRUNCATE);
1565   setTargetDAGCombine(ISD::SINT_TO_FP);
1566   setTargetDAGCombine(ISD::SETCC);
1567   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1568   setTargetDAGCombine(ISD::BUILD_VECTOR);
1569   if (Subtarget->is64Bit())
1570     setTargetDAGCombine(ISD::MUL);
1571   setTargetDAGCombine(ISD::XOR);
1572
1573   computeRegisterProperties();
1574
1575   // On Darwin, -Os means optimize for size without hurting performance,
1576   // do not reduce the limit.
1577   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1578   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1579   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1580   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1581   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1582   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1583   setPrefLoopAlignment(4); // 2^4 bytes.
1584
1585   // Predictable cmov don't hurt on atom because it's in-order.
1586   PredictableSelectIsExpensive = !Subtarget->isAtom();
1587
1588   setPrefFunctionAlignment(4); // 2^4 bytes.
1589 }
1590
1591 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1592   if (!VT.isVector())
1593     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1594
1595   if (Subtarget->hasAVX512())
1596     switch(VT.getVectorNumElements()) {
1597     case  8: return MVT::v8i1;
1598     case 16: return MVT::v16i1;
1599   }
1600
1601   return VT.changeVectorElementTypeToInteger();
1602 }
1603
1604 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1605 /// the desired ByVal argument alignment.
1606 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1607   if (MaxAlign == 16)
1608     return;
1609   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1610     if (VTy->getBitWidth() == 128)
1611       MaxAlign = 16;
1612   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1613     unsigned EltAlign = 0;
1614     getMaxByValAlign(ATy->getElementType(), EltAlign);
1615     if (EltAlign > MaxAlign)
1616       MaxAlign = EltAlign;
1617   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1618     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1619       unsigned EltAlign = 0;
1620       getMaxByValAlign(STy->getElementType(i), EltAlign);
1621       if (EltAlign > MaxAlign)
1622         MaxAlign = EltAlign;
1623       if (MaxAlign == 16)
1624         break;
1625     }
1626   }
1627 }
1628
1629 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1630 /// function arguments in the caller parameter area. For X86, aggregates
1631 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1632 /// are at 4-byte boundaries.
1633 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1634   if (Subtarget->is64Bit()) {
1635     // Max of 8 and alignment of type.
1636     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1637     if (TyAlign > 8)
1638       return TyAlign;
1639     return 8;
1640   }
1641
1642   unsigned Align = 4;
1643   if (Subtarget->hasSSE1())
1644     getMaxByValAlign(Ty, Align);
1645   return Align;
1646 }
1647
1648 /// getOptimalMemOpType - Returns the target specific optimal type for load
1649 /// and store operations as a result of memset, memcpy, and memmove
1650 /// lowering. If DstAlign is zero that means it's safe to destination
1651 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1652 /// means there isn't a need to check it against alignment requirement,
1653 /// probably because the source does not need to be loaded. If 'IsMemset' is
1654 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1655 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1656 /// source is constant so it does not need to be loaded.
1657 /// It returns EVT::Other if the type should be determined using generic
1658 /// target-independent logic.
1659 EVT
1660 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1661                                        unsigned DstAlign, unsigned SrcAlign,
1662                                        bool IsMemset, bool ZeroMemset,
1663                                        bool MemcpyStrSrc,
1664                                        MachineFunction &MF) const {
1665   const Function *F = MF.getFunction();
1666   if ((!IsMemset || ZeroMemset) &&
1667       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1668                                        Attribute::NoImplicitFloat)) {
1669     if (Size >= 16 &&
1670         (Subtarget->isUnalignedMemAccessFast() ||
1671          ((DstAlign == 0 || DstAlign >= 16) &&
1672           (SrcAlign == 0 || SrcAlign >= 16)))) {
1673       if (Size >= 32) {
1674         if (Subtarget->hasInt256())
1675           return MVT::v8i32;
1676         if (Subtarget->hasFp256())
1677           return MVT::v8f32;
1678       }
1679       if (Subtarget->hasSSE2())
1680         return MVT::v4i32;
1681       if (Subtarget->hasSSE1())
1682         return MVT::v4f32;
1683     } else if (!MemcpyStrSrc && Size >= 8 &&
1684                !Subtarget->is64Bit() &&
1685                Subtarget->hasSSE2()) {
1686       // Do not use f64 to lower memcpy if source is string constant. It's
1687       // better to use i32 to avoid the loads.
1688       return MVT::f64;
1689     }
1690   }
1691   if (Subtarget->is64Bit() && Size >= 8)
1692     return MVT::i64;
1693   return MVT::i32;
1694 }
1695
1696 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1697   if (VT == MVT::f32)
1698     return X86ScalarSSEf32;
1699   else if (VT == MVT::f64)
1700     return X86ScalarSSEf64;
1701   return true;
1702 }
1703
1704 bool
1705 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1706                                                  unsigned,
1707                                                  bool *Fast) const {
1708   if (Fast)
1709     *Fast = Subtarget->isUnalignedMemAccessFast();
1710   return true;
1711 }
1712
1713 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1714 /// current function.  The returned value is a member of the
1715 /// MachineJumpTableInfo::JTEntryKind enum.
1716 unsigned X86TargetLowering::getJumpTableEncoding() const {
1717   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1718   // symbol.
1719   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1720       Subtarget->isPICStyleGOT())
1721     return MachineJumpTableInfo::EK_Custom32;
1722
1723   // Otherwise, use the normal jump table encoding heuristics.
1724   return TargetLowering::getJumpTableEncoding();
1725 }
1726
1727 const MCExpr *
1728 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1729                                              const MachineBasicBlock *MBB,
1730                                              unsigned uid,MCContext &Ctx) const{
1731   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1732          Subtarget->isPICStyleGOT());
1733   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1734   // entries.
1735   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1736                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1737 }
1738
1739 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1740 /// jumptable.
1741 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1742                                                     SelectionDAG &DAG) const {
1743   if (!Subtarget->is64Bit())
1744     // This doesn't have SDLoc associated with it, but is not really the
1745     // same as a Register.
1746     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1747   return Table;
1748 }
1749
1750 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1751 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1752 /// MCExpr.
1753 const MCExpr *X86TargetLowering::
1754 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1755                              MCContext &Ctx) const {
1756   // X86-64 uses RIP relative addressing based on the jump table label.
1757   if (Subtarget->isPICStyleRIPRel())
1758     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1759
1760   // Otherwise, the reference is relative to the PIC base.
1761   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1762 }
1763
1764 // FIXME: Why this routine is here? Move to RegInfo!
1765 std::pair<const TargetRegisterClass*, uint8_t>
1766 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1767   const TargetRegisterClass *RRC = nullptr;
1768   uint8_t Cost = 1;
1769   switch (VT.SimpleTy) {
1770   default:
1771     return TargetLowering::findRepresentativeClass(VT);
1772   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1773     RRC = Subtarget->is64Bit() ?
1774       (const TargetRegisterClass*)&X86::GR64RegClass :
1775       (const TargetRegisterClass*)&X86::GR32RegClass;
1776     break;
1777   case MVT::x86mmx:
1778     RRC = &X86::VR64RegClass;
1779     break;
1780   case MVT::f32: case MVT::f64:
1781   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1782   case MVT::v4f32: case MVT::v2f64:
1783   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1784   case MVT::v4f64:
1785     RRC = &X86::VR128RegClass;
1786     break;
1787   }
1788   return std::make_pair(RRC, Cost);
1789 }
1790
1791 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1792                                                unsigned &Offset) const {
1793   if (!Subtarget->isTargetLinux())
1794     return false;
1795
1796   if (Subtarget->is64Bit()) {
1797     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1798     Offset = 0x28;
1799     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1800       AddressSpace = 256;
1801     else
1802       AddressSpace = 257;
1803   } else {
1804     // %gs:0x14 on i386
1805     Offset = 0x14;
1806     AddressSpace = 256;
1807   }
1808   return true;
1809 }
1810
1811 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1812                                             unsigned DestAS) const {
1813   assert(SrcAS != DestAS && "Expected different address spaces!");
1814
1815   return SrcAS < 256 && DestAS < 256;
1816 }
1817
1818 //===----------------------------------------------------------------------===//
1819 //               Return Value Calling Convention Implementation
1820 //===----------------------------------------------------------------------===//
1821
1822 #include "X86GenCallingConv.inc"
1823
1824 bool
1825 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1826                                   MachineFunction &MF, bool isVarArg,
1827                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1828                         LLVMContext &Context) const {
1829   SmallVector<CCValAssign, 16> RVLocs;
1830   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1831                  RVLocs, Context);
1832   return CCInfo.CheckReturn(Outs, RetCC_X86);
1833 }
1834
1835 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1836   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1837   return ScratchRegs;
1838 }
1839
1840 SDValue
1841 X86TargetLowering::LowerReturn(SDValue Chain,
1842                                CallingConv::ID CallConv, bool isVarArg,
1843                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1844                                const SmallVectorImpl<SDValue> &OutVals,
1845                                SDLoc dl, SelectionDAG &DAG) const {
1846   MachineFunction &MF = DAG.getMachineFunction();
1847   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1848
1849   SmallVector<CCValAssign, 16> RVLocs;
1850   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1851                  RVLocs, *DAG.getContext());
1852   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1853
1854   SDValue Flag;
1855   SmallVector<SDValue, 6> RetOps;
1856   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1857   // Operand #1 = Bytes To Pop
1858   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1859                    MVT::i16));
1860
1861   // Copy the result values into the output registers.
1862   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1863     CCValAssign &VA = RVLocs[i];
1864     assert(VA.isRegLoc() && "Can only return in registers!");
1865     SDValue ValToCopy = OutVals[i];
1866     EVT ValVT = ValToCopy.getValueType();
1867
1868     // Promote values to the appropriate types
1869     if (VA.getLocInfo() == CCValAssign::SExt)
1870       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1871     else if (VA.getLocInfo() == CCValAssign::ZExt)
1872       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1873     else if (VA.getLocInfo() == CCValAssign::AExt)
1874       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1875     else if (VA.getLocInfo() == CCValAssign::BCvt)
1876       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1877
1878     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1879            "Unexpected FP-extend for return value.");  
1880
1881     // If this is x86-64, and we disabled SSE, we can't return FP values,
1882     // or SSE or MMX vectors.
1883     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1884          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1885           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1886       report_fatal_error("SSE register return with SSE disabled");
1887     }
1888     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1889     // llvm-gcc has never done it right and no one has noticed, so this
1890     // should be OK for now.
1891     if (ValVT == MVT::f64 &&
1892         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1893       report_fatal_error("SSE2 register return with SSE2 disabled");
1894
1895     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1896     // the RET instruction and handled by the FP Stackifier.
1897     if (VA.getLocReg() == X86::ST0 ||
1898         VA.getLocReg() == X86::ST1) {
1899       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1900       // change the value to the FP stack register class.
1901       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1902         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1903       RetOps.push_back(ValToCopy);
1904       // Don't emit a copytoreg.
1905       continue;
1906     }
1907
1908     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1909     // which is returned in RAX / RDX.
1910     if (Subtarget->is64Bit()) {
1911       if (ValVT == MVT::x86mmx) {
1912         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1913           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1914           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1915                                   ValToCopy);
1916           // If we don't have SSE2 available, convert to v4f32 so the generated
1917           // register is legal.
1918           if (!Subtarget->hasSSE2())
1919             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1920         }
1921       }
1922     }
1923
1924     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1925     Flag = Chain.getValue(1);
1926     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1927   }
1928
1929   // The x86-64 ABIs require that for returning structs by value we copy
1930   // the sret argument into %rax/%eax (depending on ABI) for the return.
1931   // Win32 requires us to put the sret argument to %eax as well.
1932   // We saved the argument into a virtual register in the entry block,
1933   // so now we copy the value out and into %rax/%eax.
1934   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1935       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1936     MachineFunction &MF = DAG.getMachineFunction();
1937     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1938     unsigned Reg = FuncInfo->getSRetReturnReg();
1939     assert(Reg &&
1940            "SRetReturnReg should have been set in LowerFormalArguments().");
1941     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1942
1943     unsigned RetValReg
1944         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1945           X86::RAX : X86::EAX;
1946     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1947     Flag = Chain.getValue(1);
1948
1949     // RAX/EAX now acts like a return value.
1950     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1951   }
1952
1953   RetOps[0] = Chain;  // Update chain.
1954
1955   // Add the flag if we have it.
1956   if (Flag.getNode())
1957     RetOps.push_back(Flag);
1958
1959   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1960 }
1961
1962 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1963   if (N->getNumValues() != 1)
1964     return false;
1965   if (!N->hasNUsesOfValue(1, 0))
1966     return false;
1967
1968   SDValue TCChain = Chain;
1969   SDNode *Copy = *N->use_begin();
1970   if (Copy->getOpcode() == ISD::CopyToReg) {
1971     // If the copy has a glue operand, we conservatively assume it isn't safe to
1972     // perform a tail call.
1973     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1974       return false;
1975     TCChain = Copy->getOperand(0);
1976   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1977     return false;
1978
1979   bool HasRet = false;
1980   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1981        UI != UE; ++UI) {
1982     if (UI->getOpcode() != X86ISD::RET_FLAG)
1983       return false;
1984     HasRet = true;
1985   }
1986
1987   if (!HasRet)
1988     return false;
1989
1990   Chain = TCChain;
1991   return true;
1992 }
1993
1994 MVT
1995 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1996                                             ISD::NodeType ExtendKind) const {
1997   MVT ReturnMVT;
1998   // TODO: Is this also valid on 32-bit?
1999   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2000     ReturnMVT = MVT::i8;
2001   else
2002     ReturnMVT = MVT::i32;
2003
2004   MVT MinVT = getRegisterType(ReturnMVT);
2005   return VT.bitsLT(MinVT) ? MinVT : VT;
2006 }
2007
2008 /// LowerCallResult - Lower the result values of a call into the
2009 /// appropriate copies out of appropriate physical registers.
2010 ///
2011 SDValue
2012 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2013                                    CallingConv::ID CallConv, bool isVarArg,
2014                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2015                                    SDLoc dl, SelectionDAG &DAG,
2016                                    SmallVectorImpl<SDValue> &InVals) const {
2017
2018   // Assign locations to each value returned by this call.
2019   SmallVector<CCValAssign, 16> RVLocs;
2020   bool Is64Bit = Subtarget->is64Bit();
2021   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2022                  DAG.getTarget(), RVLocs, *DAG.getContext());
2023   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2024
2025   // Copy all of the result registers out of their specified physreg.
2026   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2027     CCValAssign &VA = RVLocs[i];
2028     EVT CopyVT = VA.getValVT();
2029
2030     // If this is x86-64, and we disabled SSE, we can't return FP values
2031     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2032         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2033       report_fatal_error("SSE register return with SSE disabled");
2034     }
2035
2036     SDValue Val;
2037
2038     // If this is a call to a function that returns an fp value on the floating
2039     // point stack, we must guarantee the value is popped from the stack, so
2040     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2041     // if the return value is not used. We use the FpPOP_RETVAL instruction
2042     // instead.
2043     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2044       // If we prefer to use the value in xmm registers, copy it out as f80 and
2045       // use a truncate to move it from fp stack reg to xmm reg.
2046       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2047       SDValue Ops[] = { Chain, InFlag };
2048       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2049                                          MVT::Other, MVT::Glue, Ops), 1);
2050       Val = Chain.getValue(0);
2051
2052       // Round the f80 to the right size, which also moves it to the appropriate
2053       // xmm register.
2054       if (CopyVT != VA.getValVT())
2055         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2056                           // This truncation won't change the value.
2057                           DAG.getIntPtrConstant(1));
2058     } else {
2059       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2060                                  CopyVT, InFlag).getValue(1);
2061       Val = Chain.getValue(0);
2062     }
2063     InFlag = Chain.getValue(2);
2064     InVals.push_back(Val);
2065   }
2066
2067   return Chain;
2068 }
2069
2070 //===----------------------------------------------------------------------===//
2071 //                C & StdCall & Fast Calling Convention implementation
2072 //===----------------------------------------------------------------------===//
2073 //  StdCall calling convention seems to be standard for many Windows' API
2074 //  routines and around. It differs from C calling convention just a little:
2075 //  callee should clean up the stack, not caller. Symbols should be also
2076 //  decorated in some fancy way :) It doesn't support any vector arguments.
2077 //  For info on fast calling convention see Fast Calling Convention (tail call)
2078 //  implementation LowerX86_32FastCCCallTo.
2079
2080 /// CallIsStructReturn - Determines whether a call uses struct return
2081 /// semantics.
2082 enum StructReturnType {
2083   NotStructReturn,
2084   RegStructReturn,
2085   StackStructReturn
2086 };
2087 static StructReturnType
2088 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2089   if (Outs.empty())
2090     return NotStructReturn;
2091
2092   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2093   if (!Flags.isSRet())
2094     return NotStructReturn;
2095   if (Flags.isInReg())
2096     return RegStructReturn;
2097   return StackStructReturn;
2098 }
2099
2100 /// ArgsAreStructReturn - Determines whether a function uses struct
2101 /// return semantics.
2102 static StructReturnType
2103 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2104   if (Ins.empty())
2105     return NotStructReturn;
2106
2107   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2108   if (!Flags.isSRet())
2109     return NotStructReturn;
2110   if (Flags.isInReg())
2111     return RegStructReturn;
2112   return StackStructReturn;
2113 }
2114
2115 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2116 /// by "Src" to address "Dst" with size and alignment information specified by
2117 /// the specific parameter attribute. The copy will be passed as a byval
2118 /// function parameter.
2119 static SDValue
2120 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2121                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2122                           SDLoc dl) {
2123   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2124
2125   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2126                        /*isVolatile*/false, /*AlwaysInline=*/true,
2127                        MachinePointerInfo(), MachinePointerInfo());
2128 }
2129
2130 /// IsTailCallConvention - Return true if the calling convention is one that
2131 /// supports tail call optimization.
2132 static bool IsTailCallConvention(CallingConv::ID CC) {
2133   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2134           CC == CallingConv::HiPE);
2135 }
2136
2137 /// \brief Return true if the calling convention is a C calling convention.
2138 static bool IsCCallConvention(CallingConv::ID CC) {
2139   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2140           CC == CallingConv::X86_64_SysV);
2141 }
2142
2143 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2144   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2145     return false;
2146
2147   CallSite CS(CI);
2148   CallingConv::ID CalleeCC = CS.getCallingConv();
2149   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2150     return false;
2151
2152   return true;
2153 }
2154
2155 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2156 /// a tailcall target by changing its ABI.
2157 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2158                                    bool GuaranteedTailCallOpt) {
2159   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2160 }
2161
2162 SDValue
2163 X86TargetLowering::LowerMemArgument(SDValue Chain,
2164                                     CallingConv::ID CallConv,
2165                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2166                                     SDLoc dl, SelectionDAG &DAG,
2167                                     const CCValAssign &VA,
2168                                     MachineFrameInfo *MFI,
2169                                     unsigned i) const {
2170   // Create the nodes corresponding to a load from this parameter slot.
2171   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2172   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2173       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2174   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2175   EVT ValVT;
2176
2177   // If value is passed by pointer we have address passed instead of the value
2178   // itself.
2179   if (VA.getLocInfo() == CCValAssign::Indirect)
2180     ValVT = VA.getLocVT();
2181   else
2182     ValVT = VA.getValVT();
2183
2184   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2185   // changed with more analysis.
2186   // In case of tail call optimization mark all arguments mutable. Since they
2187   // could be overwritten by lowering of arguments in case of a tail call.
2188   if (Flags.isByVal()) {
2189     unsigned Bytes = Flags.getByValSize();
2190     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2191     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2192     return DAG.getFrameIndex(FI, getPointerTy());
2193   } else {
2194     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2195                                     VA.getLocMemOffset(), isImmutable);
2196     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2197     return DAG.getLoad(ValVT, dl, Chain, FIN,
2198                        MachinePointerInfo::getFixedStack(FI),
2199                        false, false, false, 0);
2200   }
2201 }
2202
2203 SDValue
2204 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2205                                         CallingConv::ID CallConv,
2206                                         bool isVarArg,
2207                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2208                                         SDLoc dl,
2209                                         SelectionDAG &DAG,
2210                                         SmallVectorImpl<SDValue> &InVals)
2211                                           const {
2212   MachineFunction &MF = DAG.getMachineFunction();
2213   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2214
2215   const Function* Fn = MF.getFunction();
2216   if (Fn->hasExternalLinkage() &&
2217       Subtarget->isTargetCygMing() &&
2218       Fn->getName() == "main")
2219     FuncInfo->setForceFramePointer(true);
2220
2221   MachineFrameInfo *MFI = MF.getFrameInfo();
2222   bool Is64Bit = Subtarget->is64Bit();
2223   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2224
2225   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2226          "Var args not supported with calling convention fastcc, ghc or hipe");
2227
2228   // Assign locations to all of the incoming arguments.
2229   SmallVector<CCValAssign, 16> ArgLocs;
2230   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2231                  ArgLocs, *DAG.getContext());
2232
2233   // Allocate shadow area for Win64
2234   if (IsWin64)
2235     CCInfo.AllocateStack(32, 8);
2236
2237   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2238
2239   unsigned LastVal = ~0U;
2240   SDValue ArgValue;
2241   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2242     CCValAssign &VA = ArgLocs[i];
2243     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2244     // places.
2245     assert(VA.getValNo() != LastVal &&
2246            "Don't support value assigned to multiple locs yet");
2247     (void)LastVal;
2248     LastVal = VA.getValNo();
2249
2250     if (VA.isRegLoc()) {
2251       EVT RegVT = VA.getLocVT();
2252       const TargetRegisterClass *RC;
2253       if (RegVT == MVT::i32)
2254         RC = &X86::GR32RegClass;
2255       else if (Is64Bit && RegVT == MVT::i64)
2256         RC = &X86::GR64RegClass;
2257       else if (RegVT == MVT::f32)
2258         RC = &X86::FR32RegClass;
2259       else if (RegVT == MVT::f64)
2260         RC = &X86::FR64RegClass;
2261       else if (RegVT.is512BitVector())
2262         RC = &X86::VR512RegClass;
2263       else if (RegVT.is256BitVector())
2264         RC = &X86::VR256RegClass;
2265       else if (RegVT.is128BitVector())
2266         RC = &X86::VR128RegClass;
2267       else if (RegVT == MVT::x86mmx)
2268         RC = &X86::VR64RegClass;
2269       else if (RegVT == MVT::i1)
2270         RC = &X86::VK1RegClass;
2271       else if (RegVT == MVT::v8i1)
2272         RC = &X86::VK8RegClass;
2273       else if (RegVT == MVT::v16i1)
2274         RC = &X86::VK16RegClass;
2275       else
2276         llvm_unreachable("Unknown argument type!");
2277
2278       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2279       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2280
2281       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2282       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2283       // right size.
2284       if (VA.getLocInfo() == CCValAssign::SExt)
2285         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2286                                DAG.getValueType(VA.getValVT()));
2287       else if (VA.getLocInfo() == CCValAssign::ZExt)
2288         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2289                                DAG.getValueType(VA.getValVT()));
2290       else if (VA.getLocInfo() == CCValAssign::BCvt)
2291         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2292
2293       if (VA.isExtInLoc()) {
2294         // Handle MMX values passed in XMM regs.
2295         if (RegVT.isVector())
2296           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2297         else
2298           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2299       }
2300     } else {
2301       assert(VA.isMemLoc());
2302       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2303     }
2304
2305     // If value is passed via pointer - do a load.
2306     if (VA.getLocInfo() == CCValAssign::Indirect)
2307       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2308                              MachinePointerInfo(), false, false, false, 0);
2309
2310     InVals.push_back(ArgValue);
2311   }
2312
2313   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2314     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2315       // The x86-64 ABIs require that for returning structs by value we copy
2316       // the sret argument into %rax/%eax (depending on ABI) for the return.
2317       // Win32 requires us to put the sret argument to %eax as well.
2318       // Save the argument into a virtual register so that we can access it
2319       // from the return points.
2320       if (Ins[i].Flags.isSRet()) {
2321         unsigned Reg = FuncInfo->getSRetReturnReg();
2322         if (!Reg) {
2323           MVT PtrTy = getPointerTy();
2324           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2325           FuncInfo->setSRetReturnReg(Reg);
2326         }
2327         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2328         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2329         break;
2330       }
2331     }
2332   }
2333
2334   unsigned StackSize = CCInfo.getNextStackOffset();
2335   // Align stack specially for tail calls.
2336   if (FuncIsMadeTailCallSafe(CallConv,
2337                              MF.getTarget().Options.GuaranteedTailCallOpt))
2338     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2339
2340   // If the function takes variable number of arguments, make a frame index for
2341   // the start of the first vararg value... for expansion of llvm.va_start.
2342   if (isVarArg) {
2343     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2344                     CallConv != CallingConv::X86_ThisCall)) {
2345       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2346     }
2347     if (Is64Bit) {
2348       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2349
2350       // FIXME: We should really autogenerate these arrays
2351       static const MCPhysReg GPR64ArgRegsWin64[] = {
2352         X86::RCX, X86::RDX, X86::R8,  X86::R9
2353       };
2354       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2355         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2356       };
2357       static const MCPhysReg XMMArgRegs64Bit[] = {
2358         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2359         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2360       };
2361       const MCPhysReg *GPR64ArgRegs;
2362       unsigned NumXMMRegs = 0;
2363
2364       if (IsWin64) {
2365         // The XMM registers which might contain var arg parameters are shadowed
2366         // in their paired GPR.  So we only need to save the GPR to their home
2367         // slots.
2368         TotalNumIntRegs = 4;
2369         GPR64ArgRegs = GPR64ArgRegsWin64;
2370       } else {
2371         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2372         GPR64ArgRegs = GPR64ArgRegs64Bit;
2373
2374         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2375                                                 TotalNumXMMRegs);
2376       }
2377       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2378                                                        TotalNumIntRegs);
2379
2380       bool NoImplicitFloatOps = Fn->getAttributes().
2381         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2382       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2383              "SSE register cannot be used when SSE is disabled!");
2384       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2385                NoImplicitFloatOps) &&
2386              "SSE register cannot be used when SSE is disabled!");
2387       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2388           !Subtarget->hasSSE1())
2389         // Kernel mode asks for SSE to be disabled, so don't push them
2390         // on the stack.
2391         TotalNumXMMRegs = 0;
2392
2393       if (IsWin64) {
2394         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2395         // Get to the caller-allocated home save location.  Add 8 to account
2396         // for the return address.
2397         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2398         FuncInfo->setRegSaveFrameIndex(
2399           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2400         // Fixup to set vararg frame on shadow area (4 x i64).
2401         if (NumIntRegs < 4)
2402           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2403       } else {
2404         // For X86-64, if there are vararg parameters that are passed via
2405         // registers, then we must store them to their spots on the stack so
2406         // they may be loaded by deferencing the result of va_next.
2407         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2408         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2409         FuncInfo->setRegSaveFrameIndex(
2410           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2411                                false));
2412       }
2413
2414       // Store the integer parameter registers.
2415       SmallVector<SDValue, 8> MemOps;
2416       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2417                                         getPointerTy());
2418       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2419       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2420         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2421                                   DAG.getIntPtrConstant(Offset));
2422         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2423                                      &X86::GR64RegClass);
2424         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2425         SDValue Store =
2426           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2427                        MachinePointerInfo::getFixedStack(
2428                          FuncInfo->getRegSaveFrameIndex(), Offset),
2429                        false, false, 0);
2430         MemOps.push_back(Store);
2431         Offset += 8;
2432       }
2433
2434       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2435         // Now store the XMM (fp + vector) parameter registers.
2436         SmallVector<SDValue, 11> SaveXMMOps;
2437         SaveXMMOps.push_back(Chain);
2438
2439         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2440         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2441         SaveXMMOps.push_back(ALVal);
2442
2443         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2444                                FuncInfo->getRegSaveFrameIndex()));
2445         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2446                                FuncInfo->getVarArgsFPOffset()));
2447
2448         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2449           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2450                                        &X86::VR128RegClass);
2451           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2452           SaveXMMOps.push_back(Val);
2453         }
2454         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2455                                      MVT::Other, SaveXMMOps));
2456       }
2457
2458       if (!MemOps.empty())
2459         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2460     }
2461   }
2462
2463   // Some CCs need callee pop.
2464   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2465                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2466     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2467   } else {
2468     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2469     // If this is an sret function, the return should pop the hidden pointer.
2470     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2471         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2472         argsAreStructReturn(Ins) == StackStructReturn)
2473       FuncInfo->setBytesToPopOnReturn(4);
2474   }
2475
2476   if (!Is64Bit) {
2477     // RegSaveFrameIndex is X86-64 only.
2478     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2479     if (CallConv == CallingConv::X86_FastCall ||
2480         CallConv == CallingConv::X86_ThisCall)
2481       // fastcc functions can't have varargs.
2482       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2483   }
2484
2485   FuncInfo->setArgumentStackSize(StackSize);
2486
2487   return Chain;
2488 }
2489
2490 SDValue
2491 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2492                                     SDValue StackPtr, SDValue Arg,
2493                                     SDLoc dl, SelectionDAG &DAG,
2494                                     const CCValAssign &VA,
2495                                     ISD::ArgFlagsTy Flags) const {
2496   unsigned LocMemOffset = VA.getLocMemOffset();
2497   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2498   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2499   if (Flags.isByVal())
2500     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2501
2502   return DAG.getStore(Chain, dl, Arg, PtrOff,
2503                       MachinePointerInfo::getStack(LocMemOffset),
2504                       false, false, 0);
2505 }
2506
2507 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2508 /// optimization is performed and it is required.
2509 SDValue
2510 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2511                                            SDValue &OutRetAddr, SDValue Chain,
2512                                            bool IsTailCall, bool Is64Bit,
2513                                            int FPDiff, SDLoc dl) const {
2514   // Adjust the Return address stack slot.
2515   EVT VT = getPointerTy();
2516   OutRetAddr = getReturnAddressFrameIndex(DAG);
2517
2518   // Load the "old" Return address.
2519   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2520                            false, false, false, 0);
2521   return SDValue(OutRetAddr.getNode(), 1);
2522 }
2523
2524 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2525 /// optimization is performed and it is required (FPDiff!=0).
2526 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2527                                         SDValue Chain, SDValue RetAddrFrIdx,
2528                                         EVT PtrVT, unsigned SlotSize,
2529                                         int FPDiff, SDLoc dl) {
2530   // Store the return address to the appropriate stack slot.
2531   if (!FPDiff) return Chain;
2532   // Calculate the new stack slot for the return address.
2533   int NewReturnAddrFI =
2534     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2535                                          false);
2536   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2537   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2538                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2539                        false, false, 0);
2540   return Chain;
2541 }
2542
2543 SDValue
2544 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2545                              SmallVectorImpl<SDValue> &InVals) const {
2546   SelectionDAG &DAG                     = CLI.DAG;
2547   SDLoc &dl                             = CLI.DL;
2548   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2549   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2550   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2551   SDValue Chain                         = CLI.Chain;
2552   SDValue Callee                        = CLI.Callee;
2553   CallingConv::ID CallConv              = CLI.CallConv;
2554   bool &isTailCall                      = CLI.IsTailCall;
2555   bool isVarArg                         = CLI.IsVarArg;
2556
2557   MachineFunction &MF = DAG.getMachineFunction();
2558   bool Is64Bit        = Subtarget->is64Bit();
2559   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2560   StructReturnType SR = callIsStructReturn(Outs);
2561   bool IsSibcall      = false;
2562
2563   if (MF.getTarget().Options.DisableTailCalls)
2564     isTailCall = false;
2565
2566   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2567   if (IsMustTail) {
2568     // Force this to be a tail call.  The verifier rules are enough to ensure
2569     // that we can lower this successfully without moving the return address
2570     // around.
2571     isTailCall = true;
2572   } else if (isTailCall) {
2573     // Check if it's really possible to do a tail call.
2574     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2575                     isVarArg, SR != NotStructReturn,
2576                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2577                     Outs, OutVals, Ins, DAG);
2578
2579     // Sibcalls are automatically detected tailcalls which do not require
2580     // ABI changes.
2581     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2582       IsSibcall = true;
2583
2584     if (isTailCall)
2585       ++NumTailCalls;
2586   }
2587
2588   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2589          "Var args not supported with calling convention fastcc, ghc or hipe");
2590
2591   // Analyze operands of the call, assigning locations to each operand.
2592   SmallVector<CCValAssign, 16> ArgLocs;
2593   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2594                  ArgLocs, *DAG.getContext());
2595
2596   // Allocate shadow area for Win64
2597   if (IsWin64)
2598     CCInfo.AllocateStack(32, 8);
2599
2600   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2601
2602   // Get a count of how many bytes are to be pushed on the stack.
2603   unsigned NumBytes = CCInfo.getNextStackOffset();
2604   if (IsSibcall)
2605     // This is a sibcall. The memory operands are available in caller's
2606     // own caller's stack.
2607     NumBytes = 0;
2608   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2609            IsTailCallConvention(CallConv))
2610     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2611
2612   int FPDiff = 0;
2613   if (isTailCall && !IsSibcall && !IsMustTail) {
2614     // Lower arguments at fp - stackoffset + fpdiff.
2615     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2616     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2617
2618     FPDiff = NumBytesCallerPushed - NumBytes;
2619
2620     // Set the delta of movement of the returnaddr stackslot.
2621     // But only set if delta is greater than previous delta.
2622     if (FPDiff < X86Info->getTCReturnAddrDelta())
2623       X86Info->setTCReturnAddrDelta(FPDiff);
2624   }
2625
2626   unsigned NumBytesToPush = NumBytes;
2627   unsigned NumBytesToPop = NumBytes;
2628
2629   // If we have an inalloca argument, all stack space has already been allocated
2630   // for us and be right at the top of the stack.  We don't support multiple
2631   // arguments passed in memory when using inalloca.
2632   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2633     NumBytesToPush = 0;
2634     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2635            "an inalloca argument must be the only memory argument");
2636   }
2637
2638   if (!IsSibcall)
2639     Chain = DAG.getCALLSEQ_START(
2640         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2641
2642   SDValue RetAddrFrIdx;
2643   // Load return address for tail calls.
2644   if (isTailCall && FPDiff)
2645     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2646                                     Is64Bit, FPDiff, dl);
2647
2648   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2649   SmallVector<SDValue, 8> MemOpChains;
2650   SDValue StackPtr;
2651
2652   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2653   // of tail call optimization arguments are handle later.
2654   const X86RegisterInfo *RegInfo =
2655     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2656   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2657     // Skip inalloca arguments, they have already been written.
2658     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2659     if (Flags.isInAlloca())
2660       continue;
2661
2662     CCValAssign &VA = ArgLocs[i];
2663     EVT RegVT = VA.getLocVT();
2664     SDValue Arg = OutVals[i];
2665     bool isByVal = Flags.isByVal();
2666
2667     // Promote the value if needed.
2668     switch (VA.getLocInfo()) {
2669     default: llvm_unreachable("Unknown loc info!");
2670     case CCValAssign::Full: break;
2671     case CCValAssign::SExt:
2672       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2673       break;
2674     case CCValAssign::ZExt:
2675       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2676       break;
2677     case CCValAssign::AExt:
2678       if (RegVT.is128BitVector()) {
2679         // Special case: passing MMX values in XMM registers.
2680         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2681         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2682         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2683       } else
2684         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2685       break;
2686     case CCValAssign::BCvt:
2687       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2688       break;
2689     case CCValAssign::Indirect: {
2690       // Store the argument.
2691       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2692       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2693       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2694                            MachinePointerInfo::getFixedStack(FI),
2695                            false, false, 0);
2696       Arg = SpillSlot;
2697       break;
2698     }
2699     }
2700
2701     if (VA.isRegLoc()) {
2702       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2703       if (isVarArg && IsWin64) {
2704         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2705         // shadow reg if callee is a varargs function.
2706         unsigned ShadowReg = 0;
2707         switch (VA.getLocReg()) {
2708         case X86::XMM0: ShadowReg = X86::RCX; break;
2709         case X86::XMM1: ShadowReg = X86::RDX; break;
2710         case X86::XMM2: ShadowReg = X86::R8; break;
2711         case X86::XMM3: ShadowReg = X86::R9; break;
2712         }
2713         if (ShadowReg)
2714           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2715       }
2716     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2717       assert(VA.isMemLoc());
2718       if (!StackPtr.getNode())
2719         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2720                                       getPointerTy());
2721       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2722                                              dl, DAG, VA, Flags));
2723     }
2724   }
2725
2726   if (!MemOpChains.empty())
2727     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2728
2729   if (Subtarget->isPICStyleGOT()) {
2730     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2731     // GOT pointer.
2732     if (!isTailCall) {
2733       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2734                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2735     } else {
2736       // If we are tail calling and generating PIC/GOT style code load the
2737       // address of the callee into ECX. The value in ecx is used as target of
2738       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2739       // for tail calls on PIC/GOT architectures. Normally we would just put the
2740       // address of GOT into ebx and then call target@PLT. But for tail calls
2741       // ebx would be restored (since ebx is callee saved) before jumping to the
2742       // target@PLT.
2743
2744       // Note: The actual moving to ECX is done further down.
2745       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2746       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2747           !G->getGlobal()->hasProtectedVisibility())
2748         Callee = LowerGlobalAddress(Callee, DAG);
2749       else if (isa<ExternalSymbolSDNode>(Callee))
2750         Callee = LowerExternalSymbol(Callee, DAG);
2751     }
2752   }
2753
2754   if (Is64Bit && isVarArg && !IsWin64) {
2755     // From AMD64 ABI document:
2756     // For calls that may call functions that use varargs or stdargs
2757     // (prototype-less calls or calls to functions containing ellipsis (...) in
2758     // the declaration) %al is used as hidden argument to specify the number
2759     // of SSE registers used. The contents of %al do not need to match exactly
2760     // the number of registers, but must be an ubound on the number of SSE
2761     // registers used and is in the range 0 - 8 inclusive.
2762
2763     // Count the number of XMM registers allocated.
2764     static const MCPhysReg XMMArgRegs[] = {
2765       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2766       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2767     };
2768     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2769     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2770            && "SSE registers cannot be used when SSE is disabled");
2771
2772     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2773                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2774   }
2775
2776   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2777   // don't need this because the eligibility check rejects calls that require
2778   // shuffling arguments passed in memory.
2779   if (!IsSibcall && isTailCall) {
2780     // Force all the incoming stack arguments to be loaded from the stack
2781     // before any new outgoing arguments are stored to the stack, because the
2782     // outgoing stack slots may alias the incoming argument stack slots, and
2783     // the alias isn't otherwise explicit. This is slightly more conservative
2784     // than necessary, because it means that each store effectively depends
2785     // on every argument instead of just those arguments it would clobber.
2786     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2787
2788     SmallVector<SDValue, 8> MemOpChains2;
2789     SDValue FIN;
2790     int FI = 0;
2791     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2792       CCValAssign &VA = ArgLocs[i];
2793       if (VA.isRegLoc())
2794         continue;
2795       assert(VA.isMemLoc());
2796       SDValue Arg = OutVals[i];
2797       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2798       // Skip inalloca arguments.  They don't require any work.
2799       if (Flags.isInAlloca())
2800         continue;
2801       // Create frame index.
2802       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2803       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2804       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2805       FIN = DAG.getFrameIndex(FI, getPointerTy());
2806
2807       if (Flags.isByVal()) {
2808         // Copy relative to framepointer.
2809         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2810         if (!StackPtr.getNode())
2811           StackPtr = DAG.getCopyFromReg(Chain, dl,
2812                                         RegInfo->getStackRegister(),
2813                                         getPointerTy());
2814         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2815
2816         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2817                                                          ArgChain,
2818                                                          Flags, DAG, dl));
2819       } else {
2820         // Store relative to framepointer.
2821         MemOpChains2.push_back(
2822           DAG.getStore(ArgChain, dl, Arg, FIN,
2823                        MachinePointerInfo::getFixedStack(FI),
2824                        false, false, 0));
2825       }
2826     }
2827
2828     if (!MemOpChains2.empty())
2829       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2830
2831     // Store the return address to the appropriate stack slot.
2832     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2833                                      getPointerTy(), RegInfo->getSlotSize(),
2834                                      FPDiff, dl);
2835   }
2836
2837   // Build a sequence of copy-to-reg nodes chained together with token chain
2838   // and flag operands which copy the outgoing args into registers.
2839   SDValue InFlag;
2840   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2841     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2842                              RegsToPass[i].second, InFlag);
2843     InFlag = Chain.getValue(1);
2844   }
2845
2846   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2847     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2848     // In the 64-bit large code model, we have to make all calls
2849     // through a register, since the call instruction's 32-bit
2850     // pc-relative offset may not be large enough to hold the whole
2851     // address.
2852   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2853     // If the callee is a GlobalAddress node (quite common, every direct call
2854     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2855     // it.
2856
2857     // We should use extra load for direct calls to dllimported functions in
2858     // non-JIT mode.
2859     const GlobalValue *GV = G->getGlobal();
2860     if (!GV->hasDLLImportStorageClass()) {
2861       unsigned char OpFlags = 0;
2862       bool ExtraLoad = false;
2863       unsigned WrapperKind = ISD::DELETED_NODE;
2864
2865       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2866       // external symbols most go through the PLT in PIC mode.  If the symbol
2867       // has hidden or protected visibility, or if it is static or local, then
2868       // we don't need to use the PLT - we can directly call it.
2869       if (Subtarget->isTargetELF() &&
2870           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2871           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2872         OpFlags = X86II::MO_PLT;
2873       } else if (Subtarget->isPICStyleStubAny() &&
2874                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2875                  (!Subtarget->getTargetTriple().isMacOSX() ||
2876                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2877         // PC-relative references to external symbols should go through $stub,
2878         // unless we're building with the leopard linker or later, which
2879         // automatically synthesizes these stubs.
2880         OpFlags = X86II::MO_DARWIN_STUB;
2881       } else if (Subtarget->isPICStyleRIPRel() &&
2882                  isa<Function>(GV) &&
2883                  cast<Function>(GV)->getAttributes().
2884                    hasAttribute(AttributeSet::FunctionIndex,
2885                                 Attribute::NonLazyBind)) {
2886         // If the function is marked as non-lazy, generate an indirect call
2887         // which loads from the GOT directly. This avoids runtime overhead
2888         // at the cost of eager binding (and one extra byte of encoding).
2889         OpFlags = X86II::MO_GOTPCREL;
2890         WrapperKind = X86ISD::WrapperRIP;
2891         ExtraLoad = true;
2892       }
2893
2894       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2895                                           G->getOffset(), OpFlags);
2896
2897       // Add a wrapper if needed.
2898       if (WrapperKind != ISD::DELETED_NODE)
2899         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2900       // Add extra indirection if needed.
2901       if (ExtraLoad)
2902         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2903                              MachinePointerInfo::getGOT(),
2904                              false, false, false, 0);
2905     }
2906   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2907     unsigned char OpFlags = 0;
2908
2909     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2910     // external symbols should go through the PLT.
2911     if (Subtarget->isTargetELF() &&
2912         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2913       OpFlags = X86II::MO_PLT;
2914     } else if (Subtarget->isPICStyleStubAny() &&
2915                (!Subtarget->getTargetTriple().isMacOSX() ||
2916                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2917       // PC-relative references to external symbols should go through $stub,
2918       // unless we're building with the leopard linker or later, which
2919       // automatically synthesizes these stubs.
2920       OpFlags = X86II::MO_DARWIN_STUB;
2921     }
2922
2923     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2924                                          OpFlags);
2925   }
2926
2927   // Returns a chain & a flag for retval copy to use.
2928   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2929   SmallVector<SDValue, 8> Ops;
2930
2931   if (!IsSibcall && isTailCall) {
2932     Chain = DAG.getCALLSEQ_END(Chain,
2933                                DAG.getIntPtrConstant(NumBytesToPop, true),
2934                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2935     InFlag = Chain.getValue(1);
2936   }
2937
2938   Ops.push_back(Chain);
2939   Ops.push_back(Callee);
2940
2941   if (isTailCall)
2942     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2943
2944   // Add argument registers to the end of the list so that they are known live
2945   // into the call.
2946   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2947     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2948                                   RegsToPass[i].second.getValueType()));
2949
2950   // Add a register mask operand representing the call-preserved registers.
2951   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2952   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2953   assert(Mask && "Missing call preserved mask for calling convention");
2954   Ops.push_back(DAG.getRegisterMask(Mask));
2955
2956   if (InFlag.getNode())
2957     Ops.push_back(InFlag);
2958
2959   if (isTailCall) {
2960     // We used to do:
2961     //// If this is the first return lowered for this function, add the regs
2962     //// to the liveout set for the function.
2963     // This isn't right, although it's probably harmless on x86; liveouts
2964     // should be computed from returns not tail calls.  Consider a void
2965     // function making a tail call to a function returning int.
2966     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2967   }
2968
2969   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2970   InFlag = Chain.getValue(1);
2971
2972   // Create the CALLSEQ_END node.
2973   unsigned NumBytesForCalleeToPop;
2974   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2975                        DAG.getTarget().Options.GuaranteedTailCallOpt))
2976     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2977   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2978            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2979            SR == StackStructReturn)
2980     // If this is a call to a struct-return function, the callee
2981     // pops the hidden struct pointer, so we have to push it back.
2982     // This is common for Darwin/X86, Linux & Mingw32 targets.
2983     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2984     NumBytesForCalleeToPop = 4;
2985   else
2986     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2987
2988   // Returns a flag for retval copy to use.
2989   if (!IsSibcall) {
2990     Chain = DAG.getCALLSEQ_END(Chain,
2991                                DAG.getIntPtrConstant(NumBytesToPop, true),
2992                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2993                                                      true),
2994                                InFlag, dl);
2995     InFlag = Chain.getValue(1);
2996   }
2997
2998   // Handle result values, copying them out of physregs into vregs that we
2999   // return.
3000   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3001                          Ins, dl, DAG, InVals);
3002 }
3003
3004 //===----------------------------------------------------------------------===//
3005 //                Fast Calling Convention (tail call) implementation
3006 //===----------------------------------------------------------------------===//
3007
3008 //  Like std call, callee cleans arguments, convention except that ECX is
3009 //  reserved for storing the tail called function address. Only 2 registers are
3010 //  free for argument passing (inreg). Tail call optimization is performed
3011 //  provided:
3012 //                * tailcallopt is enabled
3013 //                * caller/callee are fastcc
3014 //  On X86_64 architecture with GOT-style position independent code only local
3015 //  (within module) calls are supported at the moment.
3016 //  To keep the stack aligned according to platform abi the function
3017 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3018 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3019 //  If a tail called function callee has more arguments than the caller the
3020 //  caller needs to make sure that there is room to move the RETADDR to. This is
3021 //  achieved by reserving an area the size of the argument delta right after the
3022 //  original REtADDR, but before the saved framepointer or the spilled registers
3023 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3024 //  stack layout:
3025 //    arg1
3026 //    arg2
3027 //    RETADDR
3028 //    [ new RETADDR
3029 //      move area ]
3030 //    (possible EBP)
3031 //    ESI
3032 //    EDI
3033 //    local1 ..
3034
3035 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3036 /// for a 16 byte align requirement.
3037 unsigned
3038 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3039                                                SelectionDAG& DAG) const {
3040   MachineFunction &MF = DAG.getMachineFunction();
3041   const TargetMachine &TM = MF.getTarget();
3042   const X86RegisterInfo *RegInfo =
3043     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3044   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3045   unsigned StackAlignment = TFI.getStackAlignment();
3046   uint64_t AlignMask = StackAlignment - 1;
3047   int64_t Offset = StackSize;
3048   unsigned SlotSize = RegInfo->getSlotSize();
3049   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3050     // Number smaller than 12 so just add the difference.
3051     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3052   } else {
3053     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3054     Offset = ((~AlignMask) & Offset) + StackAlignment +
3055       (StackAlignment-SlotSize);
3056   }
3057   return Offset;
3058 }
3059
3060 /// MatchingStackOffset - Return true if the given stack call argument is
3061 /// already available in the same position (relatively) of the caller's
3062 /// incoming argument stack.
3063 static
3064 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3065                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3066                          const X86InstrInfo *TII) {
3067   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3068   int FI = INT_MAX;
3069   if (Arg.getOpcode() == ISD::CopyFromReg) {
3070     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3071     if (!TargetRegisterInfo::isVirtualRegister(VR))
3072       return false;
3073     MachineInstr *Def = MRI->getVRegDef(VR);
3074     if (!Def)
3075       return false;
3076     if (!Flags.isByVal()) {
3077       if (!TII->isLoadFromStackSlot(Def, FI))
3078         return false;
3079     } else {
3080       unsigned Opcode = Def->getOpcode();
3081       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3082           Def->getOperand(1).isFI()) {
3083         FI = Def->getOperand(1).getIndex();
3084         Bytes = Flags.getByValSize();
3085       } else
3086         return false;
3087     }
3088   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3089     if (Flags.isByVal())
3090       // ByVal argument is passed in as a pointer but it's now being
3091       // dereferenced. e.g.
3092       // define @foo(%struct.X* %A) {
3093       //   tail call @bar(%struct.X* byval %A)
3094       // }
3095       return false;
3096     SDValue Ptr = Ld->getBasePtr();
3097     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3098     if (!FINode)
3099       return false;
3100     FI = FINode->getIndex();
3101   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3102     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3103     FI = FINode->getIndex();
3104     Bytes = Flags.getByValSize();
3105   } else
3106     return false;
3107
3108   assert(FI != INT_MAX);
3109   if (!MFI->isFixedObjectIndex(FI))
3110     return false;
3111   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3112 }
3113
3114 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3115 /// for tail call optimization. Targets which want to do tail call
3116 /// optimization should implement this function.
3117 bool
3118 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3119                                                      CallingConv::ID CalleeCC,
3120                                                      bool isVarArg,
3121                                                      bool isCalleeStructRet,
3122                                                      bool isCallerStructRet,
3123                                                      Type *RetTy,
3124                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3125                                     const SmallVectorImpl<SDValue> &OutVals,
3126                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3127                                                      SelectionDAG &DAG) const {
3128   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3129     return false;
3130
3131   // If -tailcallopt is specified, make fastcc functions tail-callable.
3132   const MachineFunction &MF = DAG.getMachineFunction();
3133   const Function *CallerF = MF.getFunction();
3134
3135   // If the function return type is x86_fp80 and the callee return type is not,
3136   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3137   // perform a tailcall optimization here.
3138   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3139     return false;
3140
3141   CallingConv::ID CallerCC = CallerF->getCallingConv();
3142   bool CCMatch = CallerCC == CalleeCC;
3143   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3144   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3145
3146   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3147     if (IsTailCallConvention(CalleeCC) && CCMatch)
3148       return true;
3149     return false;
3150   }
3151
3152   // Look for obvious safe cases to perform tail call optimization that do not
3153   // require ABI changes. This is what gcc calls sibcall.
3154
3155   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3156   // emit a special epilogue.
3157   const X86RegisterInfo *RegInfo =
3158     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3159   if (RegInfo->needsStackRealignment(MF))
3160     return false;
3161
3162   // Also avoid sibcall optimization if either caller or callee uses struct
3163   // return semantics.
3164   if (isCalleeStructRet || isCallerStructRet)
3165     return false;
3166
3167   // An stdcall/thiscall caller is expected to clean up its arguments; the
3168   // callee isn't going to do that.
3169   // FIXME: this is more restrictive than needed. We could produce a tailcall
3170   // when the stack adjustment matches. For example, with a thiscall that takes
3171   // only one argument.
3172   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3173                    CallerCC == CallingConv::X86_ThisCall))
3174     return false;
3175
3176   // Do not sibcall optimize vararg calls unless all arguments are passed via
3177   // registers.
3178   if (isVarArg && !Outs.empty()) {
3179
3180     // Optimizing for varargs on Win64 is unlikely to be safe without
3181     // additional testing.
3182     if (IsCalleeWin64 || IsCallerWin64)
3183       return false;
3184
3185     SmallVector<CCValAssign, 16> ArgLocs;
3186     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3187                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3188
3189     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3190     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3191       if (!ArgLocs[i].isRegLoc())
3192         return false;
3193   }
3194
3195   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3196   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3197   // this into a sibcall.
3198   bool Unused = false;
3199   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3200     if (!Ins[i].Used) {
3201       Unused = true;
3202       break;
3203     }
3204   }
3205   if (Unused) {
3206     SmallVector<CCValAssign, 16> RVLocs;
3207     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3208                    DAG.getTarget(), RVLocs, *DAG.getContext());
3209     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3210     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3211       CCValAssign &VA = RVLocs[i];
3212       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3213         return false;
3214     }
3215   }
3216
3217   // If the calling conventions do not match, then we'd better make sure the
3218   // results are returned in the same way as what the caller expects.
3219   if (!CCMatch) {
3220     SmallVector<CCValAssign, 16> RVLocs1;
3221     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3222                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3223     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3224
3225     SmallVector<CCValAssign, 16> RVLocs2;
3226     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3227                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3228     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3229
3230     if (RVLocs1.size() != RVLocs2.size())
3231       return false;
3232     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3233       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3234         return false;
3235       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3236         return false;
3237       if (RVLocs1[i].isRegLoc()) {
3238         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3239           return false;
3240       } else {
3241         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3242           return false;
3243       }
3244     }
3245   }
3246
3247   // If the callee takes no arguments then go on to check the results of the
3248   // call.
3249   if (!Outs.empty()) {
3250     // Check if stack adjustment is needed. For now, do not do this if any
3251     // argument is passed on the stack.
3252     SmallVector<CCValAssign, 16> ArgLocs;
3253     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3254                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3255
3256     // Allocate shadow area for Win64
3257     if (IsCalleeWin64)
3258       CCInfo.AllocateStack(32, 8);
3259
3260     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3261     if (CCInfo.getNextStackOffset()) {
3262       MachineFunction &MF = DAG.getMachineFunction();
3263       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3264         return false;
3265
3266       // Check if the arguments are already laid out in the right way as
3267       // the caller's fixed stack objects.
3268       MachineFrameInfo *MFI = MF.getFrameInfo();
3269       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3270       const X86InstrInfo *TII =
3271           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3272       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3273         CCValAssign &VA = ArgLocs[i];
3274         SDValue Arg = OutVals[i];
3275         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3276         if (VA.getLocInfo() == CCValAssign::Indirect)
3277           return false;
3278         if (!VA.isRegLoc()) {
3279           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3280                                    MFI, MRI, TII))
3281             return false;
3282         }
3283       }
3284     }
3285
3286     // If the tailcall address may be in a register, then make sure it's
3287     // possible to register allocate for it. In 32-bit, the call address can
3288     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3289     // callee-saved registers are restored. These happen to be the same
3290     // registers used to pass 'inreg' arguments so watch out for those.
3291     if (!Subtarget->is64Bit() &&
3292         ((!isa<GlobalAddressSDNode>(Callee) &&
3293           !isa<ExternalSymbolSDNode>(Callee)) ||
3294          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3295       unsigned NumInRegs = 0;
3296       // In PIC we need an extra register to formulate the address computation
3297       // for the callee.
3298       unsigned MaxInRegs =
3299         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3300
3301       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3302         CCValAssign &VA = ArgLocs[i];
3303         if (!VA.isRegLoc())
3304           continue;
3305         unsigned Reg = VA.getLocReg();
3306         switch (Reg) {
3307         default: break;
3308         case X86::EAX: case X86::EDX: case X86::ECX:
3309           if (++NumInRegs == MaxInRegs)
3310             return false;
3311           break;
3312         }
3313       }
3314     }
3315   }
3316
3317   return true;
3318 }
3319
3320 FastISel *
3321 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3322                                   const TargetLibraryInfo *libInfo) const {
3323   return X86::createFastISel(funcInfo, libInfo);
3324 }
3325
3326 //===----------------------------------------------------------------------===//
3327 //                           Other Lowering Hooks
3328 //===----------------------------------------------------------------------===//
3329
3330 static bool MayFoldLoad(SDValue Op) {
3331   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3332 }
3333
3334 static bool MayFoldIntoStore(SDValue Op) {
3335   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3336 }
3337
3338 static bool isTargetShuffle(unsigned Opcode) {
3339   switch(Opcode) {
3340   default: return false;
3341   case X86ISD::PSHUFD:
3342   case X86ISD::PSHUFHW:
3343   case X86ISD::PSHUFLW:
3344   case X86ISD::SHUFP:
3345   case X86ISD::PALIGNR:
3346   case X86ISD::MOVLHPS:
3347   case X86ISD::MOVLHPD:
3348   case X86ISD::MOVHLPS:
3349   case X86ISD::MOVLPS:
3350   case X86ISD::MOVLPD:
3351   case X86ISD::MOVSHDUP:
3352   case X86ISD::MOVSLDUP:
3353   case X86ISD::MOVDDUP:
3354   case X86ISD::MOVSS:
3355   case X86ISD::MOVSD:
3356   case X86ISD::UNPCKL:
3357   case X86ISD::UNPCKH:
3358   case X86ISD::VPERMILP:
3359   case X86ISD::VPERM2X128:
3360   case X86ISD::VPERMI:
3361     return true;
3362   }
3363 }
3364
3365 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3366                                     SDValue V1, SelectionDAG &DAG) {
3367   switch(Opc) {
3368   default: llvm_unreachable("Unknown x86 shuffle node");
3369   case X86ISD::MOVSHDUP:
3370   case X86ISD::MOVSLDUP:
3371   case X86ISD::MOVDDUP:
3372     return DAG.getNode(Opc, dl, VT, V1);
3373   }
3374 }
3375
3376 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3377                                     SDValue V1, unsigned TargetMask,
3378                                     SelectionDAG &DAG) {
3379   switch(Opc) {
3380   default: llvm_unreachable("Unknown x86 shuffle node");
3381   case X86ISD::PSHUFD:
3382   case X86ISD::PSHUFHW:
3383   case X86ISD::PSHUFLW:
3384   case X86ISD::VPERMILP:
3385   case X86ISD::VPERMI:
3386     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3387   }
3388 }
3389
3390 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3391                                     SDValue V1, SDValue V2, unsigned TargetMask,
3392                                     SelectionDAG &DAG) {
3393   switch(Opc) {
3394   default: llvm_unreachable("Unknown x86 shuffle node");
3395   case X86ISD::PALIGNR:
3396   case X86ISD::SHUFP:
3397   case X86ISD::VPERM2X128:
3398     return DAG.getNode(Opc, dl, VT, V1, V2,
3399                        DAG.getConstant(TargetMask, MVT::i8));
3400   }
3401 }
3402
3403 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3404                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3405   switch(Opc) {
3406   default: llvm_unreachable("Unknown x86 shuffle node");
3407   case X86ISD::MOVLHPS:
3408   case X86ISD::MOVLHPD:
3409   case X86ISD::MOVHLPS:
3410   case X86ISD::MOVLPS:
3411   case X86ISD::MOVLPD:
3412   case X86ISD::MOVSS:
3413   case X86ISD::MOVSD:
3414   case X86ISD::UNPCKL:
3415   case X86ISD::UNPCKH:
3416     return DAG.getNode(Opc, dl, VT, V1, V2);
3417   }
3418 }
3419
3420 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3421   MachineFunction &MF = DAG.getMachineFunction();
3422   const X86RegisterInfo *RegInfo =
3423     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3424   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3425   int ReturnAddrIndex = FuncInfo->getRAIndex();
3426
3427   if (ReturnAddrIndex == 0) {
3428     // Set up a frame object for the return address.
3429     unsigned SlotSize = RegInfo->getSlotSize();
3430     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3431                                                            -(int64_t)SlotSize,
3432                                                            false);
3433     FuncInfo->setRAIndex(ReturnAddrIndex);
3434   }
3435
3436   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3437 }
3438
3439 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3440                                        bool hasSymbolicDisplacement) {
3441   // Offset should fit into 32 bit immediate field.
3442   if (!isInt<32>(Offset))
3443     return false;
3444
3445   // If we don't have a symbolic displacement - we don't have any extra
3446   // restrictions.
3447   if (!hasSymbolicDisplacement)
3448     return true;
3449
3450   // FIXME: Some tweaks might be needed for medium code model.
3451   if (M != CodeModel::Small && M != CodeModel::Kernel)
3452     return false;
3453
3454   // For small code model we assume that latest object is 16MB before end of 31
3455   // bits boundary. We may also accept pretty large negative constants knowing
3456   // that all objects are in the positive half of address space.
3457   if (M == CodeModel::Small && Offset < 16*1024*1024)
3458     return true;
3459
3460   // For kernel code model we know that all object resist in the negative half
3461   // of 32bits address space. We may not accept negative offsets, since they may
3462   // be just off and we may accept pretty large positive ones.
3463   if (M == CodeModel::Kernel && Offset > 0)
3464     return true;
3465
3466   return false;
3467 }
3468
3469 /// isCalleePop - Determines whether the callee is required to pop its
3470 /// own arguments. Callee pop is necessary to support tail calls.
3471 bool X86::isCalleePop(CallingConv::ID CallingConv,
3472                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3473   if (IsVarArg)
3474     return false;
3475
3476   switch (CallingConv) {
3477   default:
3478     return false;
3479   case CallingConv::X86_StdCall:
3480     return !is64Bit;
3481   case CallingConv::X86_FastCall:
3482     return !is64Bit;
3483   case CallingConv::X86_ThisCall:
3484     return !is64Bit;
3485   case CallingConv::Fast:
3486     return TailCallOpt;
3487   case CallingConv::GHC:
3488     return TailCallOpt;
3489   case CallingConv::HiPE:
3490     return TailCallOpt;
3491   }
3492 }
3493
3494 /// \brief Return true if the condition is an unsigned comparison operation.
3495 static bool isX86CCUnsigned(unsigned X86CC) {
3496   switch (X86CC) {
3497   default: llvm_unreachable("Invalid integer condition!");
3498   case X86::COND_E:     return true;
3499   case X86::COND_G:     return false;
3500   case X86::COND_GE:    return false;
3501   case X86::COND_L:     return false;
3502   case X86::COND_LE:    return false;
3503   case X86::COND_NE:    return true;
3504   case X86::COND_B:     return true;
3505   case X86::COND_A:     return true;
3506   case X86::COND_BE:    return true;
3507   case X86::COND_AE:    return true;
3508   }
3509   llvm_unreachable("covered switch fell through?!");
3510 }
3511
3512 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3513 /// specific condition code, returning the condition code and the LHS/RHS of the
3514 /// comparison to make.
3515 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3516                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3517   if (!isFP) {
3518     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3519       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3520         // X > -1   -> X == 0, jump !sign.
3521         RHS = DAG.getConstant(0, RHS.getValueType());
3522         return X86::COND_NS;
3523       }
3524       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3525         // X < 0   -> X == 0, jump on sign.
3526         return X86::COND_S;
3527       }
3528       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3529         // X < 1   -> X <= 0
3530         RHS = DAG.getConstant(0, RHS.getValueType());
3531         return X86::COND_LE;
3532       }
3533     }
3534
3535     switch (SetCCOpcode) {
3536     default: llvm_unreachable("Invalid integer condition!");
3537     case ISD::SETEQ:  return X86::COND_E;
3538     case ISD::SETGT:  return X86::COND_G;
3539     case ISD::SETGE:  return X86::COND_GE;
3540     case ISD::SETLT:  return X86::COND_L;
3541     case ISD::SETLE:  return X86::COND_LE;
3542     case ISD::SETNE:  return X86::COND_NE;
3543     case ISD::SETULT: return X86::COND_B;
3544     case ISD::SETUGT: return X86::COND_A;
3545     case ISD::SETULE: return X86::COND_BE;
3546     case ISD::SETUGE: return X86::COND_AE;
3547     }
3548   }
3549
3550   // First determine if it is required or is profitable to flip the operands.
3551
3552   // If LHS is a foldable load, but RHS is not, flip the condition.
3553   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3554       !ISD::isNON_EXTLoad(RHS.getNode())) {
3555     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3556     std::swap(LHS, RHS);
3557   }
3558
3559   switch (SetCCOpcode) {
3560   default: break;
3561   case ISD::SETOLT:
3562   case ISD::SETOLE:
3563   case ISD::SETUGT:
3564   case ISD::SETUGE:
3565     std::swap(LHS, RHS);
3566     break;
3567   }
3568
3569   // On a floating point condition, the flags are set as follows:
3570   // ZF  PF  CF   op
3571   //  0 | 0 | 0 | X > Y
3572   //  0 | 0 | 1 | X < Y
3573   //  1 | 0 | 0 | X == Y
3574   //  1 | 1 | 1 | unordered
3575   switch (SetCCOpcode) {
3576   default: llvm_unreachable("Condcode should be pre-legalized away");
3577   case ISD::SETUEQ:
3578   case ISD::SETEQ:   return X86::COND_E;
3579   case ISD::SETOLT:              // flipped
3580   case ISD::SETOGT:
3581   case ISD::SETGT:   return X86::COND_A;
3582   case ISD::SETOLE:              // flipped
3583   case ISD::SETOGE:
3584   case ISD::SETGE:   return X86::COND_AE;
3585   case ISD::SETUGT:              // flipped
3586   case ISD::SETULT:
3587   case ISD::SETLT:   return X86::COND_B;
3588   case ISD::SETUGE:              // flipped
3589   case ISD::SETULE:
3590   case ISD::SETLE:   return X86::COND_BE;
3591   case ISD::SETONE:
3592   case ISD::SETNE:   return X86::COND_NE;
3593   case ISD::SETUO:   return X86::COND_P;
3594   case ISD::SETO:    return X86::COND_NP;
3595   case ISD::SETOEQ:
3596   case ISD::SETUNE:  return X86::COND_INVALID;
3597   }
3598 }
3599
3600 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3601 /// code. Current x86 isa includes the following FP cmov instructions:
3602 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3603 static bool hasFPCMov(unsigned X86CC) {
3604   switch (X86CC) {
3605   default:
3606     return false;
3607   case X86::COND_B:
3608   case X86::COND_BE:
3609   case X86::COND_E:
3610   case X86::COND_P:
3611   case X86::COND_A:
3612   case X86::COND_AE:
3613   case X86::COND_NE:
3614   case X86::COND_NP:
3615     return true;
3616   }
3617 }
3618
3619 /// isFPImmLegal - Returns true if the target can instruction select the
3620 /// specified FP immediate natively. If false, the legalizer will
3621 /// materialize the FP immediate as a load from a constant pool.
3622 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3623   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3624     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3625       return true;
3626   }
3627   return false;
3628 }
3629
3630 /// \brief Returns true if it is beneficial to convert a load of a constant
3631 /// to just the constant itself.
3632 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3633                                                           Type *Ty) const {
3634   assert(Ty->isIntegerTy());
3635
3636   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3637   if (BitSize == 0 || BitSize > 64)
3638     return false;
3639   return true;
3640 }
3641
3642 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3643 /// the specified range (L, H].
3644 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3645   return (Val < 0) || (Val >= Low && Val < Hi);
3646 }
3647
3648 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3649 /// specified value.
3650 static bool isUndefOrEqual(int Val, int CmpVal) {
3651   return (Val < 0 || Val == CmpVal);
3652 }
3653
3654 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3655 /// from position Pos and ending in Pos+Size, falls within the specified
3656 /// sequential range (L, L+Pos]. or is undef.
3657 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3658                                        unsigned Pos, unsigned Size, int Low) {
3659   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3660     if (!isUndefOrEqual(Mask[i], Low))
3661       return false;
3662   return true;
3663 }
3664
3665 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3666 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3667 /// the second operand.
3668 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3669   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3670     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3671   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3672     return (Mask[0] < 2 && Mask[1] < 2);
3673   return false;
3674 }
3675
3676 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3677 /// is suitable for input to PSHUFHW.
3678 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3679   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3680     return false;
3681
3682   // Lower quadword copied in order or undef.
3683   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3684     return false;
3685
3686   // Upper quadword shuffled.
3687   for (unsigned i = 4; i != 8; ++i)
3688     if (!isUndefOrInRange(Mask[i], 4, 8))
3689       return false;
3690
3691   if (VT == MVT::v16i16) {
3692     // Lower quadword copied in order or undef.
3693     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3694       return false;
3695
3696     // Upper quadword shuffled.
3697     for (unsigned i = 12; i != 16; ++i)
3698       if (!isUndefOrInRange(Mask[i], 12, 16))
3699         return false;
3700   }
3701
3702   return true;
3703 }
3704
3705 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3706 /// is suitable for input to PSHUFLW.
3707 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3708   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3709     return false;
3710
3711   // Upper quadword copied in order.
3712   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3713     return false;
3714
3715   // Lower quadword shuffled.
3716   for (unsigned i = 0; i != 4; ++i)
3717     if (!isUndefOrInRange(Mask[i], 0, 4))
3718       return false;
3719
3720   if (VT == MVT::v16i16) {
3721     // Upper quadword copied in order.
3722     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3723       return false;
3724
3725     // Lower quadword shuffled.
3726     for (unsigned i = 8; i != 12; ++i)
3727       if (!isUndefOrInRange(Mask[i], 8, 12))
3728         return false;
3729   }
3730
3731   return true;
3732 }
3733
3734 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3735 /// is suitable for input to PALIGNR.
3736 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3737                           const X86Subtarget *Subtarget) {
3738   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3739       (VT.is256BitVector() && !Subtarget->hasInt256()))
3740     return false;
3741
3742   unsigned NumElts = VT.getVectorNumElements();
3743   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3744   unsigned NumLaneElts = NumElts/NumLanes;
3745
3746   // Do not handle 64-bit element shuffles with palignr.
3747   if (NumLaneElts == 2)
3748     return false;
3749
3750   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3751     unsigned i;
3752     for (i = 0; i != NumLaneElts; ++i) {
3753       if (Mask[i+l] >= 0)
3754         break;
3755     }
3756
3757     // Lane is all undef, go to next lane
3758     if (i == NumLaneElts)
3759       continue;
3760
3761     int Start = Mask[i+l];
3762
3763     // Make sure its in this lane in one of the sources
3764     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3765         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3766       return false;
3767
3768     // If not lane 0, then we must match lane 0
3769     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3770       return false;
3771
3772     // Correct second source to be contiguous with first source
3773     if (Start >= (int)NumElts)
3774       Start -= NumElts - NumLaneElts;
3775
3776     // Make sure we're shifting in the right direction.
3777     if (Start <= (int)(i+l))
3778       return false;
3779
3780     Start -= i;
3781
3782     // Check the rest of the elements to see if they are consecutive.
3783     for (++i; i != NumLaneElts; ++i) {
3784       int Idx = Mask[i+l];
3785
3786       // Make sure its in this lane
3787       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3788           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3789         return false;
3790
3791       // If not lane 0, then we must match lane 0
3792       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3793         return false;
3794
3795       if (Idx >= (int)NumElts)
3796         Idx -= NumElts - NumLaneElts;
3797
3798       if (!isUndefOrEqual(Idx, Start+i))
3799         return false;
3800
3801     }
3802   }
3803
3804   return true;
3805 }
3806
3807 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3808 /// the two vector operands have swapped position.
3809 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3810                                      unsigned NumElems) {
3811   for (unsigned i = 0; i != NumElems; ++i) {
3812     int idx = Mask[i];
3813     if (idx < 0)
3814       continue;
3815     else if (idx < (int)NumElems)
3816       Mask[i] = idx + NumElems;
3817     else
3818       Mask[i] = idx - NumElems;
3819   }
3820 }
3821
3822 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3823 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3824 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3825 /// reverse of what x86 shuffles want.
3826 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3827
3828   unsigned NumElems = VT.getVectorNumElements();
3829   unsigned NumLanes = VT.getSizeInBits()/128;
3830   unsigned NumLaneElems = NumElems/NumLanes;
3831
3832   if (NumLaneElems != 2 && NumLaneElems != 4)
3833     return false;
3834
3835   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3836   bool symetricMaskRequired =
3837     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3838
3839   // VSHUFPSY divides the resulting vector into 4 chunks.
3840   // The sources are also splitted into 4 chunks, and each destination
3841   // chunk must come from a different source chunk.
3842   //
3843   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3844   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3845   //
3846   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3847   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3848   //
3849   // VSHUFPDY divides the resulting vector into 4 chunks.
3850   // The sources are also splitted into 4 chunks, and each destination
3851   // chunk must come from a different source chunk.
3852   //
3853   //  SRC1 =>      X3       X2       X1       X0
3854   //  SRC2 =>      Y3       Y2       Y1       Y0
3855   //
3856   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3857   //
3858   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3859   unsigned HalfLaneElems = NumLaneElems/2;
3860   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3861     for (unsigned i = 0; i != NumLaneElems; ++i) {
3862       int Idx = Mask[i+l];
3863       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3864       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3865         return false;
3866       // For VSHUFPSY, the mask of the second half must be the same as the
3867       // first but with the appropriate offsets. This works in the same way as
3868       // VPERMILPS works with masks.
3869       if (!symetricMaskRequired || Idx < 0)
3870         continue;
3871       if (MaskVal[i] < 0) {
3872         MaskVal[i] = Idx - l;
3873         continue;
3874       }
3875       if ((signed)(Idx - l) != MaskVal[i])
3876         return false;
3877     }
3878   }
3879
3880   return true;
3881 }
3882
3883 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3884 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3885 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3886   if (!VT.is128BitVector())
3887     return false;
3888
3889   unsigned NumElems = VT.getVectorNumElements();
3890
3891   if (NumElems != 4)
3892     return false;
3893
3894   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3895   return isUndefOrEqual(Mask[0], 6) &&
3896          isUndefOrEqual(Mask[1], 7) &&
3897          isUndefOrEqual(Mask[2], 2) &&
3898          isUndefOrEqual(Mask[3], 3);
3899 }
3900
3901 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3902 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3903 /// <2, 3, 2, 3>
3904 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3905   if (!VT.is128BitVector())
3906     return false;
3907
3908   unsigned NumElems = VT.getVectorNumElements();
3909
3910   if (NumElems != 4)
3911     return false;
3912
3913   return isUndefOrEqual(Mask[0], 2) &&
3914          isUndefOrEqual(Mask[1], 3) &&
3915          isUndefOrEqual(Mask[2], 2) &&
3916          isUndefOrEqual(Mask[3], 3);
3917 }
3918
3919 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3920 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3921 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3922   if (!VT.is128BitVector())
3923     return false;
3924
3925   unsigned NumElems = VT.getVectorNumElements();
3926
3927   if (NumElems != 2 && NumElems != 4)
3928     return false;
3929
3930   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3931     if (!isUndefOrEqual(Mask[i], i + NumElems))
3932       return false;
3933
3934   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3935     if (!isUndefOrEqual(Mask[i], i))
3936       return false;
3937
3938   return true;
3939 }
3940
3941 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3942 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3943 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3944   if (!VT.is128BitVector())
3945     return false;
3946
3947   unsigned NumElems = VT.getVectorNumElements();
3948
3949   if (NumElems != 2 && NumElems != 4)
3950     return false;
3951
3952   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3953     if (!isUndefOrEqual(Mask[i], i))
3954       return false;
3955
3956   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3957     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3958       return false;
3959
3960   return true;
3961 }
3962
3963 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3964 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3965 /// i. e: If all but one element come from the same vector.
3966 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3967   // TODO: Deal with AVX's VINSERTPS
3968   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3969     return false;
3970
3971   unsigned CorrectPosV1 = 0;
3972   unsigned CorrectPosV2 = 0;
3973   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3974     if (Mask[i] == -1) {
3975       ++CorrectPosV1;
3976       ++CorrectPosV2;
3977       continue;
3978     }
3979
3980     if (Mask[i] == i)
3981       ++CorrectPosV1;
3982     else if (Mask[i] == i + 4)
3983       ++CorrectPosV2;
3984   }
3985
3986   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3987     // We have 3 elements (undefs count as elements from any vector) from one
3988     // vector, and one from another.
3989     return true;
3990
3991   return false;
3992 }
3993
3994 //
3995 // Some special combinations that can be optimized.
3996 //
3997 static
3998 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3999                                SelectionDAG &DAG) {
4000   MVT VT = SVOp->getSimpleValueType(0);
4001   SDLoc dl(SVOp);
4002
4003   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4004     return SDValue();
4005
4006   ArrayRef<int> Mask = SVOp->getMask();
4007
4008   // These are the special masks that may be optimized.
4009   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4010   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4011   bool MatchEvenMask = true;
4012   bool MatchOddMask  = true;
4013   for (int i=0; i<8; ++i) {
4014     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4015       MatchEvenMask = false;
4016     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4017       MatchOddMask = false;
4018   }
4019
4020   if (!MatchEvenMask && !MatchOddMask)
4021     return SDValue();
4022
4023   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4024
4025   SDValue Op0 = SVOp->getOperand(0);
4026   SDValue Op1 = SVOp->getOperand(1);
4027
4028   if (MatchEvenMask) {
4029     // Shift the second operand right to 32 bits.
4030     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4031     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4032   } else {
4033     // Shift the first operand left to 32 bits.
4034     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4035     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4036   }
4037   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4038   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4039 }
4040
4041 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4042 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4043 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4044                          bool HasInt256, bool V2IsSplat = false) {
4045
4046   assert(VT.getSizeInBits() >= 128 &&
4047          "Unsupported vector type for unpckl");
4048
4049   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4050   unsigned NumLanes;
4051   unsigned NumOf256BitLanes;
4052   unsigned NumElts = VT.getVectorNumElements();
4053   if (VT.is256BitVector()) {
4054     if (NumElts != 4 && NumElts != 8 &&
4055         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4056     return false;
4057     NumLanes = 2;
4058     NumOf256BitLanes = 1;
4059   } else if (VT.is512BitVector()) {
4060     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4061            "Unsupported vector type for unpckh");
4062     NumLanes = 2;
4063     NumOf256BitLanes = 2;
4064   } else {
4065     NumLanes = 1;
4066     NumOf256BitLanes = 1;
4067   }
4068
4069   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4070   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4071
4072   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4073     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4074       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4075         int BitI  = Mask[l256*NumEltsInStride+l+i];
4076         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4077         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4078           return false;
4079         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4080           return false;
4081         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4082           return false;
4083       }
4084     }
4085   }
4086   return true;
4087 }
4088
4089 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4090 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4091 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4092                          bool HasInt256, bool V2IsSplat = false) {
4093   assert(VT.getSizeInBits() >= 128 &&
4094          "Unsupported vector type for unpckh");
4095
4096   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4097   unsigned NumLanes;
4098   unsigned NumOf256BitLanes;
4099   unsigned NumElts = VT.getVectorNumElements();
4100   if (VT.is256BitVector()) {
4101     if (NumElts != 4 && NumElts != 8 &&
4102         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4103     return false;
4104     NumLanes = 2;
4105     NumOf256BitLanes = 1;
4106   } else if (VT.is512BitVector()) {
4107     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4108            "Unsupported vector type for unpckh");
4109     NumLanes = 2;
4110     NumOf256BitLanes = 2;
4111   } else {
4112     NumLanes = 1;
4113     NumOf256BitLanes = 1;
4114   }
4115
4116   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4117   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4118
4119   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4120     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4121       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4122         int BitI  = Mask[l256*NumEltsInStride+l+i];
4123         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4124         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4125           return false;
4126         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4127           return false;
4128         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4129           return false;
4130       }
4131     }
4132   }
4133   return true;
4134 }
4135
4136 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4137 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4138 /// <0, 0, 1, 1>
4139 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4140   unsigned NumElts = VT.getVectorNumElements();
4141   bool Is256BitVec = VT.is256BitVector();
4142
4143   if (VT.is512BitVector())
4144     return false;
4145   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4146          "Unsupported vector type for unpckh");
4147
4148   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4149       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4150     return false;
4151
4152   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4153   // FIXME: Need a better way to get rid of this, there's no latency difference
4154   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4155   // the former later. We should also remove the "_undef" special mask.
4156   if (NumElts == 4 && Is256BitVec)
4157     return false;
4158
4159   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4160   // independently on 128-bit lanes.
4161   unsigned NumLanes = VT.getSizeInBits()/128;
4162   unsigned NumLaneElts = NumElts/NumLanes;
4163
4164   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4165     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4166       int BitI  = Mask[l+i];
4167       int BitI1 = Mask[l+i+1];
4168
4169       if (!isUndefOrEqual(BitI, j))
4170         return false;
4171       if (!isUndefOrEqual(BitI1, j))
4172         return false;
4173     }
4174   }
4175
4176   return true;
4177 }
4178
4179 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4180 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4181 /// <2, 2, 3, 3>
4182 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4183   unsigned NumElts = VT.getVectorNumElements();
4184
4185   if (VT.is512BitVector())
4186     return false;
4187
4188   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4189          "Unsupported vector type for unpckh");
4190
4191   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4192       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4193     return false;
4194
4195   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4196   // independently on 128-bit lanes.
4197   unsigned NumLanes = VT.getSizeInBits()/128;
4198   unsigned NumLaneElts = NumElts/NumLanes;
4199
4200   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4201     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4202       int BitI  = Mask[l+i];
4203       int BitI1 = Mask[l+i+1];
4204       if (!isUndefOrEqual(BitI, j))
4205         return false;
4206       if (!isUndefOrEqual(BitI1, j))
4207         return false;
4208     }
4209   }
4210   return true;
4211 }
4212
4213 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4214 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4215 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4216   if (!VT.is512BitVector())
4217     return false;
4218
4219   unsigned NumElts = VT.getVectorNumElements();
4220   unsigned HalfSize = NumElts/2;
4221   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4222     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4223       *Imm = 1;
4224       return true;
4225     }
4226   }
4227   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4228     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4229       *Imm = 0;
4230       return true;
4231     }
4232   }
4233   return false;
4234 }
4235
4236 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4237 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4238 /// MOVSD, and MOVD, i.e. setting the lowest element.
4239 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4240   if (VT.getVectorElementType().getSizeInBits() < 32)
4241     return false;
4242   if (!VT.is128BitVector())
4243     return false;
4244
4245   unsigned NumElts = VT.getVectorNumElements();
4246
4247   if (!isUndefOrEqual(Mask[0], NumElts))
4248     return false;
4249
4250   for (unsigned i = 1; i != NumElts; ++i)
4251     if (!isUndefOrEqual(Mask[i], i))
4252       return false;
4253
4254   return true;
4255 }
4256
4257 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4258 /// as permutations between 128-bit chunks or halves. As an example: this
4259 /// shuffle bellow:
4260 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4261 /// The first half comes from the second half of V1 and the second half from the
4262 /// the second half of V2.
4263 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4264   if (!HasFp256 || !VT.is256BitVector())
4265     return false;
4266
4267   // The shuffle result is divided into half A and half B. In total the two
4268   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4269   // B must come from C, D, E or F.
4270   unsigned HalfSize = VT.getVectorNumElements()/2;
4271   bool MatchA = false, MatchB = false;
4272
4273   // Check if A comes from one of C, D, E, F.
4274   for (unsigned Half = 0; Half != 4; ++Half) {
4275     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4276       MatchA = true;
4277       break;
4278     }
4279   }
4280
4281   // Check if B comes from one of C, D, E, F.
4282   for (unsigned Half = 0; Half != 4; ++Half) {
4283     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4284       MatchB = true;
4285       break;
4286     }
4287   }
4288
4289   return MatchA && MatchB;
4290 }
4291
4292 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4293 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4294 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4295   MVT VT = SVOp->getSimpleValueType(0);
4296
4297   unsigned HalfSize = VT.getVectorNumElements()/2;
4298
4299   unsigned FstHalf = 0, SndHalf = 0;
4300   for (unsigned i = 0; i < HalfSize; ++i) {
4301     if (SVOp->getMaskElt(i) > 0) {
4302       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4303       break;
4304     }
4305   }
4306   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4307     if (SVOp->getMaskElt(i) > 0) {
4308       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4309       break;
4310     }
4311   }
4312
4313   return (FstHalf | (SndHalf << 4));
4314 }
4315
4316 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4317 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4318   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4319   if (EltSize < 32)
4320     return false;
4321
4322   unsigned NumElts = VT.getVectorNumElements();
4323   Imm8 = 0;
4324   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4325     for (unsigned i = 0; i != NumElts; ++i) {
4326       if (Mask[i] < 0)
4327         continue;
4328       Imm8 |= Mask[i] << (i*2);
4329     }
4330     return true;
4331   }
4332
4333   unsigned LaneSize = 4;
4334   SmallVector<int, 4> MaskVal(LaneSize, -1);
4335
4336   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4337     for (unsigned i = 0; i != LaneSize; ++i) {
4338       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4339         return false;
4340       if (Mask[i+l] < 0)
4341         continue;
4342       if (MaskVal[i] < 0) {
4343         MaskVal[i] = Mask[i+l] - l;
4344         Imm8 |= MaskVal[i] << (i*2);
4345         continue;
4346       }
4347       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4348         return false;
4349     }
4350   }
4351   return true;
4352 }
4353
4354 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4355 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4356 /// Note that VPERMIL mask matching is different depending whether theunderlying
4357 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4358 /// to the same elements of the low, but to the higher half of the source.
4359 /// In VPERMILPD the two lanes could be shuffled independently of each other
4360 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4361 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4362   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4363   if (VT.getSizeInBits() < 256 || EltSize < 32)
4364     return false;
4365   bool symetricMaskRequired = (EltSize == 32);
4366   unsigned NumElts = VT.getVectorNumElements();
4367
4368   unsigned NumLanes = VT.getSizeInBits()/128;
4369   unsigned LaneSize = NumElts/NumLanes;
4370   // 2 or 4 elements in one lane
4371
4372   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4373   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4374     for (unsigned i = 0; i != LaneSize; ++i) {
4375       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4376         return false;
4377       if (symetricMaskRequired) {
4378         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4379           ExpectedMaskVal[i] = Mask[i+l] - l;
4380           continue;
4381         }
4382         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4383           return false;
4384       }
4385     }
4386   }
4387   return true;
4388 }
4389
4390 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4391 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4392 /// element of vector 2 and the other elements to come from vector 1 in order.
4393 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4394                                bool V2IsSplat = false, bool V2IsUndef = false) {
4395   if (!VT.is128BitVector())
4396     return false;
4397
4398   unsigned NumOps = VT.getVectorNumElements();
4399   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4400     return false;
4401
4402   if (!isUndefOrEqual(Mask[0], 0))
4403     return false;
4404
4405   for (unsigned i = 1; i != NumOps; ++i)
4406     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4407           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4408           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4409       return false;
4410
4411   return true;
4412 }
4413
4414 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4415 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4416 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4417 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4418                            const X86Subtarget *Subtarget) {
4419   if (!Subtarget->hasSSE3())
4420     return false;
4421
4422   unsigned NumElems = VT.getVectorNumElements();
4423
4424   if ((VT.is128BitVector() && NumElems != 4) ||
4425       (VT.is256BitVector() && NumElems != 8) ||
4426       (VT.is512BitVector() && NumElems != 16))
4427     return false;
4428
4429   // "i+1" is the value the indexed mask element must have
4430   for (unsigned i = 0; i != NumElems; i += 2)
4431     if (!isUndefOrEqual(Mask[i], i+1) ||
4432         !isUndefOrEqual(Mask[i+1], i+1))
4433       return false;
4434
4435   return true;
4436 }
4437
4438 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4439 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4440 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4441 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4442                            const X86Subtarget *Subtarget) {
4443   if (!Subtarget->hasSSE3())
4444     return false;
4445
4446   unsigned NumElems = VT.getVectorNumElements();
4447
4448   if ((VT.is128BitVector() && NumElems != 4) ||
4449       (VT.is256BitVector() && NumElems != 8) ||
4450       (VT.is512BitVector() && NumElems != 16))
4451     return false;
4452
4453   // "i" is the value the indexed mask element must have
4454   for (unsigned i = 0; i != NumElems; i += 2)
4455     if (!isUndefOrEqual(Mask[i], i) ||
4456         !isUndefOrEqual(Mask[i+1], i))
4457       return false;
4458
4459   return true;
4460 }
4461
4462 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4463 /// specifies a shuffle of elements that is suitable for input to 256-bit
4464 /// version of MOVDDUP.
4465 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4466   if (!HasFp256 || !VT.is256BitVector())
4467     return false;
4468
4469   unsigned NumElts = VT.getVectorNumElements();
4470   if (NumElts != 4)
4471     return false;
4472
4473   for (unsigned i = 0; i != NumElts/2; ++i)
4474     if (!isUndefOrEqual(Mask[i], 0))
4475       return false;
4476   for (unsigned i = NumElts/2; i != NumElts; ++i)
4477     if (!isUndefOrEqual(Mask[i], NumElts/2))
4478       return false;
4479   return true;
4480 }
4481
4482 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4483 /// specifies a shuffle of elements that is suitable for input to 128-bit
4484 /// version of MOVDDUP.
4485 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4486   if (!VT.is128BitVector())
4487     return false;
4488
4489   unsigned e = VT.getVectorNumElements() / 2;
4490   for (unsigned i = 0; i != e; ++i)
4491     if (!isUndefOrEqual(Mask[i], i))
4492       return false;
4493   for (unsigned i = 0; i != e; ++i)
4494     if (!isUndefOrEqual(Mask[e+i], i))
4495       return false;
4496   return true;
4497 }
4498
4499 /// isVEXTRACTIndex - Return true if the specified
4500 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4501 /// suitable for instruction that extract 128 or 256 bit vectors
4502 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4503   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4504   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4505     return false;
4506
4507   // The index should be aligned on a vecWidth-bit boundary.
4508   uint64_t Index =
4509     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4510
4511   MVT VT = N->getSimpleValueType(0);
4512   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4513   bool Result = (Index * ElSize) % vecWidth == 0;
4514
4515   return Result;
4516 }
4517
4518 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4519 /// operand specifies a subvector insert that is suitable for input to
4520 /// insertion of 128 or 256-bit subvectors
4521 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4522   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4523   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4524     return false;
4525   // The index should be aligned on a vecWidth-bit boundary.
4526   uint64_t Index =
4527     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4528
4529   MVT VT = N->getSimpleValueType(0);
4530   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4531   bool Result = (Index * ElSize) % vecWidth == 0;
4532
4533   return Result;
4534 }
4535
4536 bool X86::isVINSERT128Index(SDNode *N) {
4537   return isVINSERTIndex(N, 128);
4538 }
4539
4540 bool X86::isVINSERT256Index(SDNode *N) {
4541   return isVINSERTIndex(N, 256);
4542 }
4543
4544 bool X86::isVEXTRACT128Index(SDNode *N) {
4545   return isVEXTRACTIndex(N, 128);
4546 }
4547
4548 bool X86::isVEXTRACT256Index(SDNode *N) {
4549   return isVEXTRACTIndex(N, 256);
4550 }
4551
4552 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4553 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4554 /// Handles 128-bit and 256-bit.
4555 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4556   MVT VT = N->getSimpleValueType(0);
4557
4558   assert((VT.getSizeInBits() >= 128) &&
4559          "Unsupported vector type for PSHUF/SHUFP");
4560
4561   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4562   // independently on 128-bit lanes.
4563   unsigned NumElts = VT.getVectorNumElements();
4564   unsigned NumLanes = VT.getSizeInBits()/128;
4565   unsigned NumLaneElts = NumElts/NumLanes;
4566
4567   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4568          "Only supports 2, 4 or 8 elements per lane");
4569
4570   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4571   unsigned Mask = 0;
4572   for (unsigned i = 0; i != NumElts; ++i) {
4573     int Elt = N->getMaskElt(i);
4574     if (Elt < 0) continue;
4575     Elt &= NumLaneElts - 1;
4576     unsigned ShAmt = (i << Shift) % 8;
4577     Mask |= Elt << ShAmt;
4578   }
4579
4580   return Mask;
4581 }
4582
4583 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4584 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4585 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4586   MVT VT = N->getSimpleValueType(0);
4587
4588   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4589          "Unsupported vector type for PSHUFHW");
4590
4591   unsigned NumElts = VT.getVectorNumElements();
4592
4593   unsigned Mask = 0;
4594   for (unsigned l = 0; l != NumElts; l += 8) {
4595     // 8 nodes per lane, but we only care about the last 4.
4596     for (unsigned i = 0; i < 4; ++i) {
4597       int Elt = N->getMaskElt(l+i+4);
4598       if (Elt < 0) continue;
4599       Elt &= 0x3; // only 2-bits.
4600       Mask |= Elt << (i * 2);
4601     }
4602   }
4603
4604   return Mask;
4605 }
4606
4607 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4608 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4609 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4610   MVT VT = N->getSimpleValueType(0);
4611
4612   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4613          "Unsupported vector type for PSHUFHW");
4614
4615   unsigned NumElts = VT.getVectorNumElements();
4616
4617   unsigned Mask = 0;
4618   for (unsigned l = 0; l != NumElts; l += 8) {
4619     // 8 nodes per lane, but we only care about the first 4.
4620     for (unsigned i = 0; i < 4; ++i) {
4621       int Elt = N->getMaskElt(l+i);
4622       if (Elt < 0) continue;
4623       Elt &= 0x3; // only 2-bits
4624       Mask |= Elt << (i * 2);
4625     }
4626   }
4627
4628   return Mask;
4629 }
4630
4631 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4632 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4633 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4634   MVT VT = SVOp->getSimpleValueType(0);
4635   unsigned EltSize = VT.is512BitVector() ? 1 :
4636     VT.getVectorElementType().getSizeInBits() >> 3;
4637
4638   unsigned NumElts = VT.getVectorNumElements();
4639   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4640   unsigned NumLaneElts = NumElts/NumLanes;
4641
4642   int Val = 0;
4643   unsigned i;
4644   for (i = 0; i != NumElts; ++i) {
4645     Val = SVOp->getMaskElt(i);
4646     if (Val >= 0)
4647       break;
4648   }
4649   if (Val >= (int)NumElts)
4650     Val -= NumElts - NumLaneElts;
4651
4652   assert(Val - i > 0 && "PALIGNR imm should be positive");
4653   return (Val - i) * EltSize;
4654 }
4655
4656 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4657   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4658   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4659     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4660
4661   uint64_t Index =
4662     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4663
4664   MVT VecVT = N->getOperand(0).getSimpleValueType();
4665   MVT ElVT = VecVT.getVectorElementType();
4666
4667   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4668   return Index / NumElemsPerChunk;
4669 }
4670
4671 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4672   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4673   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4674     llvm_unreachable("Illegal insert subvector for VINSERT");
4675
4676   uint64_t Index =
4677     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4678
4679   MVT VecVT = N->getSimpleValueType(0);
4680   MVT ElVT = VecVT.getVectorElementType();
4681
4682   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4683   return Index / NumElemsPerChunk;
4684 }
4685
4686 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4687 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4688 /// and VINSERTI128 instructions.
4689 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4690   return getExtractVEXTRACTImmediate(N, 128);
4691 }
4692
4693 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4694 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4695 /// and VINSERTI64x4 instructions.
4696 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4697   return getExtractVEXTRACTImmediate(N, 256);
4698 }
4699
4700 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4701 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4702 /// and VINSERTI128 instructions.
4703 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4704   return getInsertVINSERTImmediate(N, 128);
4705 }
4706
4707 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4708 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4709 /// and VINSERTI64x4 instructions.
4710 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4711   return getInsertVINSERTImmediate(N, 256);
4712 }
4713
4714 /// isZero - Returns true if Elt is a constant integer zero
4715 static bool isZero(SDValue V) {
4716   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4717   return C && C->isNullValue();
4718 }
4719
4720 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4721 /// constant +0.0.
4722 bool X86::isZeroNode(SDValue Elt) {
4723   if (isZero(Elt))
4724     return true;
4725   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4726     return CFP->getValueAPF().isPosZero();
4727   return false;
4728 }
4729
4730 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4731 /// their permute mask.
4732 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4733                                     SelectionDAG &DAG) {
4734   MVT VT = SVOp->getSimpleValueType(0);
4735   unsigned NumElems = VT.getVectorNumElements();
4736   SmallVector<int, 8> MaskVec;
4737
4738   for (unsigned i = 0; i != NumElems; ++i) {
4739     int Idx = SVOp->getMaskElt(i);
4740     if (Idx >= 0) {
4741       if (Idx < (int)NumElems)
4742         Idx += NumElems;
4743       else
4744         Idx -= NumElems;
4745     }
4746     MaskVec.push_back(Idx);
4747   }
4748   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4749                               SVOp->getOperand(0), &MaskVec[0]);
4750 }
4751
4752 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4753 /// match movhlps. The lower half elements should come from upper half of
4754 /// V1 (and in order), and the upper half elements should come from the upper
4755 /// half of V2 (and in order).
4756 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4757   if (!VT.is128BitVector())
4758     return false;
4759   if (VT.getVectorNumElements() != 4)
4760     return false;
4761   for (unsigned i = 0, e = 2; i != e; ++i)
4762     if (!isUndefOrEqual(Mask[i], i+2))
4763       return false;
4764   for (unsigned i = 2; i != 4; ++i)
4765     if (!isUndefOrEqual(Mask[i], i+4))
4766       return false;
4767   return true;
4768 }
4769
4770 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4771 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4772 /// required.
4773 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4774   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4775     return false;
4776   N = N->getOperand(0).getNode();
4777   if (!ISD::isNON_EXTLoad(N))
4778     return false;
4779   if (LD)
4780     *LD = cast<LoadSDNode>(N);
4781   return true;
4782 }
4783
4784 // Test whether the given value is a vector value which will be legalized
4785 // into a load.
4786 static bool WillBeConstantPoolLoad(SDNode *N) {
4787   if (N->getOpcode() != ISD::BUILD_VECTOR)
4788     return false;
4789
4790   // Check for any non-constant elements.
4791   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4792     switch (N->getOperand(i).getNode()->getOpcode()) {
4793     case ISD::UNDEF:
4794     case ISD::ConstantFP:
4795     case ISD::Constant:
4796       break;
4797     default:
4798       return false;
4799     }
4800
4801   // Vectors of all-zeros and all-ones are materialized with special
4802   // instructions rather than being loaded.
4803   return !ISD::isBuildVectorAllZeros(N) &&
4804          !ISD::isBuildVectorAllOnes(N);
4805 }
4806
4807 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4808 /// match movlp{s|d}. The lower half elements should come from lower half of
4809 /// V1 (and in order), and the upper half elements should come from the upper
4810 /// half of V2 (and in order). And since V1 will become the source of the
4811 /// MOVLP, it must be either a vector load or a scalar load to vector.
4812 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4813                                ArrayRef<int> Mask, MVT VT) {
4814   if (!VT.is128BitVector())
4815     return false;
4816
4817   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4818     return false;
4819   // Is V2 is a vector load, don't do this transformation. We will try to use
4820   // load folding shufps op.
4821   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4822     return false;
4823
4824   unsigned NumElems = VT.getVectorNumElements();
4825
4826   if (NumElems != 2 && NumElems != 4)
4827     return false;
4828   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4829     if (!isUndefOrEqual(Mask[i], i))
4830       return false;
4831   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4832     if (!isUndefOrEqual(Mask[i], i+NumElems))
4833       return false;
4834   return true;
4835 }
4836
4837 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4838 /// all the same.
4839 static bool isSplatVector(SDNode *N) {
4840   if (N->getOpcode() != ISD::BUILD_VECTOR)
4841     return false;
4842
4843   SDValue SplatValue = N->getOperand(0);
4844   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4845     if (N->getOperand(i) != SplatValue)
4846       return false;
4847   return true;
4848 }
4849
4850 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4851 /// to an zero vector.
4852 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4853 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4854   SDValue V1 = N->getOperand(0);
4855   SDValue V2 = N->getOperand(1);
4856   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4857   for (unsigned i = 0; i != NumElems; ++i) {
4858     int Idx = N->getMaskElt(i);
4859     if (Idx >= (int)NumElems) {
4860       unsigned Opc = V2.getOpcode();
4861       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4862         continue;
4863       if (Opc != ISD::BUILD_VECTOR ||
4864           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4865         return false;
4866     } else if (Idx >= 0) {
4867       unsigned Opc = V1.getOpcode();
4868       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4869         continue;
4870       if (Opc != ISD::BUILD_VECTOR ||
4871           !X86::isZeroNode(V1.getOperand(Idx)))
4872         return false;
4873     }
4874   }
4875   return true;
4876 }
4877
4878 /// getZeroVector - Returns a vector of specified type with all zero elements.
4879 ///
4880 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4881                              SelectionDAG &DAG, SDLoc dl) {
4882   assert(VT.isVector() && "Expected a vector type");
4883
4884   // Always build SSE zero vectors as <4 x i32> bitcasted
4885   // to their dest type. This ensures they get CSE'd.
4886   SDValue Vec;
4887   if (VT.is128BitVector()) {  // SSE
4888     if (Subtarget->hasSSE2()) {  // SSE2
4889       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4890       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4891     } else { // SSE1
4892       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4893       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4894     }
4895   } else if (VT.is256BitVector()) { // AVX
4896     if (Subtarget->hasInt256()) { // AVX2
4897       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4898       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4899       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4900     } else {
4901       // 256-bit logic and arithmetic instructions in AVX are all
4902       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4903       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4904       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4905       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4906     }
4907   } else if (VT.is512BitVector()) { // AVX-512
4908       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4909       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4910                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4911       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4912   } else if (VT.getScalarType() == MVT::i1) {
4913     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4914     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4915     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4916     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4917   } else
4918     llvm_unreachable("Unexpected vector type");
4919
4920   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4921 }
4922
4923 /// getOnesVector - Returns a vector of specified type with all bits set.
4924 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4925 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4926 /// Then bitcast to their original type, ensuring they get CSE'd.
4927 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4928                              SDLoc dl) {
4929   assert(VT.isVector() && "Expected a vector type");
4930
4931   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4932   SDValue Vec;
4933   if (VT.is256BitVector()) {
4934     if (HasInt256) { // AVX2
4935       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4936       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4937     } else { // AVX
4938       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4939       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4940     }
4941   } else if (VT.is128BitVector()) {
4942     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4943   } else
4944     llvm_unreachable("Unexpected vector type");
4945
4946   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4947 }
4948
4949 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4950 /// that point to V2 points to its first element.
4951 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4952   for (unsigned i = 0; i != NumElems; ++i) {
4953     if (Mask[i] > (int)NumElems) {
4954       Mask[i] = NumElems;
4955     }
4956   }
4957 }
4958
4959 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4960 /// operation of specified width.
4961 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4962                        SDValue V2) {
4963   unsigned NumElems = VT.getVectorNumElements();
4964   SmallVector<int, 8> Mask;
4965   Mask.push_back(NumElems);
4966   for (unsigned i = 1; i != NumElems; ++i)
4967     Mask.push_back(i);
4968   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4969 }
4970
4971 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4972 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4973                           SDValue V2) {
4974   unsigned NumElems = VT.getVectorNumElements();
4975   SmallVector<int, 8> Mask;
4976   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4977     Mask.push_back(i);
4978     Mask.push_back(i + NumElems);
4979   }
4980   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4981 }
4982
4983 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4984 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4985                           SDValue V2) {
4986   unsigned NumElems = VT.getVectorNumElements();
4987   SmallVector<int, 8> Mask;
4988   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4989     Mask.push_back(i + Half);
4990     Mask.push_back(i + NumElems + Half);
4991   }
4992   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4993 }
4994
4995 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4996 // a generic shuffle instruction because the target has no such instructions.
4997 // Generate shuffles which repeat i16 and i8 several times until they can be
4998 // represented by v4f32 and then be manipulated by target suported shuffles.
4999 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5000   MVT VT = V.getSimpleValueType();
5001   int NumElems = VT.getVectorNumElements();
5002   SDLoc dl(V);
5003
5004   while (NumElems > 4) {
5005     if (EltNo < NumElems/2) {
5006       V = getUnpackl(DAG, dl, VT, V, V);
5007     } else {
5008       V = getUnpackh(DAG, dl, VT, V, V);
5009       EltNo -= NumElems/2;
5010     }
5011     NumElems >>= 1;
5012   }
5013   return V;
5014 }
5015
5016 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5017 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5018   MVT VT = V.getSimpleValueType();
5019   SDLoc dl(V);
5020
5021   if (VT.is128BitVector()) {
5022     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5023     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5024     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5025                              &SplatMask[0]);
5026   } else if (VT.is256BitVector()) {
5027     // To use VPERMILPS to splat scalars, the second half of indicies must
5028     // refer to the higher part, which is a duplication of the lower one,
5029     // because VPERMILPS can only handle in-lane permutations.
5030     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5031                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5032
5033     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5034     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5035                              &SplatMask[0]);
5036   } else
5037     llvm_unreachable("Vector size not supported");
5038
5039   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5040 }
5041
5042 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5043 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5044   MVT SrcVT = SV->getSimpleValueType(0);
5045   SDValue V1 = SV->getOperand(0);
5046   SDLoc dl(SV);
5047
5048   int EltNo = SV->getSplatIndex();
5049   int NumElems = SrcVT.getVectorNumElements();
5050   bool Is256BitVec = SrcVT.is256BitVector();
5051
5052   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5053          "Unknown how to promote splat for type");
5054
5055   // Extract the 128-bit part containing the splat element and update
5056   // the splat element index when it refers to the higher register.
5057   if (Is256BitVec) {
5058     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5059     if (EltNo >= NumElems/2)
5060       EltNo -= NumElems/2;
5061   }
5062
5063   // All i16 and i8 vector types can't be used directly by a generic shuffle
5064   // instruction because the target has no such instruction. Generate shuffles
5065   // which repeat i16 and i8 several times until they fit in i32, and then can
5066   // be manipulated by target suported shuffles.
5067   MVT EltVT = SrcVT.getVectorElementType();
5068   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5069     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5070
5071   // Recreate the 256-bit vector and place the same 128-bit vector
5072   // into the low and high part. This is necessary because we want
5073   // to use VPERM* to shuffle the vectors
5074   if (Is256BitVec) {
5075     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5076   }
5077
5078   return getLegalSplat(DAG, V1, EltNo);
5079 }
5080
5081 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5082 /// vector of zero or undef vector.  This produces a shuffle where the low
5083 /// element of V2 is swizzled into the zero/undef vector, landing at element
5084 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5085 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5086                                            bool IsZero,
5087                                            const X86Subtarget *Subtarget,
5088                                            SelectionDAG &DAG) {
5089   MVT VT = V2.getSimpleValueType();
5090   SDValue V1 = IsZero
5091     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5092   unsigned NumElems = VT.getVectorNumElements();
5093   SmallVector<int, 16> MaskVec;
5094   for (unsigned i = 0; i != NumElems; ++i)
5095     // If this is the insertion idx, put the low elt of V2 here.
5096     MaskVec.push_back(i == Idx ? NumElems : i);
5097   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5098 }
5099
5100 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5101 /// target specific opcode. Returns true if the Mask could be calculated.
5102 /// Sets IsUnary to true if only uses one source.
5103 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5104                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5105   unsigned NumElems = VT.getVectorNumElements();
5106   SDValue ImmN;
5107
5108   IsUnary = false;
5109   switch(N->getOpcode()) {
5110   case X86ISD::SHUFP:
5111     ImmN = N->getOperand(N->getNumOperands()-1);
5112     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5113     break;
5114   case X86ISD::UNPCKH:
5115     DecodeUNPCKHMask(VT, Mask);
5116     break;
5117   case X86ISD::UNPCKL:
5118     DecodeUNPCKLMask(VT, Mask);
5119     break;
5120   case X86ISD::MOVHLPS:
5121     DecodeMOVHLPSMask(NumElems, Mask);
5122     break;
5123   case X86ISD::MOVLHPS:
5124     DecodeMOVLHPSMask(NumElems, Mask);
5125     break;
5126   case X86ISD::PALIGNR:
5127     ImmN = N->getOperand(N->getNumOperands()-1);
5128     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5129     break;
5130   case X86ISD::PSHUFD:
5131   case X86ISD::VPERMILP:
5132     ImmN = N->getOperand(N->getNumOperands()-1);
5133     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5134     IsUnary = true;
5135     break;
5136   case X86ISD::PSHUFHW:
5137     ImmN = N->getOperand(N->getNumOperands()-1);
5138     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5139     IsUnary = true;
5140     break;
5141   case X86ISD::PSHUFLW:
5142     ImmN = N->getOperand(N->getNumOperands()-1);
5143     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5144     IsUnary = true;
5145     break;
5146   case X86ISD::VPERMI:
5147     ImmN = N->getOperand(N->getNumOperands()-1);
5148     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5149     IsUnary = true;
5150     break;
5151   case X86ISD::MOVSS:
5152   case X86ISD::MOVSD: {
5153     // The index 0 always comes from the first element of the second source,
5154     // this is why MOVSS and MOVSD are used in the first place. The other
5155     // elements come from the other positions of the first source vector
5156     Mask.push_back(NumElems);
5157     for (unsigned i = 1; i != NumElems; ++i) {
5158       Mask.push_back(i);
5159     }
5160     break;
5161   }
5162   case X86ISD::VPERM2X128:
5163     ImmN = N->getOperand(N->getNumOperands()-1);
5164     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5165     if (Mask.empty()) return false;
5166     break;
5167   case X86ISD::MOVDDUP:
5168   case X86ISD::MOVLHPD:
5169   case X86ISD::MOVLPD:
5170   case X86ISD::MOVLPS:
5171   case X86ISD::MOVSHDUP:
5172   case X86ISD::MOVSLDUP:
5173     // Not yet implemented
5174     return false;
5175   default: llvm_unreachable("unknown target shuffle node");
5176   }
5177
5178   return true;
5179 }
5180
5181 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5182 /// element of the result of the vector shuffle.
5183 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5184                                    unsigned Depth) {
5185   if (Depth == 6)
5186     return SDValue();  // Limit search depth.
5187
5188   SDValue V = SDValue(N, 0);
5189   EVT VT = V.getValueType();
5190   unsigned Opcode = V.getOpcode();
5191
5192   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5193   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5194     int Elt = SV->getMaskElt(Index);
5195
5196     if (Elt < 0)
5197       return DAG.getUNDEF(VT.getVectorElementType());
5198
5199     unsigned NumElems = VT.getVectorNumElements();
5200     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5201                                          : SV->getOperand(1);
5202     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5203   }
5204
5205   // Recurse into target specific vector shuffles to find scalars.
5206   if (isTargetShuffle(Opcode)) {
5207     MVT ShufVT = V.getSimpleValueType();
5208     unsigned NumElems = ShufVT.getVectorNumElements();
5209     SmallVector<int, 16> ShuffleMask;
5210     bool IsUnary;
5211
5212     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5213       return SDValue();
5214
5215     int Elt = ShuffleMask[Index];
5216     if (Elt < 0)
5217       return DAG.getUNDEF(ShufVT.getVectorElementType());
5218
5219     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5220                                          : N->getOperand(1);
5221     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5222                                Depth+1);
5223   }
5224
5225   // Actual nodes that may contain scalar elements
5226   if (Opcode == ISD::BITCAST) {
5227     V = V.getOperand(0);
5228     EVT SrcVT = V.getValueType();
5229     unsigned NumElems = VT.getVectorNumElements();
5230
5231     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5232       return SDValue();
5233   }
5234
5235   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5236     return (Index == 0) ? V.getOperand(0)
5237                         : DAG.getUNDEF(VT.getVectorElementType());
5238
5239   if (V.getOpcode() == ISD::BUILD_VECTOR)
5240     return V.getOperand(Index);
5241
5242   return SDValue();
5243 }
5244
5245 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5246 /// shuffle operation which come from a consecutively from a zero. The
5247 /// search can start in two different directions, from left or right.
5248 /// We count undefs as zeros until PreferredNum is reached.
5249 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5250                                          unsigned NumElems, bool ZerosFromLeft,
5251                                          SelectionDAG &DAG,
5252                                          unsigned PreferredNum = -1U) {
5253   unsigned NumZeros = 0;
5254   for (unsigned i = 0; i != NumElems; ++i) {
5255     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5256     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5257     if (!Elt.getNode())
5258       break;
5259
5260     if (X86::isZeroNode(Elt))
5261       ++NumZeros;
5262     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5263       NumZeros = std::min(NumZeros + 1, PreferredNum);
5264     else
5265       break;
5266   }
5267
5268   return NumZeros;
5269 }
5270
5271 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5272 /// correspond consecutively to elements from one of the vector operands,
5273 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5274 static
5275 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5276                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5277                               unsigned NumElems, unsigned &OpNum) {
5278   bool SeenV1 = false;
5279   bool SeenV2 = false;
5280
5281   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5282     int Idx = SVOp->getMaskElt(i);
5283     // Ignore undef indicies
5284     if (Idx < 0)
5285       continue;
5286
5287     if (Idx < (int)NumElems)
5288       SeenV1 = true;
5289     else
5290       SeenV2 = true;
5291
5292     // Only accept consecutive elements from the same vector
5293     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5294       return false;
5295   }
5296
5297   OpNum = SeenV1 ? 0 : 1;
5298   return true;
5299 }
5300
5301 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5302 /// logical left shift of a vector.
5303 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5304                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5305   unsigned NumElems =
5306     SVOp->getSimpleValueType(0).getVectorNumElements();
5307   unsigned NumZeros = getNumOfConsecutiveZeros(
5308       SVOp, NumElems, false /* check zeros from right */, DAG,
5309       SVOp->getMaskElt(0));
5310   unsigned OpSrc;
5311
5312   if (!NumZeros)
5313     return false;
5314
5315   // Considering the elements in the mask that are not consecutive zeros,
5316   // check if they consecutively come from only one of the source vectors.
5317   //
5318   //               V1 = {X, A, B, C}     0
5319   //                         \  \  \    /
5320   //   vector_shuffle V1, V2 <1, 2, 3, X>
5321   //
5322   if (!isShuffleMaskConsecutive(SVOp,
5323             0,                   // Mask Start Index
5324             NumElems-NumZeros,   // Mask End Index(exclusive)
5325             NumZeros,            // Where to start looking in the src vector
5326             NumElems,            // Number of elements in vector
5327             OpSrc))              // Which source operand ?
5328     return false;
5329
5330   isLeft = false;
5331   ShAmt = NumZeros;
5332   ShVal = SVOp->getOperand(OpSrc);
5333   return true;
5334 }
5335
5336 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5337 /// logical left shift of a vector.
5338 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5339                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5340   unsigned NumElems =
5341     SVOp->getSimpleValueType(0).getVectorNumElements();
5342   unsigned NumZeros = getNumOfConsecutiveZeros(
5343       SVOp, NumElems, true /* check zeros from left */, DAG,
5344       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5345   unsigned OpSrc;
5346
5347   if (!NumZeros)
5348     return false;
5349
5350   // Considering the elements in the mask that are not consecutive zeros,
5351   // check if they consecutively come from only one of the source vectors.
5352   //
5353   //                           0    { A, B, X, X } = V2
5354   //                          / \    /  /
5355   //   vector_shuffle V1, V2 <X, X, 4, 5>
5356   //
5357   if (!isShuffleMaskConsecutive(SVOp,
5358             NumZeros,     // Mask Start Index
5359             NumElems,     // Mask End Index(exclusive)
5360             0,            // Where to start looking in the src vector
5361             NumElems,     // Number of elements in vector
5362             OpSrc))       // Which source operand ?
5363     return false;
5364
5365   isLeft = true;
5366   ShAmt = NumZeros;
5367   ShVal = SVOp->getOperand(OpSrc);
5368   return true;
5369 }
5370
5371 /// isVectorShift - Returns true if the shuffle can be implemented as a
5372 /// logical left or right shift of a vector.
5373 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5374                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5375   // Although the logic below support any bitwidth size, there are no
5376   // shift instructions which handle more than 128-bit vectors.
5377   if (!SVOp->getSimpleValueType(0).is128BitVector())
5378     return false;
5379
5380   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5381       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5382     return true;
5383
5384   return false;
5385 }
5386
5387 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5388 ///
5389 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5390                                        unsigned NumNonZero, unsigned NumZero,
5391                                        SelectionDAG &DAG,
5392                                        const X86Subtarget* Subtarget,
5393                                        const TargetLowering &TLI) {
5394   if (NumNonZero > 8)
5395     return SDValue();
5396
5397   SDLoc dl(Op);
5398   SDValue V;
5399   bool First = true;
5400   for (unsigned i = 0; i < 16; ++i) {
5401     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5402     if (ThisIsNonZero && First) {
5403       if (NumZero)
5404         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5405       else
5406         V = DAG.getUNDEF(MVT::v8i16);
5407       First = false;
5408     }
5409
5410     if ((i & 1) != 0) {
5411       SDValue ThisElt, LastElt;
5412       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5413       if (LastIsNonZero) {
5414         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5415                               MVT::i16, Op.getOperand(i-1));
5416       }
5417       if (ThisIsNonZero) {
5418         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5419         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5420                               ThisElt, DAG.getConstant(8, MVT::i8));
5421         if (LastIsNonZero)
5422           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5423       } else
5424         ThisElt = LastElt;
5425
5426       if (ThisElt.getNode())
5427         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5428                         DAG.getIntPtrConstant(i/2));
5429     }
5430   }
5431
5432   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5433 }
5434
5435 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5436 ///
5437 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5438                                      unsigned NumNonZero, unsigned NumZero,
5439                                      SelectionDAG &DAG,
5440                                      const X86Subtarget* Subtarget,
5441                                      const TargetLowering &TLI) {
5442   if (NumNonZero > 4)
5443     return SDValue();
5444
5445   SDLoc dl(Op);
5446   SDValue V;
5447   bool First = true;
5448   for (unsigned i = 0; i < 8; ++i) {
5449     bool isNonZero = (NonZeros & (1 << i)) != 0;
5450     if (isNonZero) {
5451       if (First) {
5452         if (NumZero)
5453           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5454         else
5455           V = DAG.getUNDEF(MVT::v8i16);
5456         First = false;
5457       }
5458       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5459                       MVT::v8i16, V, Op.getOperand(i),
5460                       DAG.getIntPtrConstant(i));
5461     }
5462   }
5463
5464   return V;
5465 }
5466
5467 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5468 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5469                                      unsigned NonZeros, unsigned NumNonZero,
5470                                      unsigned NumZero, SelectionDAG &DAG,
5471                                      const X86Subtarget *Subtarget,
5472                                      const TargetLowering &TLI) {
5473   // We know there's at least one non-zero element
5474   unsigned FirstNonZeroIdx = 0;
5475   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5476   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5477          X86::isZeroNode(FirstNonZero)) {
5478     ++FirstNonZeroIdx;
5479     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5480   }
5481
5482   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5483       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5484     return SDValue();
5485
5486   SDValue V = FirstNonZero.getOperand(0);
5487   MVT VVT = V.getSimpleValueType();
5488   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5489     return SDValue();
5490
5491   unsigned FirstNonZeroDst =
5492       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5493   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5494   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5495   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5496
5497   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5498     SDValue Elem = Op.getOperand(Idx);
5499     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5500       continue;
5501
5502     // TODO: What else can be here? Deal with it.
5503     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5504       return SDValue();
5505
5506     // TODO: Some optimizations are still possible here
5507     // ex: Getting one element from a vector, and the rest from another.
5508     if (Elem.getOperand(0) != V)
5509       return SDValue();
5510
5511     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5512     if (Dst == Idx)
5513       ++CorrectIdx;
5514     else if (IncorrectIdx == -1U) {
5515       IncorrectIdx = Idx;
5516       IncorrectDst = Dst;
5517     } else
5518       // There was already one element with an incorrect index.
5519       // We can't optimize this case to an insertps.
5520       return SDValue();
5521   }
5522
5523   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5524     SDLoc dl(Op);
5525     EVT VT = Op.getSimpleValueType();
5526     unsigned ElementMoveMask = 0;
5527     if (IncorrectIdx == -1U)
5528       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5529     else
5530       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5531
5532     SDValue InsertpsMask =
5533         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5534     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5535   }
5536
5537   return SDValue();
5538 }
5539
5540 /// getVShift - Return a vector logical shift node.
5541 ///
5542 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5543                          unsigned NumBits, SelectionDAG &DAG,
5544                          const TargetLowering &TLI, SDLoc dl) {
5545   assert(VT.is128BitVector() && "Unknown type for VShift");
5546   EVT ShVT = MVT::v2i64;
5547   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5548   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5549   return DAG.getNode(ISD::BITCAST, dl, VT,
5550                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5551                              DAG.getConstant(NumBits,
5552                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5553 }
5554
5555 static SDValue
5556 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5557
5558   // Check if the scalar load can be widened into a vector load. And if
5559   // the address is "base + cst" see if the cst can be "absorbed" into
5560   // the shuffle mask.
5561   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5562     SDValue Ptr = LD->getBasePtr();
5563     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5564       return SDValue();
5565     EVT PVT = LD->getValueType(0);
5566     if (PVT != MVT::i32 && PVT != MVT::f32)
5567       return SDValue();
5568
5569     int FI = -1;
5570     int64_t Offset = 0;
5571     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5572       FI = FINode->getIndex();
5573       Offset = 0;
5574     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5575                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5576       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5577       Offset = Ptr.getConstantOperandVal(1);
5578       Ptr = Ptr.getOperand(0);
5579     } else {
5580       return SDValue();
5581     }
5582
5583     // FIXME: 256-bit vector instructions don't require a strict alignment,
5584     // improve this code to support it better.
5585     unsigned RequiredAlign = VT.getSizeInBits()/8;
5586     SDValue Chain = LD->getChain();
5587     // Make sure the stack object alignment is at least 16 or 32.
5588     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5589     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5590       if (MFI->isFixedObjectIndex(FI)) {
5591         // Can't change the alignment. FIXME: It's possible to compute
5592         // the exact stack offset and reference FI + adjust offset instead.
5593         // If someone *really* cares about this. That's the way to implement it.
5594         return SDValue();
5595       } else {
5596         MFI->setObjectAlignment(FI, RequiredAlign);
5597       }
5598     }
5599
5600     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5601     // Ptr + (Offset & ~15).
5602     if (Offset < 0)
5603       return SDValue();
5604     if ((Offset % RequiredAlign) & 3)
5605       return SDValue();
5606     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5607     if (StartOffset)
5608       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5609                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5610
5611     int EltNo = (Offset - StartOffset) >> 2;
5612     unsigned NumElems = VT.getVectorNumElements();
5613
5614     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5615     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5616                              LD->getPointerInfo().getWithOffset(StartOffset),
5617                              false, false, false, 0);
5618
5619     SmallVector<int, 8> Mask;
5620     for (unsigned i = 0; i != NumElems; ++i)
5621       Mask.push_back(EltNo);
5622
5623     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5624   }
5625
5626   return SDValue();
5627 }
5628
5629 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5630 /// vector of type 'VT', see if the elements can be replaced by a single large
5631 /// load which has the same value as a build_vector whose operands are 'elts'.
5632 ///
5633 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5634 ///
5635 /// FIXME: we'd also like to handle the case where the last elements are zero
5636 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5637 /// There's even a handy isZeroNode for that purpose.
5638 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5639                                         SDLoc &DL, SelectionDAG &DAG,
5640                                         bool isAfterLegalize) {
5641   EVT EltVT = VT.getVectorElementType();
5642   unsigned NumElems = Elts.size();
5643
5644   LoadSDNode *LDBase = nullptr;
5645   unsigned LastLoadedElt = -1U;
5646
5647   // For each element in the initializer, see if we've found a load or an undef.
5648   // If we don't find an initial load element, or later load elements are
5649   // non-consecutive, bail out.
5650   for (unsigned i = 0; i < NumElems; ++i) {
5651     SDValue Elt = Elts[i];
5652
5653     if (!Elt.getNode() ||
5654         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5655       return SDValue();
5656     if (!LDBase) {
5657       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5658         return SDValue();
5659       LDBase = cast<LoadSDNode>(Elt.getNode());
5660       LastLoadedElt = i;
5661       continue;
5662     }
5663     if (Elt.getOpcode() == ISD::UNDEF)
5664       continue;
5665
5666     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5667     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5668       return SDValue();
5669     LastLoadedElt = i;
5670   }
5671
5672   // If we have found an entire vector of loads and undefs, then return a large
5673   // load of the entire vector width starting at the base pointer.  If we found
5674   // consecutive loads for the low half, generate a vzext_load node.
5675   if (LastLoadedElt == NumElems - 1) {
5676
5677     if (isAfterLegalize &&
5678         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5679       return SDValue();
5680
5681     SDValue NewLd = SDValue();
5682
5683     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5684       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5685                           LDBase->getPointerInfo(),
5686                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5687                           LDBase->isInvariant(), 0);
5688     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5689                         LDBase->getPointerInfo(),
5690                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5691                         LDBase->isInvariant(), LDBase->getAlignment());
5692
5693     if (LDBase->hasAnyUseOfValue(1)) {
5694       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5695                                      SDValue(LDBase, 1),
5696                                      SDValue(NewLd.getNode(), 1));
5697       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5698       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5699                              SDValue(NewLd.getNode(), 1));
5700     }
5701
5702     return NewLd;
5703   }
5704   if (NumElems == 4 && LastLoadedElt == 1 &&
5705       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5706     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5707     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5708     SDValue ResNode =
5709         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5710                                 LDBase->getPointerInfo(),
5711                                 LDBase->getAlignment(),
5712                                 false/*isVolatile*/, true/*ReadMem*/,
5713                                 false/*WriteMem*/);
5714
5715     // Make sure the newly-created LOAD is in the same position as LDBase in
5716     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5717     // update uses of LDBase's output chain to use the TokenFactor.
5718     if (LDBase->hasAnyUseOfValue(1)) {
5719       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5720                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5721       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5722       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5723                              SDValue(ResNode.getNode(), 1));
5724     }
5725
5726     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5727   }
5728   return SDValue();
5729 }
5730
5731 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5732 /// to generate a splat value for the following cases:
5733 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5734 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5735 /// a scalar load, or a constant.
5736 /// The VBROADCAST node is returned when a pattern is found,
5737 /// or SDValue() otherwise.
5738 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5739                                     SelectionDAG &DAG) {
5740   if (!Subtarget->hasFp256())
5741     return SDValue();
5742
5743   MVT VT = Op.getSimpleValueType();
5744   SDLoc dl(Op);
5745
5746   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5747          "Unsupported vector type for broadcast.");
5748
5749   SDValue Ld;
5750   bool ConstSplatVal;
5751
5752   switch (Op.getOpcode()) {
5753     default:
5754       // Unknown pattern found.
5755       return SDValue();
5756
5757     case ISD::BUILD_VECTOR: {
5758       // The BUILD_VECTOR node must be a splat.
5759       if (!isSplatVector(Op.getNode()))
5760         return SDValue();
5761
5762       Ld = Op.getOperand(0);
5763       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5764                      Ld.getOpcode() == ISD::ConstantFP);
5765
5766       // The suspected load node has several users. Make sure that all
5767       // of its users are from the BUILD_VECTOR node.
5768       // Constants may have multiple users.
5769       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5770         return SDValue();
5771       break;
5772     }
5773
5774     case ISD::VECTOR_SHUFFLE: {
5775       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5776
5777       // Shuffles must have a splat mask where the first element is
5778       // broadcasted.
5779       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5780         return SDValue();
5781
5782       SDValue Sc = Op.getOperand(0);
5783       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5784           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5785
5786         if (!Subtarget->hasInt256())
5787           return SDValue();
5788
5789         // Use the register form of the broadcast instruction available on AVX2.
5790         if (VT.getSizeInBits() >= 256)
5791           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5792         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5793       }
5794
5795       Ld = Sc.getOperand(0);
5796       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5797                        Ld.getOpcode() == ISD::ConstantFP);
5798
5799       // The scalar_to_vector node and the suspected
5800       // load node must have exactly one user.
5801       // Constants may have multiple users.
5802
5803       // AVX-512 has register version of the broadcast
5804       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5805         Ld.getValueType().getSizeInBits() >= 32;
5806       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5807           !hasRegVer))
5808         return SDValue();
5809       break;
5810     }
5811   }
5812
5813   bool IsGE256 = (VT.getSizeInBits() >= 256);
5814
5815   // Handle the broadcasting a single constant scalar from the constant pool
5816   // into a vector. On Sandybridge it is still better to load a constant vector
5817   // from the constant pool and not to broadcast it from a scalar.
5818   if (ConstSplatVal && Subtarget->hasInt256()) {
5819     EVT CVT = Ld.getValueType();
5820     assert(!CVT.isVector() && "Must not broadcast a vector type");
5821     unsigned ScalarSize = CVT.getSizeInBits();
5822
5823     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5824       const Constant *C = nullptr;
5825       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5826         C = CI->getConstantIntValue();
5827       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5828         C = CF->getConstantFPValue();
5829
5830       assert(C && "Invalid constant type");
5831
5832       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5833       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5834       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5835       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5836                        MachinePointerInfo::getConstantPool(),
5837                        false, false, false, Alignment);
5838
5839       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5840     }
5841   }
5842
5843   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5844   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5845
5846   // Handle AVX2 in-register broadcasts.
5847   if (!IsLoad && Subtarget->hasInt256() &&
5848       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5849     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5850
5851   // The scalar source must be a normal load.
5852   if (!IsLoad)
5853     return SDValue();
5854
5855   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5856     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5857
5858   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5859   // double since there is no vbroadcastsd xmm
5860   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5861     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5862       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5863   }
5864
5865   // Unsupported broadcast.
5866   return SDValue();
5867 }
5868
5869 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5870 /// underlying vector and index.
5871 ///
5872 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5873 /// index.
5874 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5875                                          SDValue ExtIdx) {
5876   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5877   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5878     return Idx;
5879
5880   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5881   // lowered this:
5882   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5883   // to:
5884   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5885   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5886   //                           undef)
5887   //                       Constant<0>)
5888   // In this case the vector is the extract_subvector expression and the index
5889   // is 2, as specified by the shuffle.
5890   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5891   SDValue ShuffleVec = SVOp->getOperand(0);
5892   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5893   assert(ShuffleVecVT.getVectorElementType() ==
5894          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5895
5896   int ShuffleIdx = SVOp->getMaskElt(Idx);
5897   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5898     ExtractedFromVec = ShuffleVec;
5899     return ShuffleIdx;
5900   }
5901   return Idx;
5902 }
5903
5904 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5905   MVT VT = Op.getSimpleValueType();
5906
5907   // Skip if insert_vec_elt is not supported.
5908   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5909   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5910     return SDValue();
5911
5912   SDLoc DL(Op);
5913   unsigned NumElems = Op.getNumOperands();
5914
5915   SDValue VecIn1;
5916   SDValue VecIn2;
5917   SmallVector<unsigned, 4> InsertIndices;
5918   SmallVector<int, 8> Mask(NumElems, -1);
5919
5920   for (unsigned i = 0; i != NumElems; ++i) {
5921     unsigned Opc = Op.getOperand(i).getOpcode();
5922
5923     if (Opc == ISD::UNDEF)
5924       continue;
5925
5926     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5927       // Quit if more than 1 elements need inserting.
5928       if (InsertIndices.size() > 1)
5929         return SDValue();
5930
5931       InsertIndices.push_back(i);
5932       continue;
5933     }
5934
5935     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5936     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5937     // Quit if non-constant index.
5938     if (!isa<ConstantSDNode>(ExtIdx))
5939       return SDValue();
5940     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5941
5942     // Quit if extracted from vector of different type.
5943     if (ExtractedFromVec.getValueType() != VT)
5944       return SDValue();
5945
5946     if (!VecIn1.getNode())
5947       VecIn1 = ExtractedFromVec;
5948     else if (VecIn1 != ExtractedFromVec) {
5949       if (!VecIn2.getNode())
5950         VecIn2 = ExtractedFromVec;
5951       else if (VecIn2 != ExtractedFromVec)
5952         // Quit if more than 2 vectors to shuffle
5953         return SDValue();
5954     }
5955
5956     if (ExtractedFromVec == VecIn1)
5957       Mask[i] = Idx;
5958     else if (ExtractedFromVec == VecIn2)
5959       Mask[i] = Idx + NumElems;
5960   }
5961
5962   if (!VecIn1.getNode())
5963     return SDValue();
5964
5965   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5966   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5967   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5968     unsigned Idx = InsertIndices[i];
5969     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5970                      DAG.getIntPtrConstant(Idx));
5971   }
5972
5973   return NV;
5974 }
5975
5976 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5977 SDValue
5978 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5979
5980   MVT VT = Op.getSimpleValueType();
5981   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5982          "Unexpected type in LowerBUILD_VECTORvXi1!");
5983
5984   SDLoc dl(Op);
5985   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5986     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5987     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5988     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5989   }
5990
5991   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5992     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5993     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5994     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5995   }
5996
5997   bool AllContants = true;
5998   uint64_t Immediate = 0;
5999   int NonConstIdx = -1;
6000   bool IsSplat = true;
6001   unsigned NumNonConsts = 0;
6002   unsigned NumConsts = 0;
6003   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6004     SDValue In = Op.getOperand(idx);
6005     if (In.getOpcode() == ISD::UNDEF)
6006       continue;
6007     if (!isa<ConstantSDNode>(In)) {
6008       AllContants = false;
6009       NonConstIdx = idx;
6010       NumNonConsts++;
6011     }
6012     else {
6013       NumConsts++;
6014       if (cast<ConstantSDNode>(In)->getZExtValue())
6015       Immediate |= (1ULL << idx);
6016     }
6017     if (In != Op.getOperand(0))
6018       IsSplat = false;
6019   }
6020
6021   if (AllContants) {
6022     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6023       DAG.getConstant(Immediate, MVT::i16));
6024     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6025                        DAG.getIntPtrConstant(0));
6026   }
6027
6028   if (NumNonConsts == 1 && NonConstIdx != 0) {
6029     SDValue DstVec;
6030     if (NumConsts) {
6031       SDValue VecAsImm = DAG.getConstant(Immediate,
6032                                          MVT::getIntegerVT(VT.getSizeInBits()));
6033       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6034     }
6035     else 
6036       DstVec = DAG.getUNDEF(VT);
6037     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6038                        Op.getOperand(NonConstIdx),
6039                        DAG.getIntPtrConstant(NonConstIdx));
6040   }
6041   if (!IsSplat && (NonConstIdx != 0))
6042     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6043   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6044   SDValue Select;
6045   if (IsSplat)
6046     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6047                           DAG.getConstant(-1, SelectVT),
6048                           DAG.getConstant(0, SelectVT));
6049   else
6050     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6051                          DAG.getConstant((Immediate | 1), SelectVT),
6052                          DAG.getConstant(Immediate, SelectVT));
6053   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6054 }
6055
6056 /// \brief Return true if \p N implements a horizontal binop and return the
6057 /// operands for the horizontal binop into V0 and V1.
6058 /// 
6059 /// This is a helper function of PerformBUILD_VECTORCombine.
6060 /// This function checks that the build_vector \p N in input implements a
6061 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6062 /// operation to match.
6063 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6064 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6065 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6066 /// arithmetic sub.
6067 ///
6068 /// This function only analyzes elements of \p N whose indices are
6069 /// in range [BaseIdx, LastIdx).
6070 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6071                               SelectionDAG &DAG,
6072                               unsigned BaseIdx, unsigned LastIdx,
6073                               SDValue &V0, SDValue &V1) {
6074   EVT VT = N->getValueType(0);
6075
6076   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6077   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6078          "Invalid Vector in input!");
6079   
6080   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6081   bool CanFold = true;
6082   unsigned ExpectedVExtractIdx = BaseIdx;
6083   unsigned NumElts = LastIdx - BaseIdx;
6084   V0 = DAG.getUNDEF(VT);
6085   V1 = DAG.getUNDEF(VT);
6086
6087   // Check if N implements a horizontal binop.
6088   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6089     SDValue Op = N->getOperand(i + BaseIdx);
6090
6091     // Skip UNDEFs.
6092     if (Op->getOpcode() == ISD::UNDEF) {
6093       // Update the expected vector extract index.
6094       if (i * 2 == NumElts)
6095         ExpectedVExtractIdx = BaseIdx;
6096       ExpectedVExtractIdx += 2;
6097       continue;
6098     }
6099
6100     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6101
6102     if (!CanFold)
6103       break;
6104
6105     SDValue Op0 = Op.getOperand(0);
6106     SDValue Op1 = Op.getOperand(1);
6107
6108     // Try to match the following pattern:
6109     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6110     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6111         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6112         Op0.getOperand(0) == Op1.getOperand(0) &&
6113         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6114         isa<ConstantSDNode>(Op1.getOperand(1)));
6115     if (!CanFold)
6116       break;
6117
6118     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6119     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6120
6121     if (i * 2 < NumElts) {
6122       if (V0.getOpcode() == ISD::UNDEF)
6123         V0 = Op0.getOperand(0);
6124     } else {
6125       if (V1.getOpcode() == ISD::UNDEF)
6126         V1 = Op0.getOperand(0);
6127       if (i * 2 == NumElts)
6128         ExpectedVExtractIdx = BaseIdx;
6129     }
6130
6131     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6132     if (I0 == ExpectedVExtractIdx)
6133       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6134     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6135       // Try to match the following dag sequence:
6136       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6137       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6138     } else
6139       CanFold = false;
6140
6141     ExpectedVExtractIdx += 2;
6142   }
6143
6144   return CanFold;
6145 }
6146
6147 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6148 /// a concat_vector. 
6149 ///
6150 /// This is a helper function of PerformBUILD_VECTORCombine.
6151 /// This function expects two 256-bit vectors called V0 and V1.
6152 /// At first, each vector is split into two separate 128-bit vectors.
6153 /// Then, the resulting 128-bit vectors are used to implement two
6154 /// horizontal binary operations. 
6155 ///
6156 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6157 ///
6158 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6159 /// the two new horizontal binop.
6160 /// When Mode is set, the first horizontal binop dag node would take as input
6161 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6162 /// horizontal binop dag node would take as input the lower 128-bit of V1
6163 /// and the upper 128-bit of V1.
6164 ///   Example:
6165 ///     HADD V0_LO, V0_HI
6166 ///     HADD V1_LO, V1_HI
6167 ///
6168 /// Otherwise, the first horizontal binop dag node takes as input the lower
6169 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6170 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6171 ///   Example:
6172 ///     HADD V0_LO, V1_LO
6173 ///     HADD V0_HI, V1_HI
6174 ///
6175 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6176 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6177 /// the upper 128-bits of the result.
6178 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6179                                      SDLoc DL, SelectionDAG &DAG,
6180                                      unsigned X86Opcode, bool Mode,
6181                                      bool isUndefLO, bool isUndefHI) {
6182   EVT VT = V0.getValueType();
6183   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6184          "Invalid nodes in input!");
6185
6186   unsigned NumElts = VT.getVectorNumElements();
6187   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6188   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6189   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6190   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6191   EVT NewVT = V0_LO.getValueType();
6192
6193   SDValue LO = DAG.getUNDEF(NewVT);
6194   SDValue HI = DAG.getUNDEF(NewVT);
6195
6196   if (Mode) {
6197     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6198     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6199       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6200     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6201       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6202   } else {
6203     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6204     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6205                        V1_LO->getOpcode() != ISD::UNDEF))
6206       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6207
6208     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6209                        V1_HI->getOpcode() != ISD::UNDEF))
6210       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6211   }
6212
6213   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6214 }
6215
6216 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6217 /// sequence of 'vadd + vsub + blendi'.
6218 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6219                            const X86Subtarget *Subtarget) {
6220   SDLoc DL(BV);
6221   EVT VT = BV->getValueType(0);
6222   unsigned NumElts = VT.getVectorNumElements();
6223   SDValue InVec0 = DAG.getUNDEF(VT);
6224   SDValue InVec1 = DAG.getUNDEF(VT);
6225
6226   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6227           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6228
6229   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6231   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6232     return SDValue();
6233
6234   // Odd-numbered elements in the input build vector are obtained from
6235   // adding two integer/float elements.
6236   // Even-numbered elements in the input build vector are obtained from
6237   // subtracting two integer/float elements.
6238   unsigned ExpectedOpcode = ISD::FSUB;
6239   unsigned NextExpectedOpcode = ISD::FADD;
6240   bool AddFound = false;
6241   bool SubFound = false;
6242
6243   for (unsigned i = 0, e = NumElts; i != e; i++) {
6244     SDValue Op = BV->getOperand(i);
6245       
6246     // Skip 'undef' values.
6247     unsigned Opcode = Op.getOpcode();
6248     if (Opcode == ISD::UNDEF) {
6249       std::swap(ExpectedOpcode, NextExpectedOpcode);
6250       continue;
6251     }
6252       
6253     // Early exit if we found an unexpected opcode.
6254     if (Opcode != ExpectedOpcode)
6255       return SDValue();
6256
6257     SDValue Op0 = Op.getOperand(0);
6258     SDValue Op1 = Op.getOperand(1);
6259
6260     // Try to match the following pattern:
6261     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6262     // Early exit if we cannot match that sequence.
6263     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6264         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6265         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6266         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6267         Op0.getOperand(1) != Op1.getOperand(1))
6268       return SDValue();
6269
6270     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6271     if (I0 != i)
6272       return SDValue();
6273
6274     // We found a valid add/sub node. Update the information accordingly.
6275     if (i & 1)
6276       AddFound = true;
6277     else
6278       SubFound = true;
6279
6280     // Update InVec0 and InVec1.
6281     if (InVec0.getOpcode() == ISD::UNDEF)
6282       InVec0 = Op0.getOperand(0);
6283     if (InVec1.getOpcode() == ISD::UNDEF)
6284       InVec1 = Op1.getOperand(0);
6285
6286     // Make sure that operands in input to each add/sub node always
6287     // come from a same pair of vectors.
6288     if (InVec0 != Op0.getOperand(0)) {
6289       if (ExpectedOpcode == ISD::FSUB)
6290         return SDValue();
6291
6292       // FADD is commutable. Try to commute the operands
6293       // and then test again.
6294       std::swap(Op0, Op1);
6295       if (InVec0 != Op0.getOperand(0))
6296         return SDValue();
6297     }
6298
6299     if (InVec1 != Op1.getOperand(0))
6300       return SDValue();
6301
6302     // Update the pair of expected opcodes.
6303     std::swap(ExpectedOpcode, NextExpectedOpcode);
6304   }
6305
6306   // Don't try to fold this build_vector into a VSELECT if it has
6307   // too many UNDEF operands.
6308   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6309       InVec1.getOpcode() != ISD::UNDEF) {
6310     // Emit a sequence of vector add and sub followed by a VSELECT.
6311     // The new VSELECT will be lowered into a BLENDI.
6312     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6313     // and emit a single ADDSUB instruction.
6314     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6315     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6316
6317     // Construct the VSELECT mask.
6318     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6319     EVT SVT = MaskVT.getVectorElementType();
6320     unsigned SVTBits = SVT.getSizeInBits();
6321     SmallVector<SDValue, 8> Ops;
6322
6323     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6324       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6325                             APInt::getAllOnesValue(SVTBits);
6326       SDValue Constant = DAG.getConstant(Value, SVT);
6327       Ops.push_back(Constant);
6328     }
6329
6330     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6331     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6332   }
6333   
6334   return SDValue();
6335 }
6336
6337 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6338                                           const X86Subtarget *Subtarget) {
6339   SDLoc DL(N);
6340   EVT VT = N->getValueType(0);
6341   unsigned NumElts = VT.getVectorNumElements();
6342   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6343   SDValue InVec0, InVec1;
6344
6345   // Try to match an ADDSUB.
6346   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6347       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6348     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6349     if (Value.getNode())
6350       return Value;
6351   }
6352
6353   // Try to match horizontal ADD/SUB.
6354   unsigned NumUndefsLO = 0;
6355   unsigned NumUndefsHI = 0;
6356   unsigned Half = NumElts/2;
6357
6358   // Count the number of UNDEF operands in the build_vector in input.
6359   for (unsigned i = 0, e = Half; i != e; ++i)
6360     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6361       NumUndefsLO++;
6362
6363   for (unsigned i = Half, e = NumElts; i != e; ++i)
6364     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6365       NumUndefsHI++;
6366
6367   // Early exit if this is either a build_vector of all UNDEFs or all the
6368   // operands but one are UNDEF.
6369   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6370     return SDValue();
6371
6372   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6373     // Try to match an SSE3 float HADD/HSUB.
6374     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6375       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6376     
6377     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6378       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6379   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6380     // Try to match an SSSE3 integer HADD/HSUB.
6381     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6382       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6383     
6384     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6385       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6386   }
6387   
6388   if (!Subtarget->hasAVX())
6389     return SDValue();
6390
6391   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6392     // Try to match an AVX horizontal add/sub of packed single/double
6393     // precision floating point values from 256-bit vectors.
6394     SDValue InVec2, InVec3;
6395     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6396         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6397         ((InVec0.getOpcode() == ISD::UNDEF ||
6398           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6399         ((InVec1.getOpcode() == ISD::UNDEF ||
6400           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6401       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6402
6403     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6404         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6405         ((InVec0.getOpcode() == ISD::UNDEF ||
6406           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6407         ((InVec1.getOpcode() == ISD::UNDEF ||
6408           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6409       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6410   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6411     // Try to match an AVX2 horizontal add/sub of signed integers.
6412     SDValue InVec2, InVec3;
6413     unsigned X86Opcode;
6414     bool CanFold = true;
6415
6416     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6417         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6418         ((InVec0.getOpcode() == ISD::UNDEF ||
6419           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6420         ((InVec1.getOpcode() == ISD::UNDEF ||
6421           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6422       X86Opcode = X86ISD::HADD;
6423     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6424         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6425         ((InVec0.getOpcode() == ISD::UNDEF ||
6426           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6427         ((InVec1.getOpcode() == ISD::UNDEF ||
6428           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6429       X86Opcode = X86ISD::HSUB;
6430     else
6431       CanFold = false;
6432
6433     if (CanFold) {
6434       // Fold this build_vector into a single horizontal add/sub.
6435       // Do this only if the target has AVX2.
6436       if (Subtarget->hasAVX2())
6437         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6438  
6439       // Do not try to expand this build_vector into a pair of horizontal
6440       // add/sub if we can emit a pair of scalar add/sub.
6441       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6442         return SDValue();
6443
6444       // Convert this build_vector into a pair of horizontal binop followed by
6445       // a concat vector.
6446       bool isUndefLO = NumUndefsLO == Half;
6447       bool isUndefHI = NumUndefsHI == Half;
6448       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6449                                    isUndefLO, isUndefHI);
6450     }
6451   }
6452
6453   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6454        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6455     unsigned X86Opcode;
6456     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6457       X86Opcode = X86ISD::HADD;
6458     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6459       X86Opcode = X86ISD::HSUB;
6460     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6461       X86Opcode = X86ISD::FHADD;
6462     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6463       X86Opcode = X86ISD::FHSUB;
6464     else
6465       return SDValue();
6466
6467     // Don't try to expand this build_vector into a pair of horizontal add/sub
6468     // if we can simply emit a pair of scalar add/sub.
6469     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6470       return SDValue();
6471
6472     // Convert this build_vector into two horizontal add/sub followed by
6473     // a concat vector.
6474     bool isUndefLO = NumUndefsLO == Half;
6475     bool isUndefHI = NumUndefsHI == Half;
6476     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6477                                  isUndefLO, isUndefHI);
6478   }
6479
6480   return SDValue();
6481 }
6482
6483 SDValue
6484 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6485   SDLoc dl(Op);
6486
6487   MVT VT = Op.getSimpleValueType();
6488   MVT ExtVT = VT.getVectorElementType();
6489   unsigned NumElems = Op.getNumOperands();
6490
6491   // Generate vectors for predicate vectors.
6492   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6493     return LowerBUILD_VECTORvXi1(Op, DAG);
6494
6495   // Vectors containing all zeros can be matched by pxor and xorps later
6496   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6497     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6498     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6499     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6500       return Op;
6501
6502     return getZeroVector(VT, Subtarget, DAG, dl);
6503   }
6504
6505   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6506   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6507   // vpcmpeqd on 256-bit vectors.
6508   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6509     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6510       return Op;
6511
6512     if (!VT.is512BitVector())
6513       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6514   }
6515
6516   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6517   if (Broadcast.getNode())
6518     return Broadcast;
6519
6520   unsigned EVTBits = ExtVT.getSizeInBits();
6521
6522   unsigned NumZero  = 0;
6523   unsigned NumNonZero = 0;
6524   unsigned NonZeros = 0;
6525   bool IsAllConstants = true;
6526   SmallSet<SDValue, 8> Values;
6527   for (unsigned i = 0; i < NumElems; ++i) {
6528     SDValue Elt = Op.getOperand(i);
6529     if (Elt.getOpcode() == ISD::UNDEF)
6530       continue;
6531     Values.insert(Elt);
6532     if (Elt.getOpcode() != ISD::Constant &&
6533         Elt.getOpcode() != ISD::ConstantFP)
6534       IsAllConstants = false;
6535     if (X86::isZeroNode(Elt))
6536       NumZero++;
6537     else {
6538       NonZeros |= (1 << i);
6539       NumNonZero++;
6540     }
6541   }
6542
6543   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6544   if (NumNonZero == 0)
6545     return DAG.getUNDEF(VT);
6546
6547   // Special case for single non-zero, non-undef, element.
6548   if (NumNonZero == 1) {
6549     unsigned Idx = countTrailingZeros(NonZeros);
6550     SDValue Item = Op.getOperand(Idx);
6551
6552     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6553     // the value are obviously zero, truncate the value to i32 and do the
6554     // insertion that way.  Only do this if the value is non-constant or if the
6555     // value is a constant being inserted into element 0.  It is cheaper to do
6556     // a constant pool load than it is to do a movd + shuffle.
6557     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6558         (!IsAllConstants || Idx == 0)) {
6559       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6560         // Handle SSE only.
6561         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6562         EVT VecVT = MVT::v4i32;
6563         unsigned VecElts = 4;
6564
6565         // Truncate the value (which may itself be a constant) to i32, and
6566         // convert it to a vector with movd (S2V+shuffle to zero extend).
6567         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6568         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6569         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6570
6571         // Now we have our 32-bit value zero extended in the low element of
6572         // a vector.  If Idx != 0, swizzle it into place.
6573         if (Idx != 0) {
6574           SmallVector<int, 4> Mask;
6575           Mask.push_back(Idx);
6576           for (unsigned i = 1; i != VecElts; ++i)
6577             Mask.push_back(i);
6578           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6579                                       &Mask[0]);
6580         }
6581         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6582       }
6583     }
6584
6585     // If we have a constant or non-constant insertion into the low element of
6586     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6587     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6588     // depending on what the source datatype is.
6589     if (Idx == 0) {
6590       if (NumZero == 0)
6591         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6592
6593       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6594           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6595         if (VT.is256BitVector() || VT.is512BitVector()) {
6596           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6597           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6598                              Item, DAG.getIntPtrConstant(0));
6599         }
6600         assert(VT.is128BitVector() && "Expected an SSE value type!");
6601         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6602         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6603         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6604       }
6605
6606       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6607         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6608         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6609         if (VT.is256BitVector()) {
6610           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6611           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6612         } else {
6613           assert(VT.is128BitVector() && "Expected an SSE value type!");
6614           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6615         }
6616         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6617       }
6618     }
6619
6620     // Is it a vector logical left shift?
6621     if (NumElems == 2 && Idx == 1 &&
6622         X86::isZeroNode(Op.getOperand(0)) &&
6623         !X86::isZeroNode(Op.getOperand(1))) {
6624       unsigned NumBits = VT.getSizeInBits();
6625       return getVShift(true, VT,
6626                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6627                                    VT, Op.getOperand(1)),
6628                        NumBits/2, DAG, *this, dl);
6629     }
6630
6631     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6632       return SDValue();
6633
6634     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6635     // is a non-constant being inserted into an element other than the low one,
6636     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6637     // movd/movss) to move this into the low element, then shuffle it into
6638     // place.
6639     if (EVTBits == 32) {
6640       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6641
6642       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6643       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6644       SmallVector<int, 8> MaskVec;
6645       for (unsigned i = 0; i != NumElems; ++i)
6646         MaskVec.push_back(i == Idx ? 0 : 1);
6647       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6648     }
6649   }
6650
6651   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6652   if (Values.size() == 1) {
6653     if (EVTBits == 32) {
6654       // Instead of a shuffle like this:
6655       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6656       // Check if it's possible to issue this instead.
6657       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6658       unsigned Idx = countTrailingZeros(NonZeros);
6659       SDValue Item = Op.getOperand(Idx);
6660       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6661         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6662     }
6663     return SDValue();
6664   }
6665
6666   // A vector full of immediates; various special cases are already
6667   // handled, so this is best done with a single constant-pool load.
6668   if (IsAllConstants)
6669     return SDValue();
6670
6671   // For AVX-length vectors, build the individual 128-bit pieces and use
6672   // shuffles to put them in place.
6673   if (VT.is256BitVector() || VT.is512BitVector()) {
6674     SmallVector<SDValue, 64> V;
6675     for (unsigned i = 0; i != NumElems; ++i)
6676       V.push_back(Op.getOperand(i));
6677
6678     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6679
6680     // Build both the lower and upper subvector.
6681     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6682                                 makeArrayRef(&V[0], NumElems/2));
6683     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6684                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6685
6686     // Recreate the wider vector with the lower and upper part.
6687     if (VT.is256BitVector())
6688       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6689     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6690   }
6691
6692   // Let legalizer expand 2-wide build_vectors.
6693   if (EVTBits == 64) {
6694     if (NumNonZero == 1) {
6695       // One half is zero or undef.
6696       unsigned Idx = countTrailingZeros(NonZeros);
6697       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6698                                  Op.getOperand(Idx));
6699       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6700     }
6701     return SDValue();
6702   }
6703
6704   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6705   if (EVTBits == 8 && NumElems == 16) {
6706     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6707                                         Subtarget, *this);
6708     if (V.getNode()) return V;
6709   }
6710
6711   if (EVTBits == 16 && NumElems == 8) {
6712     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6713                                       Subtarget, *this);
6714     if (V.getNode()) return V;
6715   }
6716
6717   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6718   if (EVTBits == 32 && NumElems == 4) {
6719     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6720                                       NumZero, DAG, Subtarget, *this);
6721     if (V.getNode())
6722       return V;
6723   }
6724
6725   // If element VT is == 32 bits, turn it into a number of shuffles.
6726   SmallVector<SDValue, 8> V(NumElems);
6727   if (NumElems == 4 && NumZero > 0) {
6728     for (unsigned i = 0; i < 4; ++i) {
6729       bool isZero = !(NonZeros & (1 << i));
6730       if (isZero)
6731         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6732       else
6733         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6734     }
6735
6736     for (unsigned i = 0; i < 2; ++i) {
6737       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6738         default: break;
6739         case 0:
6740           V[i] = V[i*2];  // Must be a zero vector.
6741           break;
6742         case 1:
6743           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6744           break;
6745         case 2:
6746           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6747           break;
6748         case 3:
6749           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6750           break;
6751       }
6752     }
6753
6754     bool Reverse1 = (NonZeros & 0x3) == 2;
6755     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6756     int MaskVec[] = {
6757       Reverse1 ? 1 : 0,
6758       Reverse1 ? 0 : 1,
6759       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6760       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6761     };
6762     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6763   }
6764
6765   if (Values.size() > 1 && VT.is128BitVector()) {
6766     // Check for a build vector of consecutive loads.
6767     for (unsigned i = 0; i < NumElems; ++i)
6768       V[i] = Op.getOperand(i);
6769
6770     // Check for elements which are consecutive loads.
6771     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6772     if (LD.getNode())
6773       return LD;
6774
6775     // Check for a build vector from mostly shuffle plus few inserting.
6776     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6777     if (Sh.getNode())
6778       return Sh;
6779
6780     // For SSE 4.1, use insertps to put the high elements into the low element.
6781     if (getSubtarget()->hasSSE41()) {
6782       SDValue Result;
6783       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6784         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6785       else
6786         Result = DAG.getUNDEF(VT);
6787
6788       for (unsigned i = 1; i < NumElems; ++i) {
6789         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6790         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6791                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6792       }
6793       return Result;
6794     }
6795
6796     // Otherwise, expand into a number of unpckl*, start by extending each of
6797     // our (non-undef) elements to the full vector width with the element in the
6798     // bottom slot of the vector (which generates no code for SSE).
6799     for (unsigned i = 0; i < NumElems; ++i) {
6800       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6801         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6802       else
6803         V[i] = DAG.getUNDEF(VT);
6804     }
6805
6806     // Next, we iteratively mix elements, e.g. for v4f32:
6807     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6808     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6809     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6810     unsigned EltStride = NumElems >> 1;
6811     while (EltStride != 0) {
6812       for (unsigned i = 0; i < EltStride; ++i) {
6813         // If V[i+EltStride] is undef and this is the first round of mixing,
6814         // then it is safe to just drop this shuffle: V[i] is already in the
6815         // right place, the one element (since it's the first round) being
6816         // inserted as undef can be dropped.  This isn't safe for successive
6817         // rounds because they will permute elements within both vectors.
6818         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6819             EltStride == NumElems/2)
6820           continue;
6821
6822         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6823       }
6824       EltStride >>= 1;
6825     }
6826     return V[0];
6827   }
6828   return SDValue();
6829 }
6830
6831 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6832 // to create 256-bit vectors from two other 128-bit ones.
6833 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6834   SDLoc dl(Op);
6835   MVT ResVT = Op.getSimpleValueType();
6836
6837   assert((ResVT.is256BitVector() ||
6838           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6839
6840   SDValue V1 = Op.getOperand(0);
6841   SDValue V2 = Op.getOperand(1);
6842   unsigned NumElems = ResVT.getVectorNumElements();
6843   if(ResVT.is256BitVector())
6844     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6845
6846   if (Op.getNumOperands() == 4) {
6847     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6848                                 ResVT.getVectorNumElements()/2);
6849     SDValue V3 = Op.getOperand(2);
6850     SDValue V4 = Op.getOperand(3);
6851     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6852       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6853   }
6854   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6855 }
6856
6857 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6858   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6859   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6860          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6861           Op.getNumOperands() == 4)));
6862
6863   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6864   // from two other 128-bit ones.
6865
6866   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6867   return LowerAVXCONCAT_VECTORS(Op, DAG);
6868 }
6869
6870
6871 //===----------------------------------------------------------------------===//
6872 // Vector shuffle lowering
6873 //
6874 // This is an experimental code path for lowering vector shuffles on x86. It is
6875 // designed to handle arbitrary vector shuffles and blends, gracefully
6876 // degrading performance as necessary. It works hard to recognize idiomatic
6877 // shuffles and lower them to optimal instruction patterns without leaving
6878 // a framework that allows reasonably efficient handling of all vector shuffle
6879 // patterns.
6880 //===----------------------------------------------------------------------===//
6881
6882 /// \brief Tiny helper function to identify a no-op mask.
6883 ///
6884 /// This is a somewhat boring predicate function. It checks whether the mask
6885 /// array input, which is assumed to be a single-input shuffle mask of the kind
6886 /// used by the X86 shuffle instructions (not a fully general
6887 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6888 /// in-place shuffle are 'no-op's.
6889 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6890   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6891     if (Mask[i] != -1 && Mask[i] != i)
6892       return false;
6893   return true;
6894 }
6895
6896 /// \brief Helper function to classify a mask as a single-input mask.
6897 ///
6898 /// This isn't a generic single-input test because in the vector shuffle
6899 /// lowering we canonicalize single inputs to be the first input operand. This
6900 /// means we can more quickly test for a single input by only checking whether
6901 /// an input from the second operand exists. We also assume that the size of
6902 /// mask corresponds to the size of the input vectors which isn't true in the
6903 /// fully general case.
6904 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6905   for (int M : Mask)
6906     if (M >= (int)Mask.size())
6907       return false;
6908   return true;
6909 }
6910
6911 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6912 ///
6913 /// This helper function produces an 8-bit shuffle immediate corresponding to
6914 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6915 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6916 /// example.
6917 ///
6918 /// NB: We rely heavily on "undef" masks preserving the input lane.
6919 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6920                                           SelectionDAG &DAG) {
6921   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6922   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6923   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6924   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6925   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6926
6927   unsigned Imm = 0;
6928   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6929   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6930   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6931   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6932   return DAG.getConstant(Imm, MVT::i8);
6933 }
6934
6935 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6936 ///
6937 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6938 /// support for floating point shuffles but not integer shuffles. These
6939 /// instructions will incur a domain crossing penalty on some chips though so
6940 /// it is better to avoid lowering through this for integer vectors where
6941 /// possible.
6942 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6943                                        const X86Subtarget *Subtarget,
6944                                        SelectionDAG &DAG) {
6945   SDLoc DL(Op);
6946   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6947   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6948   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6949   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6950   ArrayRef<int> Mask = SVOp->getMask();
6951   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6952
6953   if (isSingleInputShuffleMask(Mask)) {
6954     // Straight shuffle of a single input vector. Simulate this by using the
6955     // single input as both of the "inputs" to this instruction..
6956     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6957     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6958                        DAG.getConstant(SHUFPDMask, MVT::i8));
6959   }
6960   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6961   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6962
6963   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6964   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6965                      DAG.getConstant(SHUFPDMask, MVT::i8));
6966 }
6967
6968 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6969 ///
6970 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6971 /// the integer unit to minimize domain crossing penalties. However, for blends
6972 /// it falls back to the floating point shuffle operation with appropriate bit
6973 /// casting.
6974 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6975                                        const X86Subtarget *Subtarget,
6976                                        SelectionDAG &DAG) {
6977   SDLoc DL(Op);
6978   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6979   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6980   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6981   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6982   ArrayRef<int> Mask = SVOp->getMask();
6983   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6984
6985   if (isSingleInputShuffleMask(Mask)) {
6986     // Straight shuffle of a single input vector. For everything from SSE2
6987     // onward this has a single fast instruction with no scary immediates.
6988     // We have to map the mask as it is actually a v4i32 shuffle instruction.
6989     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
6990     int WidenedMask[4] = {
6991         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
6992         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
6993     return DAG.getNode(
6994         ISD::BITCAST, DL, MVT::v2i64,
6995         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
6996                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
6997   }
6998
6999   // We implement this with SHUFPD which is pretty lame because it will likely
7000   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7001   // However, all the alternatives are still more cycles and newer chips don't
7002   // have this problem. It would be really nice if x86 had better shuffles here.
7003   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7004   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7005   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7006                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7007 }
7008
7009 /// \brief Lower 4-lane 32-bit floating point shuffles.
7010 ///
7011 /// Uses instructions exclusively from the floating point unit to minimize
7012 /// domain crossing penalties, as these are sufficient to implement all v4f32
7013 /// shuffles.
7014 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7015                                        const X86Subtarget *Subtarget,
7016                                        SelectionDAG &DAG) {
7017   SDLoc DL(Op);
7018   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7019   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7020   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7021   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7022   ArrayRef<int> Mask = SVOp->getMask();
7023   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7024
7025   SDValue LowV = V1, HighV = V2;
7026   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7027
7028   int NumV2Elements =
7029       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7030
7031   if (NumV2Elements == 0)
7032     // Straight shuffle of a single input vector. We pass the input vector to
7033     // both operands to simulate this with a SHUFPS.
7034     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7035                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7036
7037   if (NumV2Elements == 1) {
7038     int V2Index =
7039         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7040         Mask.begin();
7041     // Compute the index adjacent to V2Index and in the same half by toggling
7042     // the low bit.
7043     int V2AdjIndex = V2Index ^ 1;
7044
7045     if (Mask[V2AdjIndex] == -1) {
7046       // Handles all the cases where we have a single V2 element and an undef.
7047       // This will only ever happen in the high lanes because we commute the
7048       // vector otherwise.
7049       if (V2Index < 2)
7050         std::swap(LowV, HighV);
7051       NewMask[V2Index] -= 4;
7052     } else {
7053       // Handle the case where the V2 element ends up adjacent to a V1 element.
7054       // To make this work, blend them together as the first step.
7055       int V1Index = V2AdjIndex;
7056       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7057       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7058                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7059
7060       // Now proceed to reconstruct the final blend as we have the necessary
7061       // high or low half formed.
7062       if (V2Index < 2) {
7063         LowV = V2;
7064         HighV = V1;
7065       } else {
7066         HighV = V2;
7067       }
7068       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7069       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7070     }
7071   } else if (NumV2Elements == 2) {
7072     if (Mask[0] < 4 && Mask[1] < 4) {
7073       // Handle the easy case where we have V1 in the low lanes and V2 in the
7074       // high lanes. We never see this reversed because we sort the shuffle.
7075       NewMask[2] -= 4;
7076       NewMask[3] -= 4;
7077     } else {
7078       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7079       // trying to place elements directly, just blend them and set up the final
7080       // shuffle to place them.
7081
7082       // The first two blend mask elements are for V1, the second two are for
7083       // V2.
7084       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7085                           Mask[2] < 4 ? Mask[2] : Mask[3],
7086                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7087                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7088       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7089                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7090
7091       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7092       // a blend.
7093       LowV = HighV = V1;
7094       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7095       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7096       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7097       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7098     }
7099   }
7100   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7101                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7102 }
7103
7104 /// \brief Lower 4-lane i32 vector shuffles.
7105 ///
7106 /// We try to handle these with integer-domain shuffles where we can, but for
7107 /// blends we use the floating point domain blend instructions.
7108 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7109                                        const X86Subtarget *Subtarget,
7110                                        SelectionDAG &DAG) {
7111   SDLoc DL(Op);
7112   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7113   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7114   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7115   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7116   ArrayRef<int> Mask = SVOp->getMask();
7117   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7118
7119   if (isSingleInputShuffleMask(Mask))
7120     // Straight shuffle of a single input vector. For everything from SSE2
7121     // onward this has a single fast instruction with no scary immediates.
7122     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7123                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7124
7125   // We implement this with SHUFPS because it can blend from two vectors.
7126   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7127   // up the inputs, bypassing domain shift penalties that we would encur if we
7128   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7129   // relevant.
7130   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7131                      DAG.getVectorShuffle(
7132                          MVT::v4f32, DL,
7133                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7134                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7135 }
7136
7137 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7138 /// shuffle lowering, and the most complex part.
7139 ///
7140 /// The lowering strategy is to try to form pairs of input lanes which are
7141 /// targeted at the same half of the final vector, and then use a dword shuffle
7142 /// to place them onto the right half, and finally unpack the paired lanes into
7143 /// their final position.
7144 ///
7145 /// The exact breakdown of how to form these dword pairs and align them on the
7146 /// correct sides is really tricky. See the comments within the function for
7147 /// more of the details.
7148 static SDValue lowerV8I16SingleInputVectorShuffle(
7149     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7150     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7151   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7152   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7153   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7154
7155   SmallVector<int, 4> LoInputs;
7156   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7157                [](int M) { return M >= 0; });
7158   std::sort(LoInputs.begin(), LoInputs.end());
7159   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7160   SmallVector<int, 4> HiInputs;
7161   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7162                [](int M) { return M >= 0; });
7163   std::sort(HiInputs.begin(), HiInputs.end());
7164   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7165   int NumLToL =
7166       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7167   int NumHToL = LoInputs.size() - NumLToL;
7168   int NumLToH =
7169       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7170   int NumHToH = HiInputs.size() - NumLToH;
7171   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7172   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7173   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7174   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7175
7176   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7177   // such inputs we can swap two of the dwords across the half mark and end up
7178   // with <=2 inputs to each half in each half. Once there, we can fall through
7179   // to the generic code below. For example:
7180   //
7181   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7182   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7183   //
7184   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7185   // and 2-2.
7186   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7187                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7188     // Compute the index of dword with only one word among the three inputs in
7189     // a half by taking the sum of the half with three inputs and subtracting
7190     // the sum of the actual three inputs. The difference is the remaining
7191     // slot.
7192     int DWordA = (ThreeInputHalfSum -
7193                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7194                  2;
7195     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7196
7197     int PSHUFDMask[] = {0, 1, 2, 3};
7198     PSHUFDMask[DWordA] = DWordB;
7199     PSHUFDMask[DWordB] = DWordA;
7200     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7201                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7202                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7203                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7204
7205     // Adjust the mask to match the new locations of A and B.
7206     for (int &M : Mask)
7207       if (M != -1 && M/2 == DWordA)
7208         M = 2 * DWordB + M % 2;
7209       else if (M != -1 && M/2 == DWordB)
7210         M = 2 * DWordA + M % 2;
7211
7212     // Recurse back into this routine to re-compute state now that this isn't
7213     // a 3 and 1 problem.
7214     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7215                                 Mask);
7216   };
7217   if (NumLToL == 3 && NumHToL == 1)
7218     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7219   else if (NumLToL == 1 && NumHToL == 3)
7220     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7221   else if (NumLToH == 1 && NumHToH == 3)
7222     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7223   else if (NumLToH == 3 && NumHToH == 1)
7224     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7225
7226   // At this point there are at most two inputs to the low and high halves from
7227   // each half. That means the inputs can always be grouped into dwords and
7228   // those dwords can then be moved to the correct half with a dword shuffle.
7229   // We use at most one low and one high word shuffle to collect these paired
7230   // inputs into dwords, and finally a dword shuffle to place them.
7231   int PSHUFLMask[4] = {-1, -1, -1, -1};
7232   int PSHUFHMask[4] = {-1, -1, -1, -1};
7233   int PSHUFDMask[4] = {-1, -1, -1, -1};
7234
7235   // First fix the masks for all the inputs that are staying in their
7236   // original halves. This will then dictate the targets of the cross-half
7237   // shuffles.
7238   auto fixInPlaceInputs = [&PSHUFDMask](
7239       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7240       MutableArrayRef<int> HalfMask, int HalfOffset) {
7241     if (InPlaceInputs.empty())
7242       return;
7243     if (InPlaceInputs.size() == 1) {
7244       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7245           InPlaceInputs[0] - HalfOffset;
7246       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7247       return;
7248     }
7249
7250     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7251     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7252         InPlaceInputs[0] - HalfOffset;
7253     // Put the second input next to the first so that they are packed into
7254     // a dword. We find the adjacent index by toggling the low bit.
7255     int AdjIndex = InPlaceInputs[0] ^ 1;
7256     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7257     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7258     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7259   };
7260   if (!HToLInputs.empty())
7261     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7262   if (!LToHInputs.empty())
7263     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7264
7265   // Now gather the cross-half inputs and place them into a free dword of
7266   // their target half.
7267   // FIXME: This operation could almost certainly be simplified dramatically to
7268   // look more like the 3-1 fixing operation.
7269   auto moveInputsToRightHalf = [&PSHUFDMask](
7270       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7271       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7272       int SourceOffset, int DestOffset) {
7273     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7274       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7275     };
7276     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7277                                                int Word) {
7278       int LowWord = Word & ~1;
7279       int HighWord = Word | 1;
7280       return isWordClobbered(SourceHalfMask, LowWord) ||
7281              isWordClobbered(SourceHalfMask, HighWord);
7282     };
7283
7284     if (IncomingInputs.empty())
7285       return;
7286
7287     if (ExistingInputs.empty()) {
7288       // Map any dwords with inputs from them into the right half.
7289       for (int Input : IncomingInputs) {
7290         // If the source half mask maps over the inputs, turn those into
7291         // swaps and use the swapped lane.
7292         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7293           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7294             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7295                 Input - SourceOffset;
7296             // We have to swap the uses in our half mask in one sweep.
7297             for (int &M : HalfMask)
7298               if (M == SourceHalfMask[Input - SourceOffset])
7299                 M = Input;
7300               else if (M == Input)
7301                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7302           } else {
7303             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7304                        Input - SourceOffset &&
7305                    "Previous placement doesn't match!");
7306           }
7307           // Note that this correctly re-maps both when we do a swap and when
7308           // we observe the other side of the swap above. We rely on that to
7309           // avoid swapping the members of the input list directly.
7310           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7311         }
7312
7313         // Map the input's dword into the correct half.
7314         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7315           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7316         else
7317           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7318                      Input / 2 &&
7319                  "Previous placement doesn't match!");
7320       }
7321
7322       // And just directly shift any other-half mask elements to be same-half
7323       // as we will have mirrored the dword containing the element into the
7324       // same position within that half.
7325       for (int &M : HalfMask)
7326         if (M >= SourceOffset && M < SourceOffset + 4) {
7327           M = M - SourceOffset + DestOffset;
7328           assert(M >= 0 && "This should never wrap below zero!");
7329         }
7330       return;
7331     }
7332
7333     // Ensure we have the input in a viable dword of its current half. This
7334     // is particularly tricky because the original position may be clobbered
7335     // by inputs being moved and *staying* in that half.
7336     if (IncomingInputs.size() == 1) {
7337       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7338         int InputFixed = std::find(std::begin(SourceHalfMask),
7339                                    std::end(SourceHalfMask), -1) -
7340                          std::begin(SourceHalfMask) + SourceOffset;
7341         SourceHalfMask[InputFixed - SourceOffset] =
7342             IncomingInputs[0] - SourceOffset;
7343         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7344                      InputFixed);
7345         IncomingInputs[0] = InputFixed;
7346       }
7347     } else if (IncomingInputs.size() == 2) {
7348       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7349           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7350         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7351         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7352                "Not all dwords can be clobbered!");
7353         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7354         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7355         for (int &M : HalfMask)
7356           if (M == IncomingInputs[0])
7357             M = SourceDWordBase + SourceOffset;
7358           else if (M == IncomingInputs[1])
7359             M = SourceDWordBase + 1 + SourceOffset;
7360         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7361         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7362       }
7363     } else {
7364       llvm_unreachable("Unhandled input size!");
7365     }
7366
7367     // Now hoist the DWord down to the right half.
7368     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7369     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7370     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7371     for (int Input : IncomingInputs)
7372       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7373                    FreeDWord * 2 + Input % 2);
7374   };
7375   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7376                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7377   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7378                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7379
7380   // Now enact all the shuffles we've computed to move the inputs into their
7381   // target half.
7382   if (!isNoopShuffleMask(PSHUFLMask))
7383     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7384                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7385   if (!isNoopShuffleMask(PSHUFHMask))
7386     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7387                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7388   if (!isNoopShuffleMask(PSHUFDMask))
7389     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7390                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7391                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7392                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7393
7394   // At this point, each half should contain all its inputs, and we can then
7395   // just shuffle them into their final position.
7396   assert(std::count_if(LoMask.begin(), LoMask.end(),
7397                        [](int M) { return M >= 4; }) == 0 &&
7398          "Failed to lift all the high half inputs to the low mask!");
7399   assert(std::count_if(HiMask.begin(), HiMask.end(),
7400                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7401          "Failed to lift all the low half inputs to the high mask!");
7402
7403   // Do a half shuffle for the low mask.
7404   if (!isNoopShuffleMask(LoMask))
7405     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7406                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7407
7408   // Do a half shuffle with the high mask after shifting its values down.
7409   for (int &M : HiMask)
7410     if (M >= 0)
7411       M -= 4;
7412   if (!isNoopShuffleMask(HiMask))
7413     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7414                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7415
7416   return V;
7417 }
7418
7419 /// \brief Detect whether the mask pattern should be lowered through
7420 /// interleaving.
7421 ///
7422 /// This essentially tests whether viewing the mask as an interleaving of two
7423 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7424 /// lowering it through interleaving is a significantly better strategy.
7425 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7426   int NumEvenInputs[2] = {0, 0};
7427   int NumOddInputs[2] = {0, 0};
7428   int NumLoInputs[2] = {0, 0};
7429   int NumHiInputs[2] = {0, 0};
7430   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7431     if (Mask[i] < 0)
7432       continue;
7433
7434     int InputIdx = Mask[i] >= Size;
7435
7436     if (i < Size / 2)
7437       ++NumLoInputs[InputIdx];
7438     else
7439       ++NumHiInputs[InputIdx];
7440
7441     if ((i % 2) == 0)
7442       ++NumEvenInputs[InputIdx];
7443     else
7444       ++NumOddInputs[InputIdx];
7445   }
7446
7447   // The minimum number of cross-input results for both the interleaved and
7448   // split cases. If interleaving results in fewer cross-input results, return
7449   // true.
7450   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7451                                     NumEvenInputs[0] + NumOddInputs[1]);
7452   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7453                               NumLoInputs[0] + NumHiInputs[1]);
7454   return InterleavedCrosses < SplitCrosses;
7455 }
7456
7457 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7458 ///
7459 /// This strategy only works when the inputs from each vector fit into a single
7460 /// half of that vector, and generally there are not so many inputs as to leave
7461 /// the in-place shuffles required highly constrained (and thus expensive). It
7462 /// shifts all the inputs into a single side of both input vectors and then
7463 /// uses an unpack to interleave these inputs in a single vector. At that
7464 /// point, we will fall back on the generic single input shuffle lowering.
7465 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7466                                                  SDValue V2,
7467                                                  MutableArrayRef<int> Mask,
7468                                                  const X86Subtarget *Subtarget,
7469                                                  SelectionDAG &DAG) {
7470   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7471   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7472   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7473   for (int i = 0; i < 8; ++i)
7474     if (Mask[i] >= 0 && Mask[i] < 4)
7475       LoV1Inputs.push_back(i);
7476     else if (Mask[i] >= 4 && Mask[i] < 8)
7477       HiV1Inputs.push_back(i);
7478     else if (Mask[i] >= 8 && Mask[i] < 12)
7479       LoV2Inputs.push_back(i);
7480     else if (Mask[i] >= 12)
7481       HiV2Inputs.push_back(i);
7482
7483   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7484   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7485   (void)NumV1Inputs;
7486   (void)NumV2Inputs;
7487   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7488   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7489   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7490
7491   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7492                      HiV1Inputs.size() + HiV2Inputs.size();
7493
7494   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7495                               ArrayRef<int> HiInputs, bool MoveToLo,
7496                               int MaskOffset) {
7497     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7498     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7499     if (BadInputs.empty())
7500       return V;
7501
7502     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7503     int MoveOffset = MoveToLo ? 0 : 4;
7504
7505     if (GoodInputs.empty()) {
7506       for (int BadInput : BadInputs) {
7507         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7508         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7509       }
7510     } else {
7511       if (GoodInputs.size() == 2) {
7512         // If the low inputs are spread across two dwords, pack them into
7513         // a single dword.
7514         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7515             Mask[GoodInputs[0]] - MaskOffset;
7516         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7517             Mask[GoodInputs[1]] - MaskOffset;
7518         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7519         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7520       } else {
7521         // Otherwise pin the low inputs.
7522         for (int GoodInput : GoodInputs)
7523           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7524       }
7525
7526       int MoveMaskIdx =
7527           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7528           std::begin(MoveMask);
7529       assert(MoveMaskIdx >= MoveOffset && "Established above");
7530
7531       if (BadInputs.size() == 2) {
7532         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7533         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7534         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7535             Mask[BadInputs[0]] - MaskOffset;
7536         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7537             Mask[BadInputs[1]] - MaskOffset;
7538         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7539         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7540       } else {
7541         assert(BadInputs.size() == 1 && "All sizes handled");
7542         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7543         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7544       }
7545     }
7546
7547     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7548                                 MoveMask);
7549   };
7550   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7551                         /*MaskOffset*/ 0);
7552   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7553                         /*MaskOffset*/ 8);
7554
7555   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7556   // cross-half traffic in the final shuffle.
7557
7558   // Munge the mask to be a single-input mask after the unpack merges the
7559   // results.
7560   for (int &M : Mask)
7561     if (M != -1)
7562       M = 2 * (M % 4) + (M / 8);
7563
7564   return DAG.getVectorShuffle(
7565       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7566                                   DL, MVT::v8i16, V1, V2),
7567       DAG.getUNDEF(MVT::v8i16), Mask);
7568 }
7569
7570 /// \brief Generic lowering of 8-lane i16 shuffles.
7571 ///
7572 /// This handles both single-input shuffles and combined shuffle/blends with
7573 /// two inputs. The single input shuffles are immediately delegated to
7574 /// a dedicated lowering routine.
7575 ///
7576 /// The blends are lowered in one of three fundamental ways. If there are few
7577 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7578 /// of the input is significantly cheaper when lowered as an interleaving of
7579 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7580 /// halves of the inputs separately (making them have relatively few inputs)
7581 /// and then concatenate them.
7582 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7583                                        const X86Subtarget *Subtarget,
7584                                        SelectionDAG &DAG) {
7585   SDLoc DL(Op);
7586   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7587   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7588   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7589   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7590   ArrayRef<int> OrigMask = SVOp->getMask();
7591   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7592                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7593   MutableArrayRef<int> Mask(MaskStorage);
7594
7595   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7596
7597   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7598   auto isV2 = [](int M) { return M >= 8; };
7599
7600   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7601   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7602
7603   if (NumV2Inputs == 0)
7604     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7605
7606   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7607                             "to be V1-input shuffles.");
7608
7609   if (NumV1Inputs + NumV2Inputs <= 4)
7610     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7611
7612   // Check whether an interleaving lowering is likely to be more efficient.
7613   // This isn't perfect but it is a strong heuristic that tends to work well on
7614   // the kinds of shuffles that show up in practice.
7615   //
7616   // FIXME: Handle 1x, 2x, and 4x interleaving.
7617   if (shouldLowerAsInterleaving(Mask)) {
7618     // FIXME: Figure out whether we should pack these into the low or high
7619     // halves.
7620
7621     int EMask[8], OMask[8];
7622     for (int i = 0; i < 4; ++i) {
7623       EMask[i] = Mask[2*i];
7624       OMask[i] = Mask[2*i + 1];
7625       EMask[i + 4] = -1;
7626       OMask[i + 4] = -1;
7627     }
7628
7629     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7630     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7631
7632     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7633   }
7634
7635   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7636   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7637
7638   for (int i = 0; i < 4; ++i) {
7639     LoBlendMask[i] = Mask[i];
7640     HiBlendMask[i] = Mask[i + 4];
7641   }
7642
7643   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7644   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7645   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7646   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7647
7648   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7649                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7650 }
7651
7652 /// \brief Generic lowering of v16i8 shuffles.
7653 ///
7654 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7655 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7656 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7657 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7658 /// back together.
7659 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7660                                        const X86Subtarget *Subtarget,
7661                                        SelectionDAG &DAG) {
7662   SDLoc DL(Op);
7663   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7664   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7665   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7666   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7667   ArrayRef<int> OrigMask = SVOp->getMask();
7668   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7669   int MaskStorage[16] = {
7670       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7671       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7672       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7673       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7674   MutableArrayRef<int> Mask(MaskStorage);
7675   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7676   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7677
7678   // For single-input shuffles, there are some nicer lowering tricks we can use.
7679   if (isSingleInputShuffleMask(Mask)) {
7680     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7681     // Notably, this handles splat and partial-splat shuffles more efficiently.
7682     //
7683     // FIXME: We should check for other patterns which can be widened into an
7684     // i16 shuffle as well.
7685     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7686       for (int i = 0; i < 16; i += 2) {
7687         if (Mask[i] != Mask[i + 1])
7688           return false;
7689       }
7690       return true;
7691     };
7692     if (canWidenViaDuplication(Mask)) {
7693       SmallVector<int, 4> LoInputs;
7694       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7695                    [](int M) { return M >= 0 && M < 8; });
7696       std::sort(LoInputs.begin(), LoInputs.end());
7697       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7698                      LoInputs.end());
7699       SmallVector<int, 4> HiInputs;
7700       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7701                    [](int M) { return M >= 8; });
7702       std::sort(HiInputs.begin(), HiInputs.end());
7703       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7704                      HiInputs.end());
7705
7706       bool TargetLo = LoInputs.size() >= HiInputs.size();
7707       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7708       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7709
7710       int ByteMask[16];
7711       SmallDenseMap<int, int, 8> LaneMap;
7712       for (int i = 0; i < 16; ++i)
7713         ByteMask[i] = -1;
7714       for (int I : InPlaceInputs) {
7715         ByteMask[I] = I;
7716         LaneMap[I] = I;
7717       }
7718       int FreeByteIdx = 0;
7719       int TargetOffset = TargetLo ? 0 : 8;
7720       for (int I : MovingInputs) {
7721         // Walk the free index into the byte mask until we find an unoccupied
7722         // spot. We bound this to 8 steps to catch bugs, the pigeonhole
7723         // principle indicates that there *must* be a spot as we can only have
7724         // 8 duplicated inputs. We have to walk the index using modular
7725         // arithmetic to wrap around as necessary.
7726         // FIXME: We could do a much better job of picking an inexpensive slot
7727         // so this doesn't go through the worst case for the byte shuffle.
7728         for (int j = 0; j < 8 && ByteMask[FreeByteIdx + TargetOffset] != -1;
7729              ++j, FreeByteIdx = (FreeByteIdx + 1) % 8)
7730           ;
7731         assert(ByteMask[FreeByteIdx + TargetOffset] == -1 &&
7732                "Failed to find a free byte!");
7733         ByteMask[FreeByteIdx + TargetOffset] = I;
7734         LaneMap[I] = FreeByteIdx + TargetOffset;
7735       }
7736       V1 = DAG.getVectorShuffle(MVT::v16i8, DL, V1, DAG.getUNDEF(MVT::v16i8),
7737                                 ByteMask);
7738       for (int &M : Mask)
7739         if (M != -1)
7740           M = LaneMap[M];
7741
7742       // Unpack the bytes to form the i16s that will be shuffled into place.
7743       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7744                        MVT::v16i8, V1, V1);
7745
7746       int I16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7747       for (int i = 0; i < 16; i += 2) {
7748         if (Mask[i] != -1)
7749           I16Shuffle[i / 2] = Mask[i] - (TargetLo ? 0 : 8);
7750         assert(I16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7751       }
7752       return DAG.getVectorShuffle(MVT::v8i16, DL,
7753                                   DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7754                                   DAG.getUNDEF(MVT::v8i16), I16Shuffle);
7755     }
7756   }
7757
7758   // Check whether an interleaving lowering is likely to be more efficient.
7759   // This isn't perfect but it is a strong heuristic that tends to work well on
7760   // the kinds of shuffles that show up in practice.
7761   //
7762   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7763   if (shouldLowerAsInterleaving(Mask)) {
7764     // FIXME: Figure out whether we should pack these into the low or high
7765     // halves.
7766
7767     int EMask[16], OMask[16];
7768     for (int i = 0; i < 8; ++i) {
7769       EMask[i] = Mask[2*i];
7770       OMask[i] = Mask[2*i + 1];
7771       EMask[i + 8] = -1;
7772       OMask[i + 8] = -1;
7773     }
7774
7775     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7776     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7777
7778     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7779   }
7780   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7781   SDValue LoV1 =
7782       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7783                   DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, Zero));
7784   SDValue HiV1 =
7785       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7786                   DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, Zero));
7787   SDValue LoV2 =
7788       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7789                   DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V2, Zero));
7790   SDValue HiV2 =
7791       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7792                   DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V2, Zero));
7793
7794   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7795   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7796   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7797   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7798
7799   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7800                             MutableArrayRef<int> V1HalfBlendMask,
7801                             MutableArrayRef<int> V2HalfBlendMask) {
7802     for (int i = 0; i < 8; ++i)
7803       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7804         V1HalfBlendMask[i] = HalfMask[i];
7805         HalfMask[i] = i;
7806       } else if (HalfMask[i] >= 16) {
7807         V2HalfBlendMask[i] = HalfMask[i] - 16;
7808         HalfMask[i] = i + 8;
7809       }
7810   };
7811   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7812   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7813
7814   SDValue V1Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1LoBlendMask);
7815   SDValue V2Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2LoBlendMask);
7816   SDValue V1Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1HiBlendMask);
7817   SDValue V2Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2HiBlendMask);
7818
7819   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7820   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7821
7822   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7823 }
7824
7825 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7826 ///
7827 /// This routine breaks down the specific type of 128-bit shuffle and
7828 /// dispatches to the lowering routines accordingly.
7829 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7830                                         MVT VT, const X86Subtarget *Subtarget,
7831                                         SelectionDAG &DAG) {
7832   switch (VT.SimpleTy) {
7833   case MVT::v2i64:
7834     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7835   case MVT::v2f64:
7836     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7837   case MVT::v4i32:
7838     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7839   case MVT::v4f32:
7840     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7841   case MVT::v8i16:
7842     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7843   case MVT::v16i8:
7844     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7845
7846   default:
7847     llvm_unreachable("Unimplemented!");
7848   }
7849 }
7850
7851 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7852 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7853   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7854     if (Mask[i] + 1 != Mask[i+1])
7855       return false;
7856
7857   return true;
7858 }
7859
7860 /// \brief Top-level lowering for x86 vector shuffles.
7861 ///
7862 /// This handles decomposition, canonicalization, and lowering of all x86
7863 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7864 /// above in helper routines. The canonicalization attempts to widen shuffles
7865 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7866 /// s.t. only one of the two inputs needs to be tested, etc.
7867 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7868                                   SelectionDAG &DAG) {
7869   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7870   ArrayRef<int> Mask = SVOp->getMask();
7871   SDValue V1 = Op.getOperand(0);
7872   SDValue V2 = Op.getOperand(1);
7873   MVT VT = Op.getSimpleValueType();
7874   int NumElements = VT.getVectorNumElements();
7875   SDLoc dl(Op);
7876
7877   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7878
7879   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7880   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7881   if (V1IsUndef && V2IsUndef)
7882     return DAG.getUNDEF(VT);
7883
7884   // When we create a shuffle node we put the UNDEF node to second operand,
7885   // but in some cases the first operand may be transformed to UNDEF.
7886   // In this case we should just commute the node.
7887   if (V1IsUndef)
7888     return CommuteVectorShuffle(SVOp, DAG);
7889
7890   // Check for non-undef masks pointing at an undef vector and make the masks
7891   // undef as well. This makes it easier to match the shuffle based solely on
7892   // the mask.
7893   if (V2IsUndef)
7894     for (int M : Mask)
7895       if (M >= NumElements) {
7896         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7897         for (int &M : NewMask)
7898           if (M >= NumElements)
7899             M = -1;
7900         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7901       }
7902
7903   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7904   // lanes but wider integers. We cap this to not form integers larger than i64
7905   // but it might be interesting to form i128 integers to handle flipping the
7906   // low and high halves of AVX 256-bit vectors.
7907   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7908       areAdjacentMasksSequential(Mask)) {
7909     SmallVector<int, 8> NewMask;
7910     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7911       NewMask.push_back(Mask[i] / 2);
7912     MVT NewVT =
7913         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7914                          VT.getVectorNumElements() / 2);
7915     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7916     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7917     return DAG.getNode(ISD::BITCAST, dl, VT,
7918                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7919   }
7920
7921   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7922   for (int M : SVOp->getMask())
7923     if (M < 0)
7924       ++NumUndefElements;
7925     else if (M < NumElements)
7926       ++NumV1Elements;
7927     else
7928       ++NumV2Elements;
7929
7930   // Commute the shuffle as needed such that more elements come from V1 than
7931   // V2. This allows us to match the shuffle pattern strictly on how many
7932   // elements come from V1 without handling the symmetric cases.
7933   if (NumV2Elements > NumV1Elements)
7934     return CommuteVectorShuffle(SVOp, DAG);
7935
7936   // When the number of V1 and V2 elements are the same, try to minimize the
7937   // number of uses of V2 in the low half of the vector.
7938   if (NumV1Elements == NumV2Elements) {
7939     int LowV1Elements = 0, LowV2Elements = 0;
7940     for (int M : SVOp->getMask().slice(0, NumElements / 2))
7941       if (M >= NumElements)
7942         ++LowV2Elements;
7943       else if (M >= 0)
7944         ++LowV1Elements;
7945     if (LowV2Elements > LowV1Elements)
7946       return CommuteVectorShuffle(SVOp, DAG);
7947   }
7948
7949   // For each vector width, delegate to a specialized lowering routine.
7950   if (VT.getSizeInBits() == 128)
7951     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
7952
7953   llvm_unreachable("Unimplemented!");
7954 }
7955
7956
7957 //===----------------------------------------------------------------------===//
7958 // Legacy vector shuffle lowering
7959 //
7960 // This code is the legacy code handling vector shuffles until the above
7961 // replaces its functionality and performance.
7962 //===----------------------------------------------------------------------===//
7963
7964 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
7965                         bool hasInt256, unsigned *MaskOut = nullptr) {
7966   MVT EltVT = VT.getVectorElementType();
7967
7968   // There is no blend with immediate in AVX-512.
7969   if (VT.is512BitVector())
7970     return false;
7971
7972   if (!hasSSE41 || EltVT == MVT::i8)
7973     return false;
7974   if (!hasInt256 && VT == MVT::v16i16)
7975     return false;
7976
7977   unsigned MaskValue = 0;
7978   unsigned NumElems = VT.getVectorNumElements();
7979   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7980   unsigned NumLanes = (NumElems - 1) / 8 + 1;
7981   unsigned NumElemsInLane = NumElems / NumLanes;
7982
7983   // Blend for v16i16 should be symetric for the both lanes.
7984   for (unsigned i = 0; i < NumElemsInLane; ++i) {
7985
7986     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
7987     int EltIdx = MaskVals[i];
7988
7989     if ((EltIdx < 0 || EltIdx == (int)i) &&
7990         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
7991       continue;
7992
7993     if (((unsigned)EltIdx == (i + NumElems)) &&
7994         (SndLaneEltIdx < 0 ||
7995          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
7996       MaskValue |= (1 << i);
7997     else
7998       return false;
7999   }
8000
8001   if (MaskOut)
8002     *MaskOut = MaskValue;
8003   return true;
8004 }
8005
8006 // Try to lower a shuffle node into a simple blend instruction.
8007 // This function assumes isBlendMask returns true for this
8008 // SuffleVectorSDNode
8009 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8010                                           unsigned MaskValue,
8011                                           const X86Subtarget *Subtarget,
8012                                           SelectionDAG &DAG) {
8013   MVT VT = SVOp->getSimpleValueType(0);
8014   MVT EltVT = VT.getVectorElementType();
8015   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8016                      Subtarget->hasInt256() && "Trying to lower a "
8017                                                "VECTOR_SHUFFLE to a Blend but "
8018                                                "with the wrong mask"));
8019   SDValue V1 = SVOp->getOperand(0);
8020   SDValue V2 = SVOp->getOperand(1);
8021   SDLoc dl(SVOp);
8022   unsigned NumElems = VT.getVectorNumElements();
8023
8024   // Convert i32 vectors to floating point if it is not AVX2.
8025   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8026   MVT BlendVT = VT;
8027   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8028     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8029                                NumElems);
8030     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8031     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8032   }
8033
8034   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8035                             DAG.getConstant(MaskValue, MVT::i32));
8036   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8037 }
8038
8039 /// In vector type \p VT, return true if the element at index \p InputIdx
8040 /// falls on a different 128-bit lane than \p OutputIdx.
8041 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8042                                      unsigned OutputIdx) {
8043   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8044   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8045 }
8046
8047 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8048 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8049 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8050 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8051 /// zero.
8052 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8053                          SelectionDAG &DAG) {
8054   MVT VT = V1.getSimpleValueType();
8055   assert(VT.is128BitVector() || VT.is256BitVector());
8056
8057   MVT EltVT = VT.getVectorElementType();
8058   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8059   unsigned NumElts = VT.getVectorNumElements();
8060
8061   SmallVector<SDValue, 32> PshufbMask;
8062   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8063     int InputIdx = MaskVals[OutputIdx];
8064     unsigned InputByteIdx;
8065
8066     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8067       InputByteIdx = 0x80;
8068     else {
8069       // Cross lane is not allowed.
8070       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8071         return SDValue();
8072       InputByteIdx = InputIdx * EltSizeInBytes;
8073       // Index is an byte offset within the 128-bit lane.
8074       InputByteIdx &= 0xf;
8075     }
8076
8077     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8078       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8079       if (InputByteIdx != 0x80)
8080         ++InputByteIdx;
8081     }
8082   }
8083
8084   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8085   if (ShufVT != VT)
8086     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8087   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8088                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8089 }
8090
8091 // v8i16 shuffles - Prefer shuffles in the following order:
8092 // 1. [all]   pshuflw, pshufhw, optional move
8093 // 2. [ssse3] 1 x pshufb
8094 // 3. [ssse3] 2 x pshufb + 1 x por
8095 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8096 static SDValue
8097 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8098                          SelectionDAG &DAG) {
8099   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8100   SDValue V1 = SVOp->getOperand(0);
8101   SDValue V2 = SVOp->getOperand(1);
8102   SDLoc dl(SVOp);
8103   SmallVector<int, 8> MaskVals;
8104
8105   // Determine if more than 1 of the words in each of the low and high quadwords
8106   // of the result come from the same quadword of one of the two inputs.  Undef
8107   // mask values count as coming from any quadword, for better codegen.
8108   //
8109   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8110   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8111   unsigned LoQuad[] = { 0, 0, 0, 0 };
8112   unsigned HiQuad[] = { 0, 0, 0, 0 };
8113   // Indices of quads used.
8114   std::bitset<4> InputQuads;
8115   for (unsigned i = 0; i < 8; ++i) {
8116     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8117     int EltIdx = SVOp->getMaskElt(i);
8118     MaskVals.push_back(EltIdx);
8119     if (EltIdx < 0) {
8120       ++Quad[0];
8121       ++Quad[1];
8122       ++Quad[2];
8123       ++Quad[3];
8124       continue;
8125     }
8126     ++Quad[EltIdx / 4];
8127     InputQuads.set(EltIdx / 4);
8128   }
8129
8130   int BestLoQuad = -1;
8131   unsigned MaxQuad = 1;
8132   for (unsigned i = 0; i < 4; ++i) {
8133     if (LoQuad[i] > MaxQuad) {
8134       BestLoQuad = i;
8135       MaxQuad = LoQuad[i];
8136     }
8137   }
8138
8139   int BestHiQuad = -1;
8140   MaxQuad = 1;
8141   for (unsigned i = 0; i < 4; ++i) {
8142     if (HiQuad[i] > MaxQuad) {
8143       BestHiQuad = i;
8144       MaxQuad = HiQuad[i];
8145     }
8146   }
8147
8148   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8149   // of the two input vectors, shuffle them into one input vector so only a
8150   // single pshufb instruction is necessary. If there are more than 2 input
8151   // quads, disable the next transformation since it does not help SSSE3.
8152   bool V1Used = InputQuads[0] || InputQuads[1];
8153   bool V2Used = InputQuads[2] || InputQuads[3];
8154   if (Subtarget->hasSSSE3()) {
8155     if (InputQuads.count() == 2 && V1Used && V2Used) {
8156       BestLoQuad = InputQuads[0] ? 0 : 1;
8157       BestHiQuad = InputQuads[2] ? 2 : 3;
8158     }
8159     if (InputQuads.count() > 2) {
8160       BestLoQuad = -1;
8161       BestHiQuad = -1;
8162     }
8163   }
8164
8165   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8166   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8167   // words from all 4 input quadwords.
8168   SDValue NewV;
8169   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8170     int MaskV[] = {
8171       BestLoQuad < 0 ? 0 : BestLoQuad,
8172       BestHiQuad < 0 ? 1 : BestHiQuad
8173     };
8174     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8175                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8176                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8177     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8178
8179     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8180     // source words for the shuffle, to aid later transformations.
8181     bool AllWordsInNewV = true;
8182     bool InOrder[2] = { true, true };
8183     for (unsigned i = 0; i != 8; ++i) {
8184       int idx = MaskVals[i];
8185       if (idx != (int)i)
8186         InOrder[i/4] = false;
8187       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8188         continue;
8189       AllWordsInNewV = false;
8190       break;
8191     }
8192
8193     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8194     if (AllWordsInNewV) {
8195       for (int i = 0; i != 8; ++i) {
8196         int idx = MaskVals[i];
8197         if (idx < 0)
8198           continue;
8199         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8200         if ((idx != i) && idx < 4)
8201           pshufhw = false;
8202         if ((idx != i) && idx > 3)
8203           pshuflw = false;
8204       }
8205       V1 = NewV;
8206       V2Used = false;
8207       BestLoQuad = 0;
8208       BestHiQuad = 1;
8209     }
8210
8211     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8212     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8213     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8214       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8215       unsigned TargetMask = 0;
8216       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8217                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8218       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8219       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8220                              getShufflePSHUFLWImmediate(SVOp);
8221       V1 = NewV.getOperand(0);
8222       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8223     }
8224   }
8225
8226   // Promote splats to a larger type which usually leads to more efficient code.
8227   // FIXME: Is this true if pshufb is available?
8228   if (SVOp->isSplat())
8229     return PromoteSplat(SVOp, DAG);
8230
8231   // If we have SSSE3, and all words of the result are from 1 input vector,
8232   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8233   // is present, fall back to case 4.
8234   if (Subtarget->hasSSSE3()) {
8235     SmallVector<SDValue,16> pshufbMask;
8236
8237     // If we have elements from both input vectors, set the high bit of the
8238     // shuffle mask element to zero out elements that come from V2 in the V1
8239     // mask, and elements that come from V1 in the V2 mask, so that the two
8240     // results can be OR'd together.
8241     bool TwoInputs = V1Used && V2Used;
8242     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8243     if (!TwoInputs)
8244       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8245
8246     // Calculate the shuffle mask for the second input, shuffle it, and
8247     // OR it with the first shuffled input.
8248     CommuteVectorShuffleMask(MaskVals, 8);
8249     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8250     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8251     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8252   }
8253
8254   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8255   // and update MaskVals with new element order.
8256   std::bitset<8> InOrder;
8257   if (BestLoQuad >= 0) {
8258     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8259     for (int i = 0; i != 4; ++i) {
8260       int idx = MaskVals[i];
8261       if (idx < 0) {
8262         InOrder.set(i);
8263       } else if ((idx / 4) == BestLoQuad) {
8264         MaskV[i] = idx & 3;
8265         InOrder.set(i);
8266       }
8267     }
8268     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8269                                 &MaskV[0]);
8270
8271     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8272       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8273       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8274                                   NewV.getOperand(0),
8275                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8276     }
8277   }
8278
8279   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8280   // and update MaskVals with the new element order.
8281   if (BestHiQuad >= 0) {
8282     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8283     for (unsigned i = 4; i != 8; ++i) {
8284       int idx = MaskVals[i];
8285       if (idx < 0) {
8286         InOrder.set(i);
8287       } else if ((idx / 4) == BestHiQuad) {
8288         MaskV[i] = (idx & 3) + 4;
8289         InOrder.set(i);
8290       }
8291     }
8292     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8293                                 &MaskV[0]);
8294
8295     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8296       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8297       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8298                                   NewV.getOperand(0),
8299                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8300     }
8301   }
8302
8303   // In case BestHi & BestLo were both -1, which means each quadword has a word
8304   // from each of the four input quadwords, calculate the InOrder bitvector now
8305   // before falling through to the insert/extract cleanup.
8306   if (BestLoQuad == -1 && BestHiQuad == -1) {
8307     NewV = V1;
8308     for (int i = 0; i != 8; ++i)
8309       if (MaskVals[i] < 0 || MaskVals[i] == i)
8310         InOrder.set(i);
8311   }
8312
8313   // The other elements are put in the right place using pextrw and pinsrw.
8314   for (unsigned i = 0; i != 8; ++i) {
8315     if (InOrder[i])
8316       continue;
8317     int EltIdx = MaskVals[i];
8318     if (EltIdx < 0)
8319       continue;
8320     SDValue ExtOp = (EltIdx < 8) ?
8321       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8322                   DAG.getIntPtrConstant(EltIdx)) :
8323       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8324                   DAG.getIntPtrConstant(EltIdx - 8));
8325     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8326                        DAG.getIntPtrConstant(i));
8327   }
8328   return NewV;
8329 }
8330
8331 /// \brief v16i16 shuffles
8332 ///
8333 /// FIXME: We only support generation of a single pshufb currently.  We can
8334 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8335 /// well (e.g 2 x pshufb + 1 x por).
8336 static SDValue
8337 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8338   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8339   SDValue V1 = SVOp->getOperand(0);
8340   SDValue V2 = SVOp->getOperand(1);
8341   SDLoc dl(SVOp);
8342
8343   if (V2.getOpcode() != ISD::UNDEF)
8344     return SDValue();
8345
8346   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8347   return getPSHUFB(MaskVals, V1, dl, DAG);
8348 }
8349
8350 // v16i8 shuffles - Prefer shuffles in the following order:
8351 // 1. [ssse3] 1 x pshufb
8352 // 2. [ssse3] 2 x pshufb + 1 x por
8353 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8354 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8355                                         const X86Subtarget* Subtarget,
8356                                         SelectionDAG &DAG) {
8357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8358   SDValue V1 = SVOp->getOperand(0);
8359   SDValue V2 = SVOp->getOperand(1);
8360   SDLoc dl(SVOp);
8361   ArrayRef<int> MaskVals = SVOp->getMask();
8362
8363   // Promote splats to a larger type which usually leads to more efficient code.
8364   // FIXME: Is this true if pshufb is available?
8365   if (SVOp->isSplat())
8366     return PromoteSplat(SVOp, DAG);
8367
8368   // If we have SSSE3, case 1 is generated when all result bytes come from
8369   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8370   // present, fall back to case 3.
8371
8372   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8373   if (Subtarget->hasSSSE3()) {
8374     SmallVector<SDValue,16> pshufbMask;
8375
8376     // If all result elements are from one input vector, then only translate
8377     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8378     //
8379     // Otherwise, we have elements from both input vectors, and must zero out
8380     // elements that come from V2 in the first mask, and V1 in the second mask
8381     // so that we can OR them together.
8382     for (unsigned i = 0; i != 16; ++i) {
8383       int EltIdx = MaskVals[i];
8384       if (EltIdx < 0 || EltIdx >= 16)
8385         EltIdx = 0x80;
8386       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8387     }
8388     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8389                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8390                                  MVT::v16i8, pshufbMask));
8391
8392     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8393     // the 2nd operand if it's undefined or zero.
8394     if (V2.getOpcode() == ISD::UNDEF ||
8395         ISD::isBuildVectorAllZeros(V2.getNode()))
8396       return V1;
8397
8398     // Calculate the shuffle mask for the second input, shuffle it, and
8399     // OR it with the first shuffled input.
8400     pshufbMask.clear();
8401     for (unsigned i = 0; i != 16; ++i) {
8402       int EltIdx = MaskVals[i];
8403       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8404       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8405     }
8406     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8407                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8408                                  MVT::v16i8, pshufbMask));
8409     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8410   }
8411
8412   // No SSSE3 - Calculate in place words and then fix all out of place words
8413   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8414   // the 16 different words that comprise the two doublequadword input vectors.
8415   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8416   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8417   SDValue NewV = V1;
8418   for (int i = 0; i != 8; ++i) {
8419     int Elt0 = MaskVals[i*2];
8420     int Elt1 = MaskVals[i*2+1];
8421
8422     // This word of the result is all undef, skip it.
8423     if (Elt0 < 0 && Elt1 < 0)
8424       continue;
8425
8426     // This word of the result is already in the correct place, skip it.
8427     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8428       continue;
8429
8430     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8431     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8432     SDValue InsElt;
8433
8434     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8435     // using a single extract together, load it and store it.
8436     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8437       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8438                            DAG.getIntPtrConstant(Elt1 / 2));
8439       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8440                         DAG.getIntPtrConstant(i));
8441       continue;
8442     }
8443
8444     // If Elt1 is defined, extract it from the appropriate source.  If the
8445     // source byte is not also odd, shift the extracted word left 8 bits
8446     // otherwise clear the bottom 8 bits if we need to do an or.
8447     if (Elt1 >= 0) {
8448       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8449                            DAG.getIntPtrConstant(Elt1 / 2));
8450       if ((Elt1 & 1) == 0)
8451         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8452                              DAG.getConstant(8,
8453                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8454       else if (Elt0 >= 0)
8455         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8456                              DAG.getConstant(0xFF00, MVT::i16));
8457     }
8458     // If Elt0 is defined, extract it from the appropriate source.  If the
8459     // source byte is not also even, shift the extracted word right 8 bits. If
8460     // Elt1 was also defined, OR the extracted values together before
8461     // inserting them in the result.
8462     if (Elt0 >= 0) {
8463       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8464                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8465       if ((Elt0 & 1) != 0)
8466         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8467                               DAG.getConstant(8,
8468                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8469       else if (Elt1 >= 0)
8470         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8471                              DAG.getConstant(0x00FF, MVT::i16));
8472       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8473                          : InsElt0;
8474     }
8475     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8476                        DAG.getIntPtrConstant(i));
8477   }
8478   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8479 }
8480
8481 // v32i8 shuffles - Translate to VPSHUFB if possible.
8482 static
8483 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8484                                  const X86Subtarget *Subtarget,
8485                                  SelectionDAG &DAG) {
8486   MVT VT = SVOp->getSimpleValueType(0);
8487   SDValue V1 = SVOp->getOperand(0);
8488   SDValue V2 = SVOp->getOperand(1);
8489   SDLoc dl(SVOp);
8490   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8491
8492   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8493   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8494   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8495
8496   // VPSHUFB may be generated if
8497   // (1) one of input vector is undefined or zeroinitializer.
8498   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8499   // And (2) the mask indexes don't cross the 128-bit lane.
8500   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8501       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8502     return SDValue();
8503
8504   if (V1IsAllZero && !V2IsAllZero) {
8505     CommuteVectorShuffleMask(MaskVals, 32);
8506     V1 = V2;
8507   }
8508   return getPSHUFB(MaskVals, V1, dl, DAG);
8509 }
8510
8511 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8512 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8513 /// done when every pair / quad of shuffle mask elements point to elements in
8514 /// the right sequence. e.g.
8515 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8516 static
8517 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8518                                  SelectionDAG &DAG) {
8519   MVT VT = SVOp->getSimpleValueType(0);
8520   SDLoc dl(SVOp);
8521   unsigned NumElems = VT.getVectorNumElements();
8522   MVT NewVT;
8523   unsigned Scale;
8524   switch (VT.SimpleTy) {
8525   default: llvm_unreachable("Unexpected!");
8526   case MVT::v2i64:
8527   case MVT::v2f64:
8528            return SDValue(SVOp, 0);
8529   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8530   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8531   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8532   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8533   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8534   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8535   }
8536
8537   SmallVector<int, 8> MaskVec;
8538   for (unsigned i = 0; i != NumElems; i += Scale) {
8539     int StartIdx = -1;
8540     for (unsigned j = 0; j != Scale; ++j) {
8541       int EltIdx = SVOp->getMaskElt(i+j);
8542       if (EltIdx < 0)
8543         continue;
8544       if (StartIdx < 0)
8545         StartIdx = (EltIdx / Scale);
8546       if (EltIdx != (int)(StartIdx*Scale + j))
8547         return SDValue();
8548     }
8549     MaskVec.push_back(StartIdx);
8550   }
8551
8552   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8553   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8554   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8555 }
8556
8557 /// getVZextMovL - Return a zero-extending vector move low node.
8558 ///
8559 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8560                             SDValue SrcOp, SelectionDAG &DAG,
8561                             const X86Subtarget *Subtarget, SDLoc dl) {
8562   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8563     LoadSDNode *LD = nullptr;
8564     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8565       LD = dyn_cast<LoadSDNode>(SrcOp);
8566     if (!LD) {
8567       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8568       // instead.
8569       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8570       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8571           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8572           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8573           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8574         // PR2108
8575         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8576         return DAG.getNode(ISD::BITCAST, dl, VT,
8577                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8578                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8579                                                    OpVT,
8580                                                    SrcOp.getOperand(0)
8581                                                           .getOperand(0))));
8582       }
8583     }
8584   }
8585
8586   return DAG.getNode(ISD::BITCAST, dl, VT,
8587                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8588                                  DAG.getNode(ISD::BITCAST, dl,
8589                                              OpVT, SrcOp)));
8590 }
8591
8592 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8593 /// which could not be matched by any known target speficic shuffle
8594 static SDValue
8595 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8596
8597   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8598   if (NewOp.getNode())
8599     return NewOp;
8600
8601   MVT VT = SVOp->getSimpleValueType(0);
8602
8603   unsigned NumElems = VT.getVectorNumElements();
8604   unsigned NumLaneElems = NumElems / 2;
8605
8606   SDLoc dl(SVOp);
8607   MVT EltVT = VT.getVectorElementType();
8608   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8609   SDValue Output[2];
8610
8611   SmallVector<int, 16> Mask;
8612   for (unsigned l = 0; l < 2; ++l) {
8613     // Build a shuffle mask for the output, discovering on the fly which
8614     // input vectors to use as shuffle operands (recorded in InputUsed).
8615     // If building a suitable shuffle vector proves too hard, then bail
8616     // out with UseBuildVector set.
8617     bool UseBuildVector = false;
8618     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8619     unsigned LaneStart = l * NumLaneElems;
8620     for (unsigned i = 0; i != NumLaneElems; ++i) {
8621       // The mask element.  This indexes into the input.
8622       int Idx = SVOp->getMaskElt(i+LaneStart);
8623       if (Idx < 0) {
8624         // the mask element does not index into any input vector.
8625         Mask.push_back(-1);
8626         continue;
8627       }
8628
8629       // The input vector this mask element indexes into.
8630       int Input = Idx / NumLaneElems;
8631
8632       // Turn the index into an offset from the start of the input vector.
8633       Idx -= Input * NumLaneElems;
8634
8635       // Find or create a shuffle vector operand to hold this input.
8636       unsigned OpNo;
8637       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8638         if (InputUsed[OpNo] == Input)
8639           // This input vector is already an operand.
8640           break;
8641         if (InputUsed[OpNo] < 0) {
8642           // Create a new operand for this input vector.
8643           InputUsed[OpNo] = Input;
8644           break;
8645         }
8646       }
8647
8648       if (OpNo >= array_lengthof(InputUsed)) {
8649         // More than two input vectors used!  Give up on trying to create a
8650         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8651         UseBuildVector = true;
8652         break;
8653       }
8654
8655       // Add the mask index for the new shuffle vector.
8656       Mask.push_back(Idx + OpNo * NumLaneElems);
8657     }
8658
8659     if (UseBuildVector) {
8660       SmallVector<SDValue, 16> SVOps;
8661       for (unsigned i = 0; i != NumLaneElems; ++i) {
8662         // The mask element.  This indexes into the input.
8663         int Idx = SVOp->getMaskElt(i+LaneStart);
8664         if (Idx < 0) {
8665           SVOps.push_back(DAG.getUNDEF(EltVT));
8666           continue;
8667         }
8668
8669         // The input vector this mask element indexes into.
8670         int Input = Idx / NumElems;
8671
8672         // Turn the index into an offset from the start of the input vector.
8673         Idx -= Input * NumElems;
8674
8675         // Extract the vector element by hand.
8676         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8677                                     SVOp->getOperand(Input),
8678                                     DAG.getIntPtrConstant(Idx)));
8679       }
8680
8681       // Construct the output using a BUILD_VECTOR.
8682       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8683     } else if (InputUsed[0] < 0) {
8684       // No input vectors were used! The result is undefined.
8685       Output[l] = DAG.getUNDEF(NVT);
8686     } else {
8687       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8688                                         (InputUsed[0] % 2) * NumLaneElems,
8689                                         DAG, dl);
8690       // If only one input was used, use an undefined vector for the other.
8691       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8692         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8693                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8694       // At least one input vector was used. Create a new shuffle vector.
8695       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8696     }
8697
8698     Mask.clear();
8699   }
8700
8701   // Concatenate the result back
8702   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8703 }
8704
8705 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8706 /// 4 elements, and match them with several different shuffle types.
8707 static SDValue
8708 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8709   SDValue V1 = SVOp->getOperand(0);
8710   SDValue V2 = SVOp->getOperand(1);
8711   SDLoc dl(SVOp);
8712   MVT VT = SVOp->getSimpleValueType(0);
8713
8714   assert(VT.is128BitVector() && "Unsupported vector size");
8715
8716   std::pair<int, int> Locs[4];
8717   int Mask1[] = { -1, -1, -1, -1 };
8718   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8719
8720   unsigned NumHi = 0;
8721   unsigned NumLo = 0;
8722   for (unsigned i = 0; i != 4; ++i) {
8723     int Idx = PermMask[i];
8724     if (Idx < 0) {
8725       Locs[i] = std::make_pair(-1, -1);
8726     } else {
8727       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8728       if (Idx < 4) {
8729         Locs[i] = std::make_pair(0, NumLo);
8730         Mask1[NumLo] = Idx;
8731         NumLo++;
8732       } else {
8733         Locs[i] = std::make_pair(1, NumHi);
8734         if (2+NumHi < 4)
8735           Mask1[2+NumHi] = Idx;
8736         NumHi++;
8737       }
8738     }
8739   }
8740
8741   if (NumLo <= 2 && NumHi <= 2) {
8742     // If no more than two elements come from either vector. This can be
8743     // implemented with two shuffles. First shuffle gather the elements.
8744     // The second shuffle, which takes the first shuffle as both of its
8745     // vector operands, put the elements into the right order.
8746     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8747
8748     int Mask2[] = { -1, -1, -1, -1 };
8749
8750     for (unsigned i = 0; i != 4; ++i)
8751       if (Locs[i].first != -1) {
8752         unsigned Idx = (i < 2) ? 0 : 4;
8753         Idx += Locs[i].first * 2 + Locs[i].second;
8754         Mask2[i] = Idx;
8755       }
8756
8757     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8758   }
8759
8760   if (NumLo == 3 || NumHi == 3) {
8761     // Otherwise, we must have three elements from one vector, call it X, and
8762     // one element from the other, call it Y.  First, use a shufps to build an
8763     // intermediate vector with the one element from Y and the element from X
8764     // that will be in the same half in the final destination (the indexes don't
8765     // matter). Then, use a shufps to build the final vector, taking the half
8766     // containing the element from Y from the intermediate, and the other half
8767     // from X.
8768     if (NumHi == 3) {
8769       // Normalize it so the 3 elements come from V1.
8770       CommuteVectorShuffleMask(PermMask, 4);
8771       std::swap(V1, V2);
8772     }
8773
8774     // Find the element from V2.
8775     unsigned HiIndex;
8776     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8777       int Val = PermMask[HiIndex];
8778       if (Val < 0)
8779         continue;
8780       if (Val >= 4)
8781         break;
8782     }
8783
8784     Mask1[0] = PermMask[HiIndex];
8785     Mask1[1] = -1;
8786     Mask1[2] = PermMask[HiIndex^1];
8787     Mask1[3] = -1;
8788     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8789
8790     if (HiIndex >= 2) {
8791       Mask1[0] = PermMask[0];
8792       Mask1[1] = PermMask[1];
8793       Mask1[2] = HiIndex & 1 ? 6 : 4;
8794       Mask1[3] = HiIndex & 1 ? 4 : 6;
8795       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8796     }
8797
8798     Mask1[0] = HiIndex & 1 ? 2 : 0;
8799     Mask1[1] = HiIndex & 1 ? 0 : 2;
8800     Mask1[2] = PermMask[2];
8801     Mask1[3] = PermMask[3];
8802     if (Mask1[2] >= 0)
8803       Mask1[2] += 4;
8804     if (Mask1[3] >= 0)
8805       Mask1[3] += 4;
8806     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8807   }
8808
8809   // Break it into (shuffle shuffle_hi, shuffle_lo).
8810   int LoMask[] = { -1, -1, -1, -1 };
8811   int HiMask[] = { -1, -1, -1, -1 };
8812
8813   int *MaskPtr = LoMask;
8814   unsigned MaskIdx = 0;
8815   unsigned LoIdx = 0;
8816   unsigned HiIdx = 2;
8817   for (unsigned i = 0; i != 4; ++i) {
8818     if (i == 2) {
8819       MaskPtr = HiMask;
8820       MaskIdx = 1;
8821       LoIdx = 0;
8822       HiIdx = 2;
8823     }
8824     int Idx = PermMask[i];
8825     if (Idx < 0) {
8826       Locs[i] = std::make_pair(-1, -1);
8827     } else if (Idx < 4) {
8828       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8829       MaskPtr[LoIdx] = Idx;
8830       LoIdx++;
8831     } else {
8832       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8833       MaskPtr[HiIdx] = Idx;
8834       HiIdx++;
8835     }
8836   }
8837
8838   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8839   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8840   int MaskOps[] = { -1, -1, -1, -1 };
8841   for (unsigned i = 0; i != 4; ++i)
8842     if (Locs[i].first != -1)
8843       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8844   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8845 }
8846
8847 static bool MayFoldVectorLoad(SDValue V) {
8848   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8849     V = V.getOperand(0);
8850
8851   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8852     V = V.getOperand(0);
8853   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8854       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8855     // BUILD_VECTOR (load), undef
8856     V = V.getOperand(0);
8857
8858   return MayFoldLoad(V);
8859 }
8860
8861 static
8862 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8863   MVT VT = Op.getSimpleValueType();
8864
8865   // Canonizalize to v2f64.
8866   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8867   return DAG.getNode(ISD::BITCAST, dl, VT,
8868                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8869                                           V1, DAG));
8870 }
8871
8872 static
8873 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8874                         bool HasSSE2) {
8875   SDValue V1 = Op.getOperand(0);
8876   SDValue V2 = Op.getOperand(1);
8877   MVT VT = Op.getSimpleValueType();
8878
8879   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8880
8881   if (HasSSE2 && VT == MVT::v2f64)
8882     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8883
8884   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8885   return DAG.getNode(ISD::BITCAST, dl, VT,
8886                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8887                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8888                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8889 }
8890
8891 static
8892 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8893   SDValue V1 = Op.getOperand(0);
8894   SDValue V2 = Op.getOperand(1);
8895   MVT VT = Op.getSimpleValueType();
8896
8897   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8898          "unsupported shuffle type");
8899
8900   if (V2.getOpcode() == ISD::UNDEF)
8901     V2 = V1;
8902
8903   // v4i32 or v4f32
8904   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8905 }
8906
8907 static
8908 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8909   SDValue V1 = Op.getOperand(0);
8910   SDValue V2 = Op.getOperand(1);
8911   MVT VT = Op.getSimpleValueType();
8912   unsigned NumElems = VT.getVectorNumElements();
8913
8914   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8915   // operand of these instructions is only memory, so check if there's a
8916   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8917   // same masks.
8918   bool CanFoldLoad = false;
8919
8920   // Trivial case, when V2 comes from a load.
8921   if (MayFoldVectorLoad(V2))
8922     CanFoldLoad = true;
8923
8924   // When V1 is a load, it can be folded later into a store in isel, example:
8925   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8926   //    turns into:
8927   //  (MOVLPSmr addr:$src1, VR128:$src2)
8928   // So, recognize this potential and also use MOVLPS or MOVLPD
8929   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8930     CanFoldLoad = true;
8931
8932   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8933   if (CanFoldLoad) {
8934     if (HasSSE2 && NumElems == 2)
8935       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8936
8937     if (NumElems == 4)
8938       // If we don't care about the second element, proceed to use movss.
8939       if (SVOp->getMaskElt(1) != -1)
8940         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8941   }
8942
8943   // movl and movlp will both match v2i64, but v2i64 is never matched by
8944   // movl earlier because we make it strict to avoid messing with the movlp load
8945   // folding logic (see the code above getMOVLP call). Match it here then,
8946   // this is horrible, but will stay like this until we move all shuffle
8947   // matching to x86 specific nodes. Note that for the 1st condition all
8948   // types are matched with movsd.
8949   if (HasSSE2) {
8950     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
8951     // as to remove this logic from here, as much as possible
8952     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
8953       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8954     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8955   }
8956
8957   assert(VT != MVT::v4i32 && "unsupported shuffle type");
8958
8959   // Invert the operand order and use SHUFPS to match it.
8960   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
8961                               getShuffleSHUFImmediate(SVOp), DAG);
8962 }
8963
8964 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
8965                                          SelectionDAG &DAG) {
8966   SDLoc dl(Load);
8967   MVT VT = Load->getSimpleValueType(0);
8968   MVT EVT = VT.getVectorElementType();
8969   SDValue Addr = Load->getOperand(1);
8970   SDValue NewAddr = DAG.getNode(
8971       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
8972       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
8973
8974   SDValue NewLoad =
8975       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
8976                   DAG.getMachineFunction().getMachineMemOperand(
8977                       Load->getMemOperand(), 0, EVT.getStoreSize()));
8978   return NewLoad;
8979 }
8980
8981 // It is only safe to call this function if isINSERTPSMask is true for
8982 // this shufflevector mask.
8983 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
8984                            SelectionDAG &DAG) {
8985   // Generate an insertps instruction when inserting an f32 from memory onto a
8986   // v4f32 or when copying a member from one v4f32 to another.
8987   // We also use it for transferring i32 from one register to another,
8988   // since it simply copies the same bits.
8989   // If we're transferring an i32 from memory to a specific element in a
8990   // register, we output a generic DAG that will match the PINSRD
8991   // instruction.
8992   MVT VT = SVOp->getSimpleValueType(0);
8993   MVT EVT = VT.getVectorElementType();
8994   SDValue V1 = SVOp->getOperand(0);
8995   SDValue V2 = SVOp->getOperand(1);
8996   auto Mask = SVOp->getMask();
8997   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
8998          "unsupported vector type for insertps/pinsrd");
8999
9000   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9001   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9002   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9003
9004   SDValue From;
9005   SDValue To;
9006   unsigned DestIndex;
9007   if (FromV1 == 1) {
9008     From = V1;
9009     To = V2;
9010     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9011                 Mask.begin();
9012   } else {
9013     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9014            "More than one element from V1 and from V2, or no elements from one "
9015            "of the vectors. This case should not have returned true from "
9016            "isINSERTPSMask");
9017     From = V2;
9018     To = V1;
9019     DestIndex =
9020         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9021   }
9022
9023   unsigned SrcIndex = Mask[DestIndex] % 4;
9024   if (MayFoldLoad(From)) {
9025     // Trivial case, when From comes from a load and is only used by the
9026     // shuffle. Make it use insertps from the vector that we need from that
9027     // load.
9028     SDValue NewLoad =
9029         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9030     if (!NewLoad.getNode())
9031       return SDValue();
9032
9033     if (EVT == MVT::f32) {
9034       // Create this as a scalar to vector to match the instruction pattern.
9035       SDValue LoadScalarToVector =
9036           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9037       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9038       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9039                          InsertpsMask);
9040     } else { // EVT == MVT::i32
9041       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9042       // instruction, to match the PINSRD instruction, which loads an i32 to a
9043       // certain vector element.
9044       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9045                          DAG.getConstant(DestIndex, MVT::i32));
9046     }
9047   }
9048
9049   // Vector-element-to-vector
9050   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9051   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9052 }
9053
9054 // Reduce a vector shuffle to zext.
9055 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9056                                     SelectionDAG &DAG) {
9057   // PMOVZX is only available from SSE41.
9058   if (!Subtarget->hasSSE41())
9059     return SDValue();
9060
9061   MVT VT = Op.getSimpleValueType();
9062
9063   // Only AVX2 support 256-bit vector integer extending.
9064   if (!Subtarget->hasInt256() && VT.is256BitVector())
9065     return SDValue();
9066
9067   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9068   SDLoc DL(Op);
9069   SDValue V1 = Op.getOperand(0);
9070   SDValue V2 = Op.getOperand(1);
9071   unsigned NumElems = VT.getVectorNumElements();
9072
9073   // Extending is an unary operation and the element type of the source vector
9074   // won't be equal to or larger than i64.
9075   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9076       VT.getVectorElementType() == MVT::i64)
9077     return SDValue();
9078
9079   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9080   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9081   while ((1U << Shift) < NumElems) {
9082     if (SVOp->getMaskElt(1U << Shift) == 1)
9083       break;
9084     Shift += 1;
9085     // The maximal ratio is 8, i.e. from i8 to i64.
9086     if (Shift > 3)
9087       return SDValue();
9088   }
9089
9090   // Check the shuffle mask.
9091   unsigned Mask = (1U << Shift) - 1;
9092   for (unsigned i = 0; i != NumElems; ++i) {
9093     int EltIdx = SVOp->getMaskElt(i);
9094     if ((i & Mask) != 0 && EltIdx != -1)
9095       return SDValue();
9096     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9097       return SDValue();
9098   }
9099
9100   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9101   MVT NeVT = MVT::getIntegerVT(NBits);
9102   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9103
9104   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9105     return SDValue();
9106
9107   // Simplify the operand as it's prepared to be fed into shuffle.
9108   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9109   if (V1.getOpcode() == ISD::BITCAST &&
9110       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9111       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9112       V1.getOperand(0).getOperand(0)
9113         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9114     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9115     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9116     ConstantSDNode *CIdx =
9117       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9118     // If it's foldable, i.e. normal load with single use, we will let code
9119     // selection to fold it. Otherwise, we will short the conversion sequence.
9120     if (CIdx && CIdx->getZExtValue() == 0 &&
9121         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9122       MVT FullVT = V.getSimpleValueType();
9123       MVT V1VT = V1.getSimpleValueType();
9124       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9125         // The "ext_vec_elt" node is wider than the result node.
9126         // In this case we should extract subvector from V.
9127         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9128         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9129         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9130                                         FullVT.getVectorNumElements()/Ratio);
9131         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9132                         DAG.getIntPtrConstant(0));
9133       }
9134       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9135     }
9136   }
9137
9138   return DAG.getNode(ISD::BITCAST, DL, VT,
9139                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9140 }
9141
9142 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9143                                       SelectionDAG &DAG) {
9144   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9145   MVT VT = Op.getSimpleValueType();
9146   SDLoc dl(Op);
9147   SDValue V1 = Op.getOperand(0);
9148   SDValue V2 = Op.getOperand(1);
9149
9150   if (isZeroShuffle(SVOp))
9151     return getZeroVector(VT, Subtarget, DAG, dl);
9152
9153   // Handle splat operations
9154   if (SVOp->isSplat()) {
9155     // Use vbroadcast whenever the splat comes from a foldable load
9156     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9157     if (Broadcast.getNode())
9158       return Broadcast;
9159   }
9160
9161   // Check integer expanding shuffles.
9162   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9163   if (NewOp.getNode())
9164     return NewOp;
9165
9166   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9167   // do it!
9168   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9169       VT == MVT::v32i8) {
9170     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9171     if (NewOp.getNode())
9172       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9173   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9174     // FIXME: Figure out a cleaner way to do this.
9175     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9176       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9177       if (NewOp.getNode()) {
9178         MVT NewVT = NewOp.getSimpleValueType();
9179         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9180                                NewVT, true, false))
9181           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9182                               dl);
9183       }
9184     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9185       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9186       if (NewOp.getNode()) {
9187         MVT NewVT = NewOp.getSimpleValueType();
9188         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9189           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9190                               dl);
9191       }
9192     }
9193   }
9194   return SDValue();
9195 }
9196
9197 SDValue
9198 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9199   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9200   SDValue V1 = Op.getOperand(0);
9201   SDValue V2 = Op.getOperand(1);
9202   MVT VT = Op.getSimpleValueType();
9203   SDLoc dl(Op);
9204   unsigned NumElems = VT.getVectorNumElements();
9205   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9206   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9207   bool V1IsSplat = false;
9208   bool V2IsSplat = false;
9209   bool HasSSE2 = Subtarget->hasSSE2();
9210   bool HasFp256    = Subtarget->hasFp256();
9211   bool HasInt256   = Subtarget->hasInt256();
9212   MachineFunction &MF = DAG.getMachineFunction();
9213   bool OptForSize = MF.getFunction()->getAttributes().
9214     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9215
9216   // Check if we should use the experimental vector shuffle lowering. If so,
9217   // delegate completely to that code path.
9218   if (ExperimentalVectorShuffleLowering)
9219     return lowerVectorShuffle(Op, Subtarget, DAG);
9220
9221   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9222
9223   if (V1IsUndef && V2IsUndef)
9224     return DAG.getUNDEF(VT);
9225
9226   // When we create a shuffle node we put the UNDEF node to second operand,
9227   // but in some cases the first operand may be transformed to UNDEF.
9228   // In this case we should just commute the node.
9229   if (V1IsUndef)
9230     return CommuteVectorShuffle(SVOp, DAG);
9231
9232   // Vector shuffle lowering takes 3 steps:
9233   //
9234   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9235   //    narrowing and commutation of operands should be handled.
9236   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9237   //    shuffle nodes.
9238   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9239   //    so the shuffle can be broken into other shuffles and the legalizer can
9240   //    try the lowering again.
9241   //
9242   // The general idea is that no vector_shuffle operation should be left to
9243   // be matched during isel, all of them must be converted to a target specific
9244   // node here.
9245
9246   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9247   // narrowing and commutation of operands should be handled. The actual code
9248   // doesn't include all of those, work in progress...
9249   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9250   if (NewOp.getNode())
9251     return NewOp;
9252
9253   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9254
9255   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9256   // unpckh_undef). Only use pshufd if speed is more important than size.
9257   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9258     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9259   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9260     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9261
9262   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9263       V2IsUndef && MayFoldVectorLoad(V1))
9264     return getMOVDDup(Op, dl, V1, DAG);
9265
9266   if (isMOVHLPS_v_undef_Mask(M, VT))
9267     return getMOVHighToLow(Op, dl, DAG);
9268
9269   // Use to match splats
9270   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9271       (VT == MVT::v2f64 || VT == MVT::v2i64))
9272     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9273
9274   if (isPSHUFDMask(M, VT)) {
9275     // The actual implementation will match the mask in the if above and then
9276     // during isel it can match several different instructions, not only pshufd
9277     // as its name says, sad but true, emulate the behavior for now...
9278     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9279       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9280
9281     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9282
9283     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9284       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9285
9286     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9287       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9288                                   DAG);
9289
9290     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9291                                 TargetMask, DAG);
9292   }
9293
9294   if (isPALIGNRMask(M, VT, Subtarget))
9295     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9296                                 getShufflePALIGNRImmediate(SVOp),
9297                                 DAG);
9298
9299   // Check if this can be converted into a logical shift.
9300   bool isLeft = false;
9301   unsigned ShAmt = 0;
9302   SDValue ShVal;
9303   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9304   if (isShift && ShVal.hasOneUse()) {
9305     // If the shifted value has multiple uses, it may be cheaper to use
9306     // v_set0 + movlhps or movhlps, etc.
9307     MVT EltVT = VT.getVectorElementType();
9308     ShAmt *= EltVT.getSizeInBits();
9309     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9310   }
9311
9312   if (isMOVLMask(M, VT)) {
9313     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9314       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9315     if (!isMOVLPMask(M, VT)) {
9316       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9317         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9318
9319       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9320         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9321     }
9322   }
9323
9324   // FIXME: fold these into legal mask.
9325   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9326     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9327
9328   if (isMOVHLPSMask(M, VT))
9329     return getMOVHighToLow(Op, dl, DAG);
9330
9331   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9332     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9333
9334   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9335     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9336
9337   if (isMOVLPMask(M, VT))
9338     return getMOVLP(Op, dl, DAG, HasSSE2);
9339
9340   if (ShouldXformToMOVHLPS(M, VT) ||
9341       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9342     return CommuteVectorShuffle(SVOp, DAG);
9343
9344   if (isShift) {
9345     // No better options. Use a vshldq / vsrldq.
9346     MVT EltVT = VT.getVectorElementType();
9347     ShAmt *= EltVT.getSizeInBits();
9348     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9349   }
9350
9351   bool Commuted = false;
9352   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9353   // 1,1,1,1 -> v8i16 though.
9354   V1IsSplat = isSplatVector(V1.getNode());
9355   V2IsSplat = isSplatVector(V2.getNode());
9356
9357   // Canonicalize the splat or undef, if present, to be on the RHS.
9358   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9359     CommuteVectorShuffleMask(M, NumElems);
9360     std::swap(V1, V2);
9361     std::swap(V1IsSplat, V2IsSplat);
9362     Commuted = true;
9363   }
9364
9365   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9366     // Shuffling low element of v1 into undef, just return v1.
9367     if (V2IsUndef)
9368       return V1;
9369     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9370     // the instruction selector will not match, so get a canonical MOVL with
9371     // swapped operands to undo the commute.
9372     return getMOVL(DAG, dl, VT, V2, V1);
9373   }
9374
9375   if (isUNPCKLMask(M, VT, HasInt256))
9376     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9377
9378   if (isUNPCKHMask(M, VT, HasInt256))
9379     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9380
9381   if (V2IsSplat) {
9382     // Normalize mask so all entries that point to V2 points to its first
9383     // element then try to match unpck{h|l} again. If match, return a
9384     // new vector_shuffle with the corrected mask.p
9385     SmallVector<int, 8> NewMask(M.begin(), M.end());
9386     NormalizeMask(NewMask, NumElems);
9387     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9388       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9389     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9390       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9391   }
9392
9393   if (Commuted) {
9394     // Commute is back and try unpck* again.
9395     // FIXME: this seems wrong.
9396     CommuteVectorShuffleMask(M, NumElems);
9397     std::swap(V1, V2);
9398     std::swap(V1IsSplat, V2IsSplat);
9399
9400     if (isUNPCKLMask(M, VT, HasInt256))
9401       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9402
9403     if (isUNPCKHMask(M, VT, HasInt256))
9404       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9405   }
9406
9407   // Normalize the node to match x86 shuffle ops if needed
9408   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9409     return CommuteVectorShuffle(SVOp, DAG);
9410
9411   // The checks below are all present in isShuffleMaskLegal, but they are
9412   // inlined here right now to enable us to directly emit target specific
9413   // nodes, and remove one by one until they don't return Op anymore.
9414
9415   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9416       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9417     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9418       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9419   }
9420
9421   if (isPSHUFHWMask(M, VT, HasInt256))
9422     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9423                                 getShufflePSHUFHWImmediate(SVOp),
9424                                 DAG);
9425
9426   if (isPSHUFLWMask(M, VT, HasInt256))
9427     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9428                                 getShufflePSHUFLWImmediate(SVOp),
9429                                 DAG);
9430
9431   unsigned MaskValue;
9432   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9433                   &MaskValue))
9434     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9435
9436   if (isSHUFPMask(M, VT))
9437     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9438                                 getShuffleSHUFImmediate(SVOp), DAG);
9439
9440   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9441     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9442   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9443     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9444
9445   //===--------------------------------------------------------------------===//
9446   // Generate target specific nodes for 128 or 256-bit shuffles only
9447   // supported in the AVX instruction set.
9448   //
9449
9450   // Handle VMOVDDUPY permutations
9451   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9452     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9453
9454   // Handle VPERMILPS/D* permutations
9455   if (isVPERMILPMask(M, VT)) {
9456     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9457       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9458                                   getShuffleSHUFImmediate(SVOp), DAG);
9459     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9460                                 getShuffleSHUFImmediate(SVOp), DAG);
9461   }
9462
9463   unsigned Idx;
9464   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9465     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9466                               Idx*(NumElems/2), DAG, dl);
9467
9468   // Handle VPERM2F128/VPERM2I128 permutations
9469   if (isVPERM2X128Mask(M, VT, HasFp256))
9470     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9471                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9472
9473   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9474     return getINSERTPS(SVOp, dl, DAG);
9475
9476   unsigned Imm8;
9477   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9478     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9479
9480   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9481       VT.is512BitVector()) {
9482     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9483     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9484     SmallVector<SDValue, 16> permclMask;
9485     for (unsigned i = 0; i != NumElems; ++i) {
9486       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9487     }
9488
9489     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9490     if (V2IsUndef)
9491       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9492       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9493                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9494     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9495                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9496   }
9497
9498   //===--------------------------------------------------------------------===//
9499   // Since no target specific shuffle was selected for this generic one,
9500   // lower it into other known shuffles. FIXME: this isn't true yet, but
9501   // this is the plan.
9502   //
9503
9504   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9505   if (VT == MVT::v8i16) {
9506     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9507     if (NewOp.getNode())
9508       return NewOp;
9509   }
9510
9511   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9512     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9513     if (NewOp.getNode())
9514       return NewOp;
9515   }
9516
9517   if (VT == MVT::v16i8) {
9518     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9519     if (NewOp.getNode())
9520       return NewOp;
9521   }
9522
9523   if (VT == MVT::v32i8) {
9524     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9525     if (NewOp.getNode())
9526       return NewOp;
9527   }
9528
9529   // Handle all 128-bit wide vectors with 4 elements, and match them with
9530   // several different shuffle types.
9531   if (NumElems == 4 && VT.is128BitVector())
9532     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9533
9534   // Handle general 256-bit shuffles
9535   if (VT.is256BitVector())
9536     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9537
9538   return SDValue();
9539 }
9540
9541 // This function assumes its argument is a BUILD_VECTOR of constants or
9542 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9543 // true.
9544 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9545                                     unsigned &MaskValue) {
9546   MaskValue = 0;
9547   unsigned NumElems = BuildVector->getNumOperands();
9548   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9549   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9550   unsigned NumElemsInLane = NumElems / NumLanes;
9551
9552   // Blend for v16i16 should be symetric for the both lanes.
9553   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9554     SDValue EltCond = BuildVector->getOperand(i);
9555     SDValue SndLaneEltCond =
9556         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9557
9558     int Lane1Cond = -1, Lane2Cond = -1;
9559     if (isa<ConstantSDNode>(EltCond))
9560       Lane1Cond = !isZero(EltCond);
9561     if (isa<ConstantSDNode>(SndLaneEltCond))
9562       Lane2Cond = !isZero(SndLaneEltCond);
9563
9564     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9565       // Lane1Cond != 0, means we want the first argument.
9566       // Lane1Cond == 0, means we want the second argument.
9567       // The encoding of this argument is 0 for the first argument, 1
9568       // for the second. Therefore, invert the condition.
9569       MaskValue |= !Lane1Cond << i;
9570     else if (Lane1Cond < 0)
9571       MaskValue |= !Lane2Cond << i;
9572     else
9573       return false;
9574   }
9575   return true;
9576 }
9577
9578 // Try to lower a vselect node into a simple blend instruction.
9579 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9580                                    SelectionDAG &DAG) {
9581   SDValue Cond = Op.getOperand(0);
9582   SDValue LHS = Op.getOperand(1);
9583   SDValue RHS = Op.getOperand(2);
9584   SDLoc dl(Op);
9585   MVT VT = Op.getSimpleValueType();
9586   MVT EltVT = VT.getVectorElementType();
9587   unsigned NumElems = VT.getVectorNumElements();
9588
9589   // There is no blend with immediate in AVX-512.
9590   if (VT.is512BitVector())
9591     return SDValue();
9592
9593   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9594     return SDValue();
9595   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9596     return SDValue();
9597
9598   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9599     return SDValue();
9600
9601   // Check the mask for BLEND and build the value.
9602   unsigned MaskValue = 0;
9603   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9604     return SDValue();
9605
9606   // Convert i32 vectors to floating point if it is not AVX2.
9607   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9608   MVT BlendVT = VT;
9609   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9610     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9611                                NumElems);
9612     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9613     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9614   }
9615
9616   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9617                             DAG.getConstant(MaskValue, MVT::i32));
9618   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9619 }
9620
9621 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9622   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9623   if (BlendOp.getNode())
9624     return BlendOp;
9625
9626   // Some types for vselect were previously set to Expand, not Legal or
9627   // Custom. Return an empty SDValue so we fall-through to Expand, after
9628   // the Custom lowering phase.
9629   MVT VT = Op.getSimpleValueType();
9630   switch (VT.SimpleTy) {
9631   default:
9632     break;
9633   case MVT::v8i16:
9634   case MVT::v16i16:
9635     return SDValue();
9636   }
9637
9638   // We couldn't create a "Blend with immediate" node.
9639   // This node should still be legal, but we'll have to emit a blendv*
9640   // instruction.
9641   return Op;
9642 }
9643
9644 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9645   MVT VT = Op.getSimpleValueType();
9646   SDLoc dl(Op);
9647
9648   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9649     return SDValue();
9650
9651   if (VT.getSizeInBits() == 8) {
9652     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9653                                   Op.getOperand(0), Op.getOperand(1));
9654     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9655                                   DAG.getValueType(VT));
9656     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9657   }
9658
9659   if (VT.getSizeInBits() == 16) {
9660     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9661     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9662     if (Idx == 0)
9663       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9664                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9665                                      DAG.getNode(ISD::BITCAST, dl,
9666                                                  MVT::v4i32,
9667                                                  Op.getOperand(0)),
9668                                      Op.getOperand(1)));
9669     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9670                                   Op.getOperand(0), Op.getOperand(1));
9671     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9672                                   DAG.getValueType(VT));
9673     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9674   }
9675
9676   if (VT == MVT::f32) {
9677     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9678     // the result back to FR32 register. It's only worth matching if the
9679     // result has a single use which is a store or a bitcast to i32.  And in
9680     // the case of a store, it's not worth it if the index is a constant 0,
9681     // because a MOVSSmr can be used instead, which is smaller and faster.
9682     if (!Op.hasOneUse())
9683       return SDValue();
9684     SDNode *User = *Op.getNode()->use_begin();
9685     if ((User->getOpcode() != ISD::STORE ||
9686          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9687           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9688         (User->getOpcode() != ISD::BITCAST ||
9689          User->getValueType(0) != MVT::i32))
9690       return SDValue();
9691     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9692                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9693                                               Op.getOperand(0)),
9694                                               Op.getOperand(1));
9695     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9696   }
9697
9698   if (VT == MVT::i32 || VT == MVT::i64) {
9699     // ExtractPS/pextrq works with constant index.
9700     if (isa<ConstantSDNode>(Op.getOperand(1)))
9701       return Op;
9702   }
9703   return SDValue();
9704 }
9705
9706 /// Extract one bit from mask vector, like v16i1 or v8i1.
9707 /// AVX-512 feature.
9708 SDValue
9709 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9710   SDValue Vec = Op.getOperand(0);
9711   SDLoc dl(Vec);
9712   MVT VecVT = Vec.getSimpleValueType();
9713   SDValue Idx = Op.getOperand(1);
9714   MVT EltVT = Op.getSimpleValueType();
9715
9716   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9717
9718   // variable index can't be handled in mask registers,
9719   // extend vector to VR512
9720   if (!isa<ConstantSDNode>(Idx)) {
9721     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9722     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9723     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9724                               ExtVT.getVectorElementType(), Ext, Idx);
9725     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9726   }
9727
9728   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9729   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9730   unsigned MaxSift = rc->getSize()*8 - 1;
9731   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9732                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9733   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9734                     DAG.getConstant(MaxSift, MVT::i8));
9735   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9736                        DAG.getIntPtrConstant(0));
9737 }
9738
9739 SDValue
9740 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9741                                            SelectionDAG &DAG) const {
9742   SDLoc dl(Op);
9743   SDValue Vec = Op.getOperand(0);
9744   MVT VecVT = Vec.getSimpleValueType();
9745   SDValue Idx = Op.getOperand(1);
9746
9747   if (Op.getSimpleValueType() == MVT::i1)
9748     return ExtractBitFromMaskVector(Op, DAG);
9749
9750   if (!isa<ConstantSDNode>(Idx)) {
9751     if (VecVT.is512BitVector() ||
9752         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9753          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9754
9755       MVT MaskEltVT =
9756         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9757       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9758                                     MaskEltVT.getSizeInBits());
9759
9760       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9761       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9762                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9763                                 Idx, DAG.getConstant(0, getPointerTy()));
9764       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9765       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9766                         Perm, DAG.getConstant(0, getPointerTy()));
9767     }
9768     return SDValue();
9769   }
9770
9771   // If this is a 256-bit vector result, first extract the 128-bit vector and
9772   // then extract the element from the 128-bit vector.
9773   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9774
9775     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9776     // Get the 128-bit vector.
9777     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9778     MVT EltVT = VecVT.getVectorElementType();
9779
9780     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9781
9782     //if (IdxVal >= NumElems/2)
9783     //  IdxVal -= NumElems/2;
9784     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9785     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9786                        DAG.getConstant(IdxVal, MVT::i32));
9787   }
9788
9789   assert(VecVT.is128BitVector() && "Unexpected vector length");
9790
9791   if (Subtarget->hasSSE41()) {
9792     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9793     if (Res.getNode())
9794       return Res;
9795   }
9796
9797   MVT VT = Op.getSimpleValueType();
9798   // TODO: handle v16i8.
9799   if (VT.getSizeInBits() == 16) {
9800     SDValue Vec = Op.getOperand(0);
9801     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9802     if (Idx == 0)
9803       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9804                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9805                                      DAG.getNode(ISD::BITCAST, dl,
9806                                                  MVT::v4i32, Vec),
9807                                      Op.getOperand(1)));
9808     // Transform it so it match pextrw which produces a 32-bit result.
9809     MVT EltVT = MVT::i32;
9810     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9811                                   Op.getOperand(0), Op.getOperand(1));
9812     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9813                                   DAG.getValueType(VT));
9814     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9815   }
9816
9817   if (VT.getSizeInBits() == 32) {
9818     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9819     if (Idx == 0)
9820       return Op;
9821
9822     // SHUFPS the element to the lowest double word, then movss.
9823     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9824     MVT VVT = Op.getOperand(0).getSimpleValueType();
9825     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9826                                        DAG.getUNDEF(VVT), Mask);
9827     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9828                        DAG.getIntPtrConstant(0));
9829   }
9830
9831   if (VT.getSizeInBits() == 64) {
9832     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9833     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9834     //        to match extract_elt for f64.
9835     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9836     if (Idx == 0)
9837       return Op;
9838
9839     // UNPCKHPD the element to the lowest double word, then movsd.
9840     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9841     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9842     int Mask[2] = { 1, -1 };
9843     MVT VVT = Op.getOperand(0).getSimpleValueType();
9844     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9845                                        DAG.getUNDEF(VVT), Mask);
9846     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9847                        DAG.getIntPtrConstant(0));
9848   }
9849
9850   return SDValue();
9851 }
9852
9853 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9854   MVT VT = Op.getSimpleValueType();
9855   MVT EltVT = VT.getVectorElementType();
9856   SDLoc dl(Op);
9857
9858   SDValue N0 = Op.getOperand(0);
9859   SDValue N1 = Op.getOperand(1);
9860   SDValue N2 = Op.getOperand(2);
9861
9862   if (!VT.is128BitVector())
9863     return SDValue();
9864
9865   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9866       isa<ConstantSDNode>(N2)) {
9867     unsigned Opc;
9868     if (VT == MVT::v8i16)
9869       Opc = X86ISD::PINSRW;
9870     else if (VT == MVT::v16i8)
9871       Opc = X86ISD::PINSRB;
9872     else
9873       Opc = X86ISD::PINSRB;
9874
9875     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9876     // argument.
9877     if (N1.getValueType() != MVT::i32)
9878       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9879     if (N2.getValueType() != MVT::i32)
9880       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9881     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9882   }
9883
9884   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9885     // Bits [7:6] of the constant are the source select.  This will always be
9886     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9887     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9888     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9889     // Bits [5:4] of the constant are the destination select.  This is the
9890     //  value of the incoming immediate.
9891     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9892     //   combine either bitwise AND or insert of float 0.0 to set these bits.
9893     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9894     // Create this as a scalar to vector..
9895     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9896     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9897   }
9898
9899   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9900     // PINSR* works with constant index.
9901     return Op;
9902   }
9903   return SDValue();
9904 }
9905
9906 /// Insert one bit to mask vector, like v16i1 or v8i1.
9907 /// AVX-512 feature.
9908 SDValue 
9909 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9910   SDLoc dl(Op);
9911   SDValue Vec = Op.getOperand(0);
9912   SDValue Elt = Op.getOperand(1);
9913   SDValue Idx = Op.getOperand(2);
9914   MVT VecVT = Vec.getSimpleValueType();
9915
9916   if (!isa<ConstantSDNode>(Idx)) {
9917     // Non constant index. Extend source and destination,
9918     // insert element and then truncate the result.
9919     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9920     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
9921     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
9922       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9923       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9924     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9925   }
9926
9927   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9928   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9929   if (Vec.getOpcode() == ISD::UNDEF)
9930     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9931                        DAG.getConstant(IdxVal, MVT::i8));
9932   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9933   unsigned MaxSift = rc->getSize()*8 - 1;
9934   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9935                     DAG.getConstant(MaxSift, MVT::i8));
9936   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9937                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9938   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
9939 }
9940 SDValue
9941 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
9942   MVT VT = Op.getSimpleValueType();
9943   MVT EltVT = VT.getVectorElementType();
9944   
9945   if (EltVT == MVT::i1)
9946     return InsertBitToMaskVector(Op, DAG);
9947
9948   SDLoc dl(Op);
9949   SDValue N0 = Op.getOperand(0);
9950   SDValue N1 = Op.getOperand(1);
9951   SDValue N2 = Op.getOperand(2);
9952
9953   // If this is a 256-bit vector result, first extract the 128-bit vector,
9954   // insert the element into the extracted half and then place it back.
9955   if (VT.is256BitVector() || VT.is512BitVector()) {
9956     if (!isa<ConstantSDNode>(N2))
9957       return SDValue();
9958
9959     // Get the desired 128-bit vector half.
9960     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
9961     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
9962
9963     // Insert the element into the desired half.
9964     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
9965     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
9966
9967     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
9968                     DAG.getConstant(IdxIn128, MVT::i32));
9969
9970     // Insert the changed part back to the 256-bit vector
9971     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
9972   }
9973
9974   if (Subtarget->hasSSE41())
9975     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
9976
9977   if (EltVT == MVT::i8)
9978     return SDValue();
9979
9980   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
9981     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
9982     // as its second argument.
9983     if (N1.getValueType() != MVT::i32)
9984       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9985     if (N2.getValueType() != MVT::i32)
9986       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9987     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
9988   }
9989   return SDValue();
9990 }
9991
9992 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
9993   SDLoc dl(Op);
9994   MVT OpVT = Op.getSimpleValueType();
9995
9996   // If this is a 256-bit vector result, first insert into a 128-bit
9997   // vector and then insert into the 256-bit vector.
9998   if (!OpVT.is128BitVector()) {
9999     // Insert into a 128-bit vector.
10000     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10001     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10002                                  OpVT.getVectorNumElements() / SizeFactor);
10003
10004     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10005
10006     // Insert the 128-bit vector.
10007     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10008   }
10009
10010   if (OpVT == MVT::v1i64 &&
10011       Op.getOperand(0).getValueType() == MVT::i64)
10012     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10013
10014   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10015   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10016   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10017                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10018 }
10019
10020 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10021 // a simple subregister reference or explicit instructions to grab
10022 // upper bits of a vector.
10023 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10024                                       SelectionDAG &DAG) {
10025   SDLoc dl(Op);
10026   SDValue In =  Op.getOperand(0);
10027   SDValue Idx = Op.getOperand(1);
10028   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10029   MVT ResVT   = Op.getSimpleValueType();
10030   MVT InVT    = In.getSimpleValueType();
10031
10032   if (Subtarget->hasFp256()) {
10033     if (ResVT.is128BitVector() &&
10034         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10035         isa<ConstantSDNode>(Idx)) {
10036       return Extract128BitVector(In, IdxVal, DAG, dl);
10037     }
10038     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10039         isa<ConstantSDNode>(Idx)) {
10040       return Extract256BitVector(In, IdxVal, DAG, dl);
10041     }
10042   }
10043   return SDValue();
10044 }
10045
10046 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10047 // simple superregister reference or explicit instructions to insert
10048 // the upper bits of a vector.
10049 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10050                                      SelectionDAG &DAG) {
10051   if (Subtarget->hasFp256()) {
10052     SDLoc dl(Op.getNode());
10053     SDValue Vec = Op.getNode()->getOperand(0);
10054     SDValue SubVec = Op.getNode()->getOperand(1);
10055     SDValue Idx = Op.getNode()->getOperand(2);
10056
10057     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10058          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10059         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10060         isa<ConstantSDNode>(Idx)) {
10061       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10062       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10063     }
10064
10065     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10066         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10067         isa<ConstantSDNode>(Idx)) {
10068       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10069       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10070     }
10071   }
10072   return SDValue();
10073 }
10074
10075 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10076 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10077 // one of the above mentioned nodes. It has to be wrapped because otherwise
10078 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10079 // be used to form addressing mode. These wrapped nodes will be selected
10080 // into MOV32ri.
10081 SDValue
10082 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10083   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10084
10085   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10086   // global base reg.
10087   unsigned char OpFlag = 0;
10088   unsigned WrapperKind = X86ISD::Wrapper;
10089   CodeModel::Model M = DAG.getTarget().getCodeModel();
10090
10091   if (Subtarget->isPICStyleRIPRel() &&
10092       (M == CodeModel::Small || M == CodeModel::Kernel))
10093     WrapperKind = X86ISD::WrapperRIP;
10094   else if (Subtarget->isPICStyleGOT())
10095     OpFlag = X86II::MO_GOTOFF;
10096   else if (Subtarget->isPICStyleStubPIC())
10097     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10098
10099   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10100                                              CP->getAlignment(),
10101                                              CP->getOffset(), OpFlag);
10102   SDLoc DL(CP);
10103   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10104   // With PIC, the address is actually $g + Offset.
10105   if (OpFlag) {
10106     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10107                          DAG.getNode(X86ISD::GlobalBaseReg,
10108                                      SDLoc(), getPointerTy()),
10109                          Result);
10110   }
10111
10112   return Result;
10113 }
10114
10115 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10116   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10117
10118   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10119   // global base reg.
10120   unsigned char OpFlag = 0;
10121   unsigned WrapperKind = X86ISD::Wrapper;
10122   CodeModel::Model M = DAG.getTarget().getCodeModel();
10123
10124   if (Subtarget->isPICStyleRIPRel() &&
10125       (M == CodeModel::Small || M == CodeModel::Kernel))
10126     WrapperKind = X86ISD::WrapperRIP;
10127   else if (Subtarget->isPICStyleGOT())
10128     OpFlag = X86II::MO_GOTOFF;
10129   else if (Subtarget->isPICStyleStubPIC())
10130     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10131
10132   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10133                                           OpFlag);
10134   SDLoc DL(JT);
10135   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10136
10137   // With PIC, the address is actually $g + Offset.
10138   if (OpFlag)
10139     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10140                          DAG.getNode(X86ISD::GlobalBaseReg,
10141                                      SDLoc(), getPointerTy()),
10142                          Result);
10143
10144   return Result;
10145 }
10146
10147 SDValue
10148 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10149   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10150
10151   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10152   // global base reg.
10153   unsigned char OpFlag = 0;
10154   unsigned WrapperKind = X86ISD::Wrapper;
10155   CodeModel::Model M = DAG.getTarget().getCodeModel();
10156
10157   if (Subtarget->isPICStyleRIPRel() &&
10158       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10159     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10160       OpFlag = X86II::MO_GOTPCREL;
10161     WrapperKind = X86ISD::WrapperRIP;
10162   } else if (Subtarget->isPICStyleGOT()) {
10163     OpFlag = X86II::MO_GOT;
10164   } else if (Subtarget->isPICStyleStubPIC()) {
10165     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10166   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10167     OpFlag = X86II::MO_DARWIN_NONLAZY;
10168   }
10169
10170   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10171
10172   SDLoc DL(Op);
10173   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10174
10175   // With PIC, the address is actually $g + Offset.
10176   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10177       !Subtarget->is64Bit()) {
10178     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10179                          DAG.getNode(X86ISD::GlobalBaseReg,
10180                                      SDLoc(), getPointerTy()),
10181                          Result);
10182   }
10183
10184   // For symbols that require a load from a stub to get the address, emit the
10185   // load.
10186   if (isGlobalStubReference(OpFlag))
10187     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10188                          MachinePointerInfo::getGOT(), false, false, false, 0);
10189
10190   return Result;
10191 }
10192
10193 SDValue
10194 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10195   // Create the TargetBlockAddressAddress node.
10196   unsigned char OpFlags =
10197     Subtarget->ClassifyBlockAddressReference();
10198   CodeModel::Model M = DAG.getTarget().getCodeModel();
10199   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10200   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10201   SDLoc dl(Op);
10202   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10203                                              OpFlags);
10204
10205   if (Subtarget->isPICStyleRIPRel() &&
10206       (M == CodeModel::Small || M == CodeModel::Kernel))
10207     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10208   else
10209     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10210
10211   // With PIC, the address is actually $g + Offset.
10212   if (isGlobalRelativeToPICBase(OpFlags)) {
10213     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10214                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10215                          Result);
10216   }
10217
10218   return Result;
10219 }
10220
10221 SDValue
10222 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10223                                       int64_t Offset, SelectionDAG &DAG) const {
10224   // Create the TargetGlobalAddress node, folding in the constant
10225   // offset if it is legal.
10226   unsigned char OpFlags =
10227       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10228   CodeModel::Model M = DAG.getTarget().getCodeModel();
10229   SDValue Result;
10230   if (OpFlags == X86II::MO_NO_FLAG &&
10231       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10232     // A direct static reference to a global.
10233     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10234     Offset = 0;
10235   } else {
10236     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10237   }
10238
10239   if (Subtarget->isPICStyleRIPRel() &&
10240       (M == CodeModel::Small || M == CodeModel::Kernel))
10241     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10242   else
10243     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10244
10245   // With PIC, the address is actually $g + Offset.
10246   if (isGlobalRelativeToPICBase(OpFlags)) {
10247     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10248                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10249                          Result);
10250   }
10251
10252   // For globals that require a load from a stub to get the address, emit the
10253   // load.
10254   if (isGlobalStubReference(OpFlags))
10255     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10256                          MachinePointerInfo::getGOT(), false, false, false, 0);
10257
10258   // If there was a non-zero offset that we didn't fold, create an explicit
10259   // addition for it.
10260   if (Offset != 0)
10261     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10262                          DAG.getConstant(Offset, getPointerTy()));
10263
10264   return Result;
10265 }
10266
10267 SDValue
10268 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10269   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10270   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10271   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10272 }
10273
10274 static SDValue
10275 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10276            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10277            unsigned char OperandFlags, bool LocalDynamic = false) {
10278   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10279   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10280   SDLoc dl(GA);
10281   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10282                                            GA->getValueType(0),
10283                                            GA->getOffset(),
10284                                            OperandFlags);
10285
10286   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10287                                            : X86ISD::TLSADDR;
10288
10289   if (InFlag) {
10290     SDValue Ops[] = { Chain,  TGA, *InFlag };
10291     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10292   } else {
10293     SDValue Ops[]  = { Chain, TGA };
10294     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10295   }
10296
10297   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10298   MFI->setAdjustsStack(true);
10299
10300   SDValue Flag = Chain.getValue(1);
10301   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10302 }
10303
10304 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10305 static SDValue
10306 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10307                                 const EVT PtrVT) {
10308   SDValue InFlag;
10309   SDLoc dl(GA);  // ? function entry point might be better
10310   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10311                                    DAG.getNode(X86ISD::GlobalBaseReg,
10312                                                SDLoc(), PtrVT), InFlag);
10313   InFlag = Chain.getValue(1);
10314
10315   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10316 }
10317
10318 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10319 static SDValue
10320 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10321                                 const EVT PtrVT) {
10322   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10323                     X86::RAX, X86II::MO_TLSGD);
10324 }
10325
10326 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10327                                            SelectionDAG &DAG,
10328                                            const EVT PtrVT,
10329                                            bool is64Bit) {
10330   SDLoc dl(GA);
10331
10332   // Get the start address of the TLS block for this module.
10333   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10334       .getInfo<X86MachineFunctionInfo>();
10335   MFI->incNumLocalDynamicTLSAccesses();
10336
10337   SDValue Base;
10338   if (is64Bit) {
10339     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10340                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10341   } else {
10342     SDValue InFlag;
10343     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10344         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10345     InFlag = Chain.getValue(1);
10346     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10347                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10348   }
10349
10350   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10351   // of Base.
10352
10353   // Build x@dtpoff.
10354   unsigned char OperandFlags = X86II::MO_DTPOFF;
10355   unsigned WrapperKind = X86ISD::Wrapper;
10356   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10357                                            GA->getValueType(0),
10358                                            GA->getOffset(), OperandFlags);
10359   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10360
10361   // Add x@dtpoff with the base.
10362   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10363 }
10364
10365 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10366 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10367                                    const EVT PtrVT, TLSModel::Model model,
10368                                    bool is64Bit, bool isPIC) {
10369   SDLoc dl(GA);
10370
10371   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10372   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10373                                                          is64Bit ? 257 : 256));
10374
10375   SDValue ThreadPointer =
10376       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10377                   MachinePointerInfo(Ptr), false, false, false, 0);
10378
10379   unsigned char OperandFlags = 0;
10380   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10381   // initialexec.
10382   unsigned WrapperKind = X86ISD::Wrapper;
10383   if (model == TLSModel::LocalExec) {
10384     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10385   } else if (model == TLSModel::InitialExec) {
10386     if (is64Bit) {
10387       OperandFlags = X86II::MO_GOTTPOFF;
10388       WrapperKind = X86ISD::WrapperRIP;
10389     } else {
10390       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10391     }
10392   } else {
10393     llvm_unreachable("Unexpected model");
10394   }
10395
10396   // emit "addl x@ntpoff,%eax" (local exec)
10397   // or "addl x@indntpoff,%eax" (initial exec)
10398   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10399   SDValue TGA =
10400       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10401                                  GA->getOffset(), OperandFlags);
10402   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10403
10404   if (model == TLSModel::InitialExec) {
10405     if (isPIC && !is64Bit) {
10406       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10407                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10408                            Offset);
10409     }
10410
10411     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10412                          MachinePointerInfo::getGOT(), false, false, false, 0);
10413   }
10414
10415   // The address of the thread local variable is the add of the thread
10416   // pointer with the offset of the variable.
10417   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10418 }
10419
10420 SDValue
10421 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10422
10423   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10424   const GlobalValue *GV = GA->getGlobal();
10425
10426   if (Subtarget->isTargetELF()) {
10427     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10428
10429     switch (model) {
10430       case TLSModel::GeneralDynamic:
10431         if (Subtarget->is64Bit())
10432           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10433         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10434       case TLSModel::LocalDynamic:
10435         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10436                                            Subtarget->is64Bit());
10437       case TLSModel::InitialExec:
10438       case TLSModel::LocalExec:
10439         return LowerToTLSExecModel(
10440             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10441             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10442     }
10443     llvm_unreachable("Unknown TLS model.");
10444   }
10445
10446   if (Subtarget->isTargetDarwin()) {
10447     // Darwin only has one model of TLS.  Lower to that.
10448     unsigned char OpFlag = 0;
10449     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10450                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10451
10452     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10453     // global base reg.
10454     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10455                  !Subtarget->is64Bit();
10456     if (PIC32)
10457       OpFlag = X86II::MO_TLVP_PIC_BASE;
10458     else
10459       OpFlag = X86II::MO_TLVP;
10460     SDLoc DL(Op);
10461     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10462                                                 GA->getValueType(0),
10463                                                 GA->getOffset(), OpFlag);
10464     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10465
10466     // With PIC32, the address is actually $g + Offset.
10467     if (PIC32)
10468       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10469                            DAG.getNode(X86ISD::GlobalBaseReg,
10470                                        SDLoc(), getPointerTy()),
10471                            Offset);
10472
10473     // Lowering the machine isd will make sure everything is in the right
10474     // location.
10475     SDValue Chain = DAG.getEntryNode();
10476     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10477     SDValue Args[] = { Chain, Offset };
10478     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10479
10480     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10481     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10482     MFI->setAdjustsStack(true);
10483
10484     // And our return value (tls address) is in the standard call return value
10485     // location.
10486     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10487     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10488                               Chain.getValue(1));
10489   }
10490
10491   if (Subtarget->isTargetKnownWindowsMSVC() ||
10492       Subtarget->isTargetWindowsGNU()) {
10493     // Just use the implicit TLS architecture
10494     // Need to generate someting similar to:
10495     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10496     //                                  ; from TEB
10497     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10498     //   mov     rcx, qword [rdx+rcx*8]
10499     //   mov     eax, .tls$:tlsvar
10500     //   [rax+rcx] contains the address
10501     // Windows 64bit: gs:0x58
10502     // Windows 32bit: fs:__tls_array
10503
10504     SDLoc dl(GA);
10505     SDValue Chain = DAG.getEntryNode();
10506
10507     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10508     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10509     // use its literal value of 0x2C.
10510     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10511                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10512                                                              256)
10513                                         : Type::getInt32PtrTy(*DAG.getContext(),
10514                                                               257));
10515
10516     SDValue TlsArray =
10517         Subtarget->is64Bit()
10518             ? DAG.getIntPtrConstant(0x58)
10519             : (Subtarget->isTargetWindowsGNU()
10520                    ? DAG.getIntPtrConstant(0x2C)
10521                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10522
10523     SDValue ThreadPointer =
10524         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10525                     MachinePointerInfo(Ptr), false, false, false, 0);
10526
10527     // Load the _tls_index variable
10528     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10529     if (Subtarget->is64Bit())
10530       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10531                            IDX, MachinePointerInfo(), MVT::i32,
10532                            false, false, 0);
10533     else
10534       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10535                         false, false, false, 0);
10536
10537     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10538                                     getPointerTy());
10539     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10540
10541     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10542     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10543                       false, false, false, 0);
10544
10545     // Get the offset of start of .tls section
10546     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10547                                              GA->getValueType(0),
10548                                              GA->getOffset(), X86II::MO_SECREL);
10549     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10550
10551     // The address of the thread local variable is the add of the thread
10552     // pointer with the offset of the variable.
10553     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10554   }
10555
10556   llvm_unreachable("TLS not implemented for this target.");
10557 }
10558
10559 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10560 /// and take a 2 x i32 value to shift plus a shift amount.
10561 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10562   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10563   MVT VT = Op.getSimpleValueType();
10564   unsigned VTBits = VT.getSizeInBits();
10565   SDLoc dl(Op);
10566   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10567   SDValue ShOpLo = Op.getOperand(0);
10568   SDValue ShOpHi = Op.getOperand(1);
10569   SDValue ShAmt  = Op.getOperand(2);
10570   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10571   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10572   // during isel.
10573   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10574                                   DAG.getConstant(VTBits - 1, MVT::i8));
10575   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10576                                      DAG.getConstant(VTBits - 1, MVT::i8))
10577                        : DAG.getConstant(0, VT);
10578
10579   SDValue Tmp2, Tmp3;
10580   if (Op.getOpcode() == ISD::SHL_PARTS) {
10581     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10582     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10583   } else {
10584     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10585     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10586   }
10587
10588   // If the shift amount is larger or equal than the width of a part we can't
10589   // rely on the results of shld/shrd. Insert a test and select the appropriate
10590   // values for large shift amounts.
10591   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10592                                 DAG.getConstant(VTBits, MVT::i8));
10593   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10594                              AndNode, DAG.getConstant(0, MVT::i8));
10595
10596   SDValue Hi, Lo;
10597   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10598   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10599   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10600
10601   if (Op.getOpcode() == ISD::SHL_PARTS) {
10602     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10603     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10604   } else {
10605     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10606     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10607   }
10608
10609   SDValue Ops[2] = { Lo, Hi };
10610   return DAG.getMergeValues(Ops, dl);
10611 }
10612
10613 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10614                                            SelectionDAG &DAG) const {
10615   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10616
10617   if (SrcVT.isVector())
10618     return SDValue();
10619
10620   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10621          "Unknown SINT_TO_FP to lower!");
10622
10623   // These are really Legal; return the operand so the caller accepts it as
10624   // Legal.
10625   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10626     return Op;
10627   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10628       Subtarget->is64Bit()) {
10629     return Op;
10630   }
10631
10632   SDLoc dl(Op);
10633   unsigned Size = SrcVT.getSizeInBits()/8;
10634   MachineFunction &MF = DAG.getMachineFunction();
10635   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10636   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10637   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10638                                StackSlot,
10639                                MachinePointerInfo::getFixedStack(SSFI),
10640                                false, false, 0);
10641   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10642 }
10643
10644 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10645                                      SDValue StackSlot,
10646                                      SelectionDAG &DAG) const {
10647   // Build the FILD
10648   SDLoc DL(Op);
10649   SDVTList Tys;
10650   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10651   if (useSSE)
10652     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10653   else
10654     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10655
10656   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10657
10658   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10659   MachineMemOperand *MMO;
10660   if (FI) {
10661     int SSFI = FI->getIndex();
10662     MMO =
10663       DAG.getMachineFunction()
10664       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10665                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10666   } else {
10667     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10668     StackSlot = StackSlot.getOperand(1);
10669   }
10670   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10671   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10672                                            X86ISD::FILD, DL,
10673                                            Tys, Ops, SrcVT, MMO);
10674
10675   if (useSSE) {
10676     Chain = Result.getValue(1);
10677     SDValue InFlag = Result.getValue(2);
10678
10679     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10680     // shouldn't be necessary except that RFP cannot be live across
10681     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10682     MachineFunction &MF = DAG.getMachineFunction();
10683     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10684     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10685     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10686     Tys = DAG.getVTList(MVT::Other);
10687     SDValue Ops[] = {
10688       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10689     };
10690     MachineMemOperand *MMO =
10691       DAG.getMachineFunction()
10692       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10693                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10694
10695     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10696                                     Ops, Op.getValueType(), MMO);
10697     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10698                          MachinePointerInfo::getFixedStack(SSFI),
10699                          false, false, false, 0);
10700   }
10701
10702   return Result;
10703 }
10704
10705 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10706 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10707                                                SelectionDAG &DAG) const {
10708   // This algorithm is not obvious. Here it is what we're trying to output:
10709   /*
10710      movq       %rax,  %xmm0
10711      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10712      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10713      #ifdef __SSE3__
10714        haddpd   %xmm0, %xmm0
10715      #else
10716        pshufd   $0x4e, %xmm0, %xmm1
10717        addpd    %xmm1, %xmm0
10718      #endif
10719   */
10720
10721   SDLoc dl(Op);
10722   LLVMContext *Context = DAG.getContext();
10723
10724   // Build some magic constants.
10725   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10726   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10727   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10728
10729   SmallVector<Constant*,2> CV1;
10730   CV1.push_back(
10731     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10732                                       APInt(64, 0x4330000000000000ULL))));
10733   CV1.push_back(
10734     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10735                                       APInt(64, 0x4530000000000000ULL))));
10736   Constant *C1 = ConstantVector::get(CV1);
10737   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10738
10739   // Load the 64-bit value into an XMM register.
10740   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10741                             Op.getOperand(0));
10742   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10743                               MachinePointerInfo::getConstantPool(),
10744                               false, false, false, 16);
10745   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10746                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10747                               CLod0);
10748
10749   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10750                               MachinePointerInfo::getConstantPool(),
10751                               false, false, false, 16);
10752   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10753   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10754   SDValue Result;
10755
10756   if (Subtarget->hasSSE3()) {
10757     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10758     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10759   } else {
10760     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10761     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10762                                            S2F, 0x4E, DAG);
10763     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10764                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10765                          Sub);
10766   }
10767
10768   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10769                      DAG.getIntPtrConstant(0));
10770 }
10771
10772 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10773 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10774                                                SelectionDAG &DAG) const {
10775   SDLoc dl(Op);
10776   // FP constant to bias correct the final result.
10777   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10778                                    MVT::f64);
10779
10780   // Load the 32-bit value into an XMM register.
10781   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10782                              Op.getOperand(0));
10783
10784   // Zero out the upper parts of the register.
10785   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10786
10787   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10788                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10789                      DAG.getIntPtrConstant(0));
10790
10791   // Or the load with the bias.
10792   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10793                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10794                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10795                                                    MVT::v2f64, Load)),
10796                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10797                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10798                                                    MVT::v2f64, Bias)));
10799   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10800                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10801                    DAG.getIntPtrConstant(0));
10802
10803   // Subtract the bias.
10804   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10805
10806   // Handle final rounding.
10807   EVT DestVT = Op.getValueType();
10808
10809   if (DestVT.bitsLT(MVT::f64))
10810     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10811                        DAG.getIntPtrConstant(0));
10812   if (DestVT.bitsGT(MVT::f64))
10813     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10814
10815   // Handle final rounding.
10816   return Sub;
10817 }
10818
10819 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10820                                                SelectionDAG &DAG) const {
10821   SDValue N0 = Op.getOperand(0);
10822   MVT SVT = N0.getSimpleValueType();
10823   SDLoc dl(Op);
10824
10825   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10826           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10827          "Custom UINT_TO_FP is not supported!");
10828
10829   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10830   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10831                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10832 }
10833
10834 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10835                                            SelectionDAG &DAG) const {
10836   SDValue N0 = Op.getOperand(0);
10837   SDLoc dl(Op);
10838
10839   if (Op.getValueType().isVector())
10840     return lowerUINT_TO_FP_vec(Op, DAG);
10841
10842   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10843   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10844   // the optimization here.
10845   if (DAG.SignBitIsZero(N0))
10846     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10847
10848   MVT SrcVT = N0.getSimpleValueType();
10849   MVT DstVT = Op.getSimpleValueType();
10850   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10851     return LowerUINT_TO_FP_i64(Op, DAG);
10852   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10853     return LowerUINT_TO_FP_i32(Op, DAG);
10854   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10855     return SDValue();
10856
10857   // Make a 64-bit buffer, and use it to build an FILD.
10858   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10859   if (SrcVT == MVT::i32) {
10860     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10861     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10862                                      getPointerTy(), StackSlot, WordOff);
10863     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10864                                   StackSlot, MachinePointerInfo(),
10865                                   false, false, 0);
10866     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10867                                   OffsetSlot, MachinePointerInfo(),
10868                                   false, false, 0);
10869     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10870     return Fild;
10871   }
10872
10873   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10874   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10875                                StackSlot, MachinePointerInfo(),
10876                                false, false, 0);
10877   // For i64 source, we need to add the appropriate power of 2 if the input
10878   // was negative.  This is the same as the optimization in
10879   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10880   // we must be careful to do the computation in x87 extended precision, not
10881   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10882   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10883   MachineMemOperand *MMO =
10884     DAG.getMachineFunction()
10885     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10886                           MachineMemOperand::MOLoad, 8, 8);
10887
10888   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10889   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10890   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10891                                          MVT::i64, MMO);
10892
10893   APInt FF(32, 0x5F800000ULL);
10894
10895   // Check whether the sign bit is set.
10896   SDValue SignSet = DAG.getSetCC(dl,
10897                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
10898                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10899                                  ISD::SETLT);
10900
10901   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10902   SDValue FudgePtr = DAG.getConstantPool(
10903                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10904                                          getPointerTy());
10905
10906   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10907   SDValue Zero = DAG.getIntPtrConstant(0);
10908   SDValue Four = DAG.getIntPtrConstant(4);
10909   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10910                                Zero, Four);
10911   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10912
10913   // Load the value out, extending it from f32 to f80.
10914   // FIXME: Avoid the extend by constructing the right constant pool?
10915   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10916                                  FudgePtr, MachinePointerInfo::getConstantPool(),
10917                                  MVT::f32, false, false, 4);
10918   // Extend everything to 80 bits to force it to be done on x87.
10919   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10920   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10921 }
10922
10923 std::pair<SDValue,SDValue>
10924 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10925                                     bool IsSigned, bool IsReplace) const {
10926   SDLoc DL(Op);
10927
10928   EVT DstTy = Op.getValueType();
10929
10930   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10931     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10932     DstTy = MVT::i64;
10933   }
10934
10935   assert(DstTy.getSimpleVT() <= MVT::i64 &&
10936          DstTy.getSimpleVT() >= MVT::i16 &&
10937          "Unknown FP_TO_INT to lower!");
10938
10939   // These are really Legal.
10940   if (DstTy == MVT::i32 &&
10941       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10942     return std::make_pair(SDValue(), SDValue());
10943   if (Subtarget->is64Bit() &&
10944       DstTy == MVT::i64 &&
10945       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10946     return std::make_pair(SDValue(), SDValue());
10947
10948   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
10949   // stack slot, or into the FTOL runtime function.
10950   MachineFunction &MF = DAG.getMachineFunction();
10951   unsigned MemSize = DstTy.getSizeInBits()/8;
10952   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10953   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10954
10955   unsigned Opc;
10956   if (!IsSigned && isIntegerTypeFTOL(DstTy))
10957     Opc = X86ISD::WIN_FTOL;
10958   else
10959     switch (DstTy.getSimpleVT().SimpleTy) {
10960     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
10961     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
10962     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
10963     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
10964     }
10965
10966   SDValue Chain = DAG.getEntryNode();
10967   SDValue Value = Op.getOperand(0);
10968   EVT TheVT = Op.getOperand(0).getValueType();
10969   // FIXME This causes a redundant load/store if the SSE-class value is already
10970   // in memory, such as if it is on the callstack.
10971   if (isScalarFPTypeInSSEReg(TheVT)) {
10972     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
10973     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
10974                          MachinePointerInfo::getFixedStack(SSFI),
10975                          false, false, 0);
10976     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
10977     SDValue Ops[] = {
10978       Chain, StackSlot, DAG.getValueType(TheVT)
10979     };
10980
10981     MachineMemOperand *MMO =
10982       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10983                               MachineMemOperand::MOLoad, MemSize, MemSize);
10984     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
10985     Chain = Value.getValue(1);
10986     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10987     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10988   }
10989
10990   MachineMemOperand *MMO =
10991     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10992                             MachineMemOperand::MOStore, MemSize, MemSize);
10993
10994   if (Opc != X86ISD::WIN_FTOL) {
10995     // Build the FP_TO_INT*_IN_MEM
10996     SDValue Ops[] = { Chain, Value, StackSlot };
10997     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
10998                                            Ops, DstTy, MMO);
10999     return std::make_pair(FIST, StackSlot);
11000   } else {
11001     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11002       DAG.getVTList(MVT::Other, MVT::Glue),
11003       Chain, Value);
11004     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11005       MVT::i32, ftol.getValue(1));
11006     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11007       MVT::i32, eax.getValue(2));
11008     SDValue Ops[] = { eax, edx };
11009     SDValue pair = IsReplace
11010       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11011       : DAG.getMergeValues(Ops, DL);
11012     return std::make_pair(pair, SDValue());
11013   }
11014 }
11015
11016 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11017                               const X86Subtarget *Subtarget) {
11018   MVT VT = Op->getSimpleValueType(0);
11019   SDValue In = Op->getOperand(0);
11020   MVT InVT = In.getSimpleValueType();
11021   SDLoc dl(Op);
11022
11023   // Optimize vectors in AVX mode:
11024   //
11025   //   v8i16 -> v8i32
11026   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11027   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11028   //   Concat upper and lower parts.
11029   //
11030   //   v4i32 -> v4i64
11031   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11032   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11033   //   Concat upper and lower parts.
11034   //
11035
11036   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11037       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11038       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11039     return SDValue();
11040
11041   if (Subtarget->hasInt256())
11042     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11043
11044   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11045   SDValue Undef = DAG.getUNDEF(InVT);
11046   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11047   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11048   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11049
11050   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11051                              VT.getVectorNumElements()/2);
11052
11053   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11054   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11055
11056   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11057 }
11058
11059 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11060                                         SelectionDAG &DAG) {
11061   MVT VT = Op->getSimpleValueType(0);
11062   SDValue In = Op->getOperand(0);
11063   MVT InVT = In.getSimpleValueType();
11064   SDLoc DL(Op);
11065   unsigned int NumElts = VT.getVectorNumElements();
11066   if (NumElts != 8 && NumElts != 16)
11067     return SDValue();
11068
11069   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11070     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11071
11072   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11073   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11074   // Now we have only mask extension
11075   assert(InVT.getVectorElementType() == MVT::i1);
11076   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11077   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11078   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11079   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11080   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11081                            MachinePointerInfo::getConstantPool(),
11082                            false, false, false, Alignment);
11083
11084   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11085   if (VT.is512BitVector())
11086     return Brcst;
11087   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11088 }
11089
11090 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11091                                SelectionDAG &DAG) {
11092   if (Subtarget->hasFp256()) {
11093     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11094     if (Res.getNode())
11095       return Res;
11096   }
11097
11098   return SDValue();
11099 }
11100
11101 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11102                                 SelectionDAG &DAG) {
11103   SDLoc DL(Op);
11104   MVT VT = Op.getSimpleValueType();
11105   SDValue In = Op.getOperand(0);
11106   MVT SVT = In.getSimpleValueType();
11107
11108   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11109     return LowerZERO_EXTEND_AVX512(Op, DAG);
11110
11111   if (Subtarget->hasFp256()) {
11112     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11113     if (Res.getNode())
11114       return Res;
11115   }
11116
11117   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11118          VT.getVectorNumElements() != SVT.getVectorNumElements());
11119   return SDValue();
11120 }
11121
11122 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11123   SDLoc DL(Op);
11124   MVT VT = Op.getSimpleValueType();
11125   SDValue In = Op.getOperand(0);
11126   MVT InVT = In.getSimpleValueType();
11127
11128   if (VT == MVT::i1) {
11129     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11130            "Invalid scalar TRUNCATE operation");
11131     if (InVT == MVT::i32)
11132       return SDValue();
11133     if (InVT.getSizeInBits() == 64)
11134       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11135     else if (InVT.getSizeInBits() < 32)
11136       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11137     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11138   }
11139   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11140          "Invalid TRUNCATE operation");
11141
11142   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11143     if (VT.getVectorElementType().getSizeInBits() >=8)
11144       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11145
11146     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11147     unsigned NumElts = InVT.getVectorNumElements();
11148     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11149     if (InVT.getSizeInBits() < 512) {
11150       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11151       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11152       InVT = ExtVT;
11153     }
11154     
11155     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11156     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11157     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11158     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11159     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11160                            MachinePointerInfo::getConstantPool(),
11161                            false, false, false, Alignment);
11162     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11163     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11164     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11165   }
11166
11167   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11168     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11169     if (Subtarget->hasInt256()) {
11170       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11171       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11172       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11173                                 ShufMask);
11174       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11175                          DAG.getIntPtrConstant(0));
11176     }
11177
11178     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11179                                DAG.getIntPtrConstant(0));
11180     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11181                                DAG.getIntPtrConstant(2));
11182     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11183     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11184     static const int ShufMask[] = {0, 2, 4, 6};
11185     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11186   }
11187
11188   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11189     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11190     if (Subtarget->hasInt256()) {
11191       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11192
11193       SmallVector<SDValue,32> pshufbMask;
11194       for (unsigned i = 0; i < 2; ++i) {
11195         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11196         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11197         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11198         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11199         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11200         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11201         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11202         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11203         for (unsigned j = 0; j < 8; ++j)
11204           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11205       }
11206       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11207       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11208       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11209
11210       static const int ShufMask[] = {0,  2,  -1,  -1};
11211       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11212                                 &ShufMask[0]);
11213       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11214                        DAG.getIntPtrConstant(0));
11215       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11216     }
11217
11218     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11219                                DAG.getIntPtrConstant(0));
11220
11221     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11222                                DAG.getIntPtrConstant(4));
11223
11224     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11225     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11226
11227     // The PSHUFB mask:
11228     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11229                                    -1, -1, -1, -1, -1, -1, -1, -1};
11230
11231     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11232     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11233     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11234
11235     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11236     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11237
11238     // The MOVLHPS Mask:
11239     static const int ShufMask2[] = {0, 1, 4, 5};
11240     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11241     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11242   }
11243
11244   // Handle truncation of V256 to V128 using shuffles.
11245   if (!VT.is128BitVector() || !InVT.is256BitVector())
11246     return SDValue();
11247
11248   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11249
11250   unsigned NumElems = VT.getVectorNumElements();
11251   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11252
11253   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11254   // Prepare truncation shuffle mask
11255   for (unsigned i = 0; i != NumElems; ++i)
11256     MaskVec[i] = i * 2;
11257   SDValue V = DAG.getVectorShuffle(NVT, DL,
11258                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11259                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11260   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11261                      DAG.getIntPtrConstant(0));
11262 }
11263
11264 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11265                                            SelectionDAG &DAG) const {
11266   assert(!Op.getSimpleValueType().isVector());
11267
11268   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11269     /*IsSigned=*/ true, /*IsReplace=*/ false);
11270   SDValue FIST = Vals.first, StackSlot = Vals.second;
11271   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11272   if (!FIST.getNode()) return Op;
11273
11274   if (StackSlot.getNode())
11275     // Load the result.
11276     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11277                        FIST, StackSlot, MachinePointerInfo(),
11278                        false, false, false, 0);
11279
11280   // The node is the result.
11281   return FIST;
11282 }
11283
11284 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11285                                            SelectionDAG &DAG) const {
11286   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11287     /*IsSigned=*/ false, /*IsReplace=*/ false);
11288   SDValue FIST = Vals.first, StackSlot = Vals.second;
11289   assert(FIST.getNode() && "Unexpected failure");
11290
11291   if (StackSlot.getNode())
11292     // Load the result.
11293     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11294                        FIST, StackSlot, MachinePointerInfo(),
11295                        false, false, false, 0);
11296
11297   // The node is the result.
11298   return FIST;
11299 }
11300
11301 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11302   SDLoc DL(Op);
11303   MVT VT = Op.getSimpleValueType();
11304   SDValue In = Op.getOperand(0);
11305   MVT SVT = In.getSimpleValueType();
11306
11307   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11308
11309   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11310                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11311                                  In, DAG.getUNDEF(SVT)));
11312 }
11313
11314 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11315   LLVMContext *Context = DAG.getContext();
11316   SDLoc dl(Op);
11317   MVT VT = Op.getSimpleValueType();
11318   MVT EltVT = VT;
11319   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11320   if (VT.isVector()) {
11321     EltVT = VT.getVectorElementType();
11322     NumElts = VT.getVectorNumElements();
11323   }
11324   Constant *C;
11325   if (EltVT == MVT::f64)
11326     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11327                                           APInt(64, ~(1ULL << 63))));
11328   else
11329     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11330                                           APInt(32, ~(1U << 31))));
11331   C = ConstantVector::getSplat(NumElts, C);
11332   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11333   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11334   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11335   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11336                              MachinePointerInfo::getConstantPool(),
11337                              false, false, false, Alignment);
11338   if (VT.isVector()) {
11339     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11340     return DAG.getNode(ISD::BITCAST, dl, VT,
11341                        DAG.getNode(ISD::AND, dl, ANDVT,
11342                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11343                                                Op.getOperand(0)),
11344                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11345   }
11346   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11347 }
11348
11349 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11350   LLVMContext *Context = DAG.getContext();
11351   SDLoc dl(Op);
11352   MVT VT = Op.getSimpleValueType();
11353   MVT EltVT = VT;
11354   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11355   if (VT.isVector()) {
11356     EltVT = VT.getVectorElementType();
11357     NumElts = VT.getVectorNumElements();
11358   }
11359   Constant *C;
11360   if (EltVT == MVT::f64)
11361     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11362                                           APInt(64, 1ULL << 63)));
11363   else
11364     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11365                                           APInt(32, 1U << 31)));
11366   C = ConstantVector::getSplat(NumElts, C);
11367   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11368   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11369   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11370   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11371                              MachinePointerInfo::getConstantPool(),
11372                              false, false, false, Alignment);
11373   if (VT.isVector()) {
11374     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11375     return DAG.getNode(ISD::BITCAST, dl, VT,
11376                        DAG.getNode(ISD::XOR, dl, XORVT,
11377                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11378                                                Op.getOperand(0)),
11379                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11380   }
11381
11382   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11383 }
11384
11385 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11386   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11387   LLVMContext *Context = DAG.getContext();
11388   SDValue Op0 = Op.getOperand(0);
11389   SDValue Op1 = Op.getOperand(1);
11390   SDLoc dl(Op);
11391   MVT VT = Op.getSimpleValueType();
11392   MVT SrcVT = Op1.getSimpleValueType();
11393
11394   // If second operand is smaller, extend it first.
11395   if (SrcVT.bitsLT(VT)) {
11396     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11397     SrcVT = VT;
11398   }
11399   // And if it is bigger, shrink it first.
11400   if (SrcVT.bitsGT(VT)) {
11401     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11402     SrcVT = VT;
11403   }
11404
11405   // At this point the operands and the result should have the same
11406   // type, and that won't be f80 since that is not custom lowered.
11407
11408   // First get the sign bit of second operand.
11409   SmallVector<Constant*,4> CV;
11410   if (SrcVT == MVT::f64) {
11411     const fltSemantics &Sem = APFloat::IEEEdouble;
11412     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11413     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11414   } else {
11415     const fltSemantics &Sem = APFloat::IEEEsingle;
11416     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11417     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11418     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11419     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11420   }
11421   Constant *C = ConstantVector::get(CV);
11422   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11423   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11424                               MachinePointerInfo::getConstantPool(),
11425                               false, false, false, 16);
11426   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11427
11428   // Shift sign bit right or left if the two operands have different types.
11429   if (SrcVT.bitsGT(VT)) {
11430     // Op0 is MVT::f32, Op1 is MVT::f64.
11431     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11432     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11433                           DAG.getConstant(32, MVT::i32));
11434     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11435     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11436                           DAG.getIntPtrConstant(0));
11437   }
11438
11439   // Clear first operand sign bit.
11440   CV.clear();
11441   if (VT == MVT::f64) {
11442     const fltSemantics &Sem = APFloat::IEEEdouble;
11443     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11444                                                    APInt(64, ~(1ULL << 63)))));
11445     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11446   } else {
11447     const fltSemantics &Sem = APFloat::IEEEsingle;
11448     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11449                                                    APInt(32, ~(1U << 31)))));
11450     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11451     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11452     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11453   }
11454   C = ConstantVector::get(CV);
11455   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11456   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11457                               MachinePointerInfo::getConstantPool(),
11458                               false, false, false, 16);
11459   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11460
11461   // Or the value with the sign bit.
11462   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11463 }
11464
11465 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11466   SDValue N0 = Op.getOperand(0);
11467   SDLoc dl(Op);
11468   MVT VT = Op.getSimpleValueType();
11469
11470   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11471   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11472                                   DAG.getConstant(1, VT));
11473   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11474 }
11475
11476 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11477 //
11478 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11479                                       SelectionDAG &DAG) {
11480   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11481
11482   if (!Subtarget->hasSSE41())
11483     return SDValue();
11484
11485   if (!Op->hasOneUse())
11486     return SDValue();
11487
11488   SDNode *N = Op.getNode();
11489   SDLoc DL(N);
11490
11491   SmallVector<SDValue, 8> Opnds;
11492   DenseMap<SDValue, unsigned> VecInMap;
11493   SmallVector<SDValue, 8> VecIns;
11494   EVT VT = MVT::Other;
11495
11496   // Recognize a special case where a vector is casted into wide integer to
11497   // test all 0s.
11498   Opnds.push_back(N->getOperand(0));
11499   Opnds.push_back(N->getOperand(1));
11500
11501   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11502     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11503     // BFS traverse all OR'd operands.
11504     if (I->getOpcode() == ISD::OR) {
11505       Opnds.push_back(I->getOperand(0));
11506       Opnds.push_back(I->getOperand(1));
11507       // Re-evaluate the number of nodes to be traversed.
11508       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11509       continue;
11510     }
11511
11512     // Quit if a non-EXTRACT_VECTOR_ELT
11513     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11514       return SDValue();
11515
11516     // Quit if without a constant index.
11517     SDValue Idx = I->getOperand(1);
11518     if (!isa<ConstantSDNode>(Idx))
11519       return SDValue();
11520
11521     SDValue ExtractedFromVec = I->getOperand(0);
11522     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11523     if (M == VecInMap.end()) {
11524       VT = ExtractedFromVec.getValueType();
11525       // Quit if not 128/256-bit vector.
11526       if (!VT.is128BitVector() && !VT.is256BitVector())
11527         return SDValue();
11528       // Quit if not the same type.
11529       if (VecInMap.begin() != VecInMap.end() &&
11530           VT != VecInMap.begin()->first.getValueType())
11531         return SDValue();
11532       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11533       VecIns.push_back(ExtractedFromVec);
11534     }
11535     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11536   }
11537
11538   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11539          "Not extracted from 128-/256-bit vector.");
11540
11541   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11542
11543   for (DenseMap<SDValue, unsigned>::const_iterator
11544         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11545     // Quit if not all elements are used.
11546     if (I->second != FullMask)
11547       return SDValue();
11548   }
11549
11550   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11551
11552   // Cast all vectors into TestVT for PTEST.
11553   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11554     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11555
11556   // If more than one full vectors are evaluated, OR them first before PTEST.
11557   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11558     // Each iteration will OR 2 nodes and append the result until there is only
11559     // 1 node left, i.e. the final OR'd value of all vectors.
11560     SDValue LHS = VecIns[Slot];
11561     SDValue RHS = VecIns[Slot + 1];
11562     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11563   }
11564
11565   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11566                      VecIns.back(), VecIns.back());
11567 }
11568
11569 /// \brief return true if \c Op has a use that doesn't just read flags.
11570 static bool hasNonFlagsUse(SDValue Op) {
11571   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11572        ++UI) {
11573     SDNode *User = *UI;
11574     unsigned UOpNo = UI.getOperandNo();
11575     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11576       // Look pass truncate.
11577       UOpNo = User->use_begin().getOperandNo();
11578       User = *User->use_begin();
11579     }
11580
11581     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11582         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11583       return true;
11584   }
11585   return false;
11586 }
11587
11588 /// Emit nodes that will be selected as "test Op0,Op0", or something
11589 /// equivalent.
11590 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11591                                     SelectionDAG &DAG) const {
11592   if (Op.getValueType() == MVT::i1)
11593     // KORTEST instruction should be selected
11594     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11595                        DAG.getConstant(0, Op.getValueType()));
11596
11597   // CF and OF aren't always set the way we want. Determine which
11598   // of these we need.
11599   bool NeedCF = false;
11600   bool NeedOF = false;
11601   switch (X86CC) {
11602   default: break;
11603   case X86::COND_A: case X86::COND_AE:
11604   case X86::COND_B: case X86::COND_BE:
11605     NeedCF = true;
11606     break;
11607   case X86::COND_G: case X86::COND_GE:
11608   case X86::COND_L: case X86::COND_LE:
11609   case X86::COND_O: case X86::COND_NO: {
11610     // Check if we really need to set the
11611     // Overflow flag. If NoSignedWrap is present
11612     // that is not actually needed.
11613     switch (Op->getOpcode()) {
11614     case ISD::ADD:
11615     case ISD::SUB:
11616     case ISD::MUL:
11617     case ISD::SHL: {
11618       const BinaryWithFlagsSDNode *BinNode =
11619           cast<BinaryWithFlagsSDNode>(Op.getNode());
11620       if (BinNode->hasNoSignedWrap())
11621         break;
11622     }
11623     default:
11624       NeedOF = true;
11625       break;
11626     }
11627     break;
11628   }
11629   }
11630   // See if we can use the EFLAGS value from the operand instead of
11631   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11632   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11633   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11634     // Emit a CMP with 0, which is the TEST pattern.
11635     //if (Op.getValueType() == MVT::i1)
11636     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11637     //                     DAG.getConstant(0, MVT::i1));
11638     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11639                        DAG.getConstant(0, Op.getValueType()));
11640   }
11641   unsigned Opcode = 0;
11642   unsigned NumOperands = 0;
11643
11644   // Truncate operations may prevent the merge of the SETCC instruction
11645   // and the arithmetic instruction before it. Attempt to truncate the operands
11646   // of the arithmetic instruction and use a reduced bit-width instruction.
11647   bool NeedTruncation = false;
11648   SDValue ArithOp = Op;
11649   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11650     SDValue Arith = Op->getOperand(0);
11651     // Both the trunc and the arithmetic op need to have one user each.
11652     if (Arith->hasOneUse())
11653       switch (Arith.getOpcode()) {
11654         default: break;
11655         case ISD::ADD:
11656         case ISD::SUB:
11657         case ISD::AND:
11658         case ISD::OR:
11659         case ISD::XOR: {
11660           NeedTruncation = true;
11661           ArithOp = Arith;
11662         }
11663       }
11664   }
11665
11666   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11667   // which may be the result of a CAST.  We use the variable 'Op', which is the
11668   // non-casted variable when we check for possible users.
11669   switch (ArithOp.getOpcode()) {
11670   case ISD::ADD:
11671     // Due to an isel shortcoming, be conservative if this add is likely to be
11672     // selected as part of a load-modify-store instruction. When the root node
11673     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11674     // uses of other nodes in the match, such as the ADD in this case. This
11675     // leads to the ADD being left around and reselected, with the result being
11676     // two adds in the output.  Alas, even if none our users are stores, that
11677     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11678     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11679     // climbing the DAG back to the root, and it doesn't seem to be worth the
11680     // effort.
11681     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11682          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11683       if (UI->getOpcode() != ISD::CopyToReg &&
11684           UI->getOpcode() != ISD::SETCC &&
11685           UI->getOpcode() != ISD::STORE)
11686         goto default_case;
11687
11688     if (ConstantSDNode *C =
11689         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11690       // An add of one will be selected as an INC.
11691       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11692         Opcode = X86ISD::INC;
11693         NumOperands = 1;
11694         break;
11695       }
11696
11697       // An add of negative one (subtract of one) will be selected as a DEC.
11698       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11699         Opcode = X86ISD::DEC;
11700         NumOperands = 1;
11701         break;
11702       }
11703     }
11704
11705     // Otherwise use a regular EFLAGS-setting add.
11706     Opcode = X86ISD::ADD;
11707     NumOperands = 2;
11708     break;
11709   case ISD::SHL:
11710   case ISD::SRL:
11711     // If we have a constant logical shift that's only used in a comparison
11712     // against zero turn it into an equivalent AND. This allows turning it into
11713     // a TEST instruction later.
11714     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11715         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11716       EVT VT = Op.getValueType();
11717       unsigned BitWidth = VT.getSizeInBits();
11718       unsigned ShAmt = Op->getConstantOperandVal(1);
11719       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11720         break;
11721       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11722                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11723                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11724       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11725         break;
11726       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11727                                 DAG.getConstant(Mask, VT));
11728       DAG.ReplaceAllUsesWith(Op, New);
11729       Op = New;
11730     }
11731     break;
11732
11733   case ISD::AND:
11734     // If the primary and result isn't used, don't bother using X86ISD::AND,
11735     // because a TEST instruction will be better.
11736     if (!hasNonFlagsUse(Op))
11737       break;
11738     // FALL THROUGH
11739   case ISD::SUB:
11740   case ISD::OR:
11741   case ISD::XOR:
11742     // Due to the ISEL shortcoming noted above, be conservative if this op is
11743     // likely to be selected as part of a load-modify-store instruction.
11744     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11745            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11746       if (UI->getOpcode() == ISD::STORE)
11747         goto default_case;
11748
11749     // Otherwise use a regular EFLAGS-setting instruction.
11750     switch (ArithOp.getOpcode()) {
11751     default: llvm_unreachable("unexpected operator!");
11752     case ISD::SUB: Opcode = X86ISD::SUB; break;
11753     case ISD::XOR: Opcode = X86ISD::XOR; break;
11754     case ISD::AND: Opcode = X86ISD::AND; break;
11755     case ISD::OR: {
11756       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11757         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11758         if (EFLAGS.getNode())
11759           return EFLAGS;
11760       }
11761       Opcode = X86ISD::OR;
11762       break;
11763     }
11764     }
11765
11766     NumOperands = 2;
11767     break;
11768   case X86ISD::ADD:
11769   case X86ISD::SUB:
11770   case X86ISD::INC:
11771   case X86ISD::DEC:
11772   case X86ISD::OR:
11773   case X86ISD::XOR:
11774   case X86ISD::AND:
11775     return SDValue(Op.getNode(), 1);
11776   default:
11777   default_case:
11778     break;
11779   }
11780
11781   // If we found that truncation is beneficial, perform the truncation and
11782   // update 'Op'.
11783   if (NeedTruncation) {
11784     EVT VT = Op.getValueType();
11785     SDValue WideVal = Op->getOperand(0);
11786     EVT WideVT = WideVal.getValueType();
11787     unsigned ConvertedOp = 0;
11788     // Use a target machine opcode to prevent further DAGCombine
11789     // optimizations that may separate the arithmetic operations
11790     // from the setcc node.
11791     switch (WideVal.getOpcode()) {
11792       default: break;
11793       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11794       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11795       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11796       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11797       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11798     }
11799
11800     if (ConvertedOp) {
11801       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11802       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11803         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11804         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11805         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11806       }
11807     }
11808   }
11809
11810   if (Opcode == 0)
11811     // Emit a CMP with 0, which is the TEST pattern.
11812     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11813                        DAG.getConstant(0, Op.getValueType()));
11814
11815   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11816   SmallVector<SDValue, 4> Ops;
11817   for (unsigned i = 0; i != NumOperands; ++i)
11818     Ops.push_back(Op.getOperand(i));
11819
11820   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11821   DAG.ReplaceAllUsesWith(Op, New);
11822   return SDValue(New.getNode(), 1);
11823 }
11824
11825 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11826 /// equivalent.
11827 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11828                                    SDLoc dl, SelectionDAG &DAG) const {
11829   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11830     if (C->getAPIntValue() == 0)
11831       return EmitTest(Op0, X86CC, dl, DAG);
11832
11833      if (Op0.getValueType() == MVT::i1)
11834        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11835   }
11836  
11837   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11838        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11839     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11840     // This avoids subregister aliasing issues. Keep the smaller reference 
11841     // if we're optimizing for size, however, as that'll allow better folding 
11842     // of memory operations.
11843     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11844         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11845              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11846         !Subtarget->isAtom()) {
11847       unsigned ExtendOp =
11848           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11849       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11850       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11851     }
11852     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11853     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11854     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11855                               Op0, Op1);
11856     return SDValue(Sub.getNode(), 1);
11857   }
11858   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11859 }
11860
11861 /// Convert a comparison if required by the subtarget.
11862 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11863                                                  SelectionDAG &DAG) const {
11864   // If the subtarget does not support the FUCOMI instruction, floating-point
11865   // comparisons have to be converted.
11866   if (Subtarget->hasCMov() ||
11867       Cmp.getOpcode() != X86ISD::CMP ||
11868       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11869       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11870     return Cmp;
11871
11872   // The instruction selector will select an FUCOM instruction instead of
11873   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11874   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11875   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11876   SDLoc dl(Cmp);
11877   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11878   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11879   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11880                             DAG.getConstant(8, MVT::i8));
11881   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11882   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11883 }
11884
11885 static bool isAllOnes(SDValue V) {
11886   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11887   return C && C->isAllOnesValue();
11888 }
11889
11890 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11891 /// if it's possible.
11892 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11893                                      SDLoc dl, SelectionDAG &DAG) const {
11894   SDValue Op0 = And.getOperand(0);
11895   SDValue Op1 = And.getOperand(1);
11896   if (Op0.getOpcode() == ISD::TRUNCATE)
11897     Op0 = Op0.getOperand(0);
11898   if (Op1.getOpcode() == ISD::TRUNCATE)
11899     Op1 = Op1.getOperand(0);
11900
11901   SDValue LHS, RHS;
11902   if (Op1.getOpcode() == ISD::SHL)
11903     std::swap(Op0, Op1);
11904   if (Op0.getOpcode() == ISD::SHL) {
11905     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11906       if (And00C->getZExtValue() == 1) {
11907         // If we looked past a truncate, check that it's only truncating away
11908         // known zeros.
11909         unsigned BitWidth = Op0.getValueSizeInBits();
11910         unsigned AndBitWidth = And.getValueSizeInBits();
11911         if (BitWidth > AndBitWidth) {
11912           APInt Zeros, Ones;
11913           DAG.computeKnownBits(Op0, Zeros, Ones);
11914           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11915             return SDValue();
11916         }
11917         LHS = Op1;
11918         RHS = Op0.getOperand(1);
11919       }
11920   } else if (Op1.getOpcode() == ISD::Constant) {
11921     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11922     uint64_t AndRHSVal = AndRHS->getZExtValue();
11923     SDValue AndLHS = Op0;
11924
11925     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11926       LHS = AndLHS.getOperand(0);
11927       RHS = AndLHS.getOperand(1);
11928     }
11929
11930     // Use BT if the immediate can't be encoded in a TEST instruction.
11931     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11932       LHS = AndLHS;
11933       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11934     }
11935   }
11936
11937   if (LHS.getNode()) {
11938     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
11939     // instruction.  Since the shift amount is in-range-or-undefined, we know
11940     // that doing a bittest on the i32 value is ok.  We extend to i32 because
11941     // the encoding for the i16 version is larger than the i32 version.
11942     // Also promote i16 to i32 for performance / code size reason.
11943     if (LHS.getValueType() == MVT::i8 ||
11944         LHS.getValueType() == MVT::i16)
11945       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
11946
11947     // If the operand types disagree, extend the shift amount to match.  Since
11948     // BT ignores high bits (like shifts) we can use anyextend.
11949     if (LHS.getValueType() != RHS.getValueType())
11950       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
11951
11952     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
11953     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
11954     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11955                        DAG.getConstant(Cond, MVT::i8), BT);
11956   }
11957
11958   return SDValue();
11959 }
11960
11961 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
11962 /// mask CMPs.
11963 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
11964                               SDValue &Op1) {
11965   unsigned SSECC;
11966   bool Swap = false;
11967
11968   // SSE Condition code mapping:
11969   //  0 - EQ
11970   //  1 - LT
11971   //  2 - LE
11972   //  3 - UNORD
11973   //  4 - NEQ
11974   //  5 - NLT
11975   //  6 - NLE
11976   //  7 - ORD
11977   switch (SetCCOpcode) {
11978   default: llvm_unreachable("Unexpected SETCC condition");
11979   case ISD::SETOEQ:
11980   case ISD::SETEQ:  SSECC = 0; break;
11981   case ISD::SETOGT:
11982   case ISD::SETGT:  Swap = true; // Fallthrough
11983   case ISD::SETLT:
11984   case ISD::SETOLT: SSECC = 1; break;
11985   case ISD::SETOGE:
11986   case ISD::SETGE:  Swap = true; // Fallthrough
11987   case ISD::SETLE:
11988   case ISD::SETOLE: SSECC = 2; break;
11989   case ISD::SETUO:  SSECC = 3; break;
11990   case ISD::SETUNE:
11991   case ISD::SETNE:  SSECC = 4; break;
11992   case ISD::SETULE: Swap = true; // Fallthrough
11993   case ISD::SETUGE: SSECC = 5; break;
11994   case ISD::SETULT: Swap = true; // Fallthrough
11995   case ISD::SETUGT: SSECC = 6; break;
11996   case ISD::SETO:   SSECC = 7; break;
11997   case ISD::SETUEQ:
11998   case ISD::SETONE: SSECC = 8; break;
11999   }
12000   if (Swap)
12001     std::swap(Op0, Op1);
12002
12003   return SSECC;
12004 }
12005
12006 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12007 // ones, and then concatenate the result back.
12008 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12009   MVT VT = Op.getSimpleValueType();
12010
12011   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12012          "Unsupported value type for operation");
12013
12014   unsigned NumElems = VT.getVectorNumElements();
12015   SDLoc dl(Op);
12016   SDValue CC = Op.getOperand(2);
12017
12018   // Extract the LHS vectors
12019   SDValue LHS = Op.getOperand(0);
12020   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12021   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12022
12023   // Extract the RHS vectors
12024   SDValue RHS = Op.getOperand(1);
12025   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12026   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12027
12028   // Issue the operation on the smaller types and concatenate the result back
12029   MVT EltVT = VT.getVectorElementType();
12030   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12031   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12032                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12033                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12034 }
12035
12036 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12037                                      const X86Subtarget *Subtarget) {
12038   SDValue Op0 = Op.getOperand(0);
12039   SDValue Op1 = Op.getOperand(1);
12040   SDValue CC = Op.getOperand(2);
12041   MVT VT = Op.getSimpleValueType();
12042   SDLoc dl(Op);
12043
12044   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12045          Op.getValueType().getScalarType() == MVT::i1 &&
12046          "Cannot set masked compare for this operation");
12047
12048   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12049   unsigned  Opc = 0;
12050   bool Unsigned = false;
12051   bool Swap = false;
12052   unsigned SSECC;
12053   switch (SetCCOpcode) {
12054   default: llvm_unreachable("Unexpected SETCC condition");
12055   case ISD::SETNE:  SSECC = 4; break;
12056   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12057   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12058   case ISD::SETLT:  Swap = true; //fall-through
12059   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12060   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12061   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12062   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12063   case ISD::SETULE: Unsigned = true; //fall-through
12064   case ISD::SETLE:  SSECC = 2; break;
12065   }
12066
12067   if (Swap)
12068     std::swap(Op0, Op1);
12069   if (Opc)
12070     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12071   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12072   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12073                      DAG.getConstant(SSECC, MVT::i8));
12074 }
12075
12076 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12077 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12078 /// return an empty value.
12079 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12080 {
12081   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12082   if (!BV)
12083     return SDValue();
12084
12085   MVT VT = Op1.getSimpleValueType();
12086   MVT EVT = VT.getVectorElementType();
12087   unsigned n = VT.getVectorNumElements();
12088   SmallVector<SDValue, 8> ULTOp1;
12089
12090   for (unsigned i = 0; i < n; ++i) {
12091     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12092     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12093       return SDValue();
12094
12095     // Avoid underflow.
12096     APInt Val = Elt->getAPIntValue();
12097     if (Val == 0)
12098       return SDValue();
12099
12100     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12101   }
12102
12103   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12104 }
12105
12106 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12107                            SelectionDAG &DAG) {
12108   SDValue Op0 = Op.getOperand(0);
12109   SDValue Op1 = Op.getOperand(1);
12110   SDValue CC = Op.getOperand(2);
12111   MVT VT = Op.getSimpleValueType();
12112   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12113   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12114   SDLoc dl(Op);
12115
12116   if (isFP) {
12117 #ifndef NDEBUG
12118     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12119     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12120 #endif
12121
12122     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12123     unsigned Opc = X86ISD::CMPP;
12124     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12125       assert(VT.getVectorNumElements() <= 16);
12126       Opc = X86ISD::CMPM;
12127     }
12128     // In the two special cases we can't handle, emit two comparisons.
12129     if (SSECC == 8) {
12130       unsigned CC0, CC1;
12131       unsigned CombineOpc;
12132       if (SetCCOpcode == ISD::SETUEQ) {
12133         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12134       } else {
12135         assert(SetCCOpcode == ISD::SETONE);
12136         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12137       }
12138
12139       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12140                                  DAG.getConstant(CC0, MVT::i8));
12141       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12142                                  DAG.getConstant(CC1, MVT::i8));
12143       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12144     }
12145     // Handle all other FP comparisons here.
12146     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12147                        DAG.getConstant(SSECC, MVT::i8));
12148   }
12149
12150   // Break 256-bit integer vector compare into smaller ones.
12151   if (VT.is256BitVector() && !Subtarget->hasInt256())
12152     return Lower256IntVSETCC(Op, DAG);
12153
12154   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12155   EVT OpVT = Op1.getValueType();
12156   if (Subtarget->hasAVX512()) {
12157     if (Op1.getValueType().is512BitVector() ||
12158         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12159       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12160
12161     // In AVX-512 architecture setcc returns mask with i1 elements,
12162     // But there is no compare instruction for i8 and i16 elements.
12163     // We are not talking about 512-bit operands in this case, these
12164     // types are illegal.
12165     if (MaskResult &&
12166         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12167          OpVT.getVectorElementType().getSizeInBits() >= 8))
12168       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12169                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12170   }
12171
12172   // We are handling one of the integer comparisons here.  Since SSE only has
12173   // GT and EQ comparisons for integer, swapping operands and multiple
12174   // operations may be required for some comparisons.
12175   unsigned Opc;
12176   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12177   bool Subus = false;
12178
12179   switch (SetCCOpcode) {
12180   default: llvm_unreachable("Unexpected SETCC condition");
12181   case ISD::SETNE:  Invert = true;
12182   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12183   case ISD::SETLT:  Swap = true;
12184   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12185   case ISD::SETGE:  Swap = true;
12186   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12187                     Invert = true; break;
12188   case ISD::SETULT: Swap = true;
12189   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12190                     FlipSigns = true; break;
12191   case ISD::SETUGE: Swap = true;
12192   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12193                     FlipSigns = true; Invert = true; break;
12194   }
12195
12196   // Special case: Use min/max operations for SETULE/SETUGE
12197   MVT VET = VT.getVectorElementType();
12198   bool hasMinMax =
12199        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12200     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12201
12202   if (hasMinMax) {
12203     switch (SetCCOpcode) {
12204     default: break;
12205     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12206     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12207     }
12208
12209     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12210   }
12211
12212   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12213   if (!MinMax && hasSubus) {
12214     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12215     // Op0 u<= Op1:
12216     //   t = psubus Op0, Op1
12217     //   pcmpeq t, <0..0>
12218     switch (SetCCOpcode) {
12219     default: break;
12220     case ISD::SETULT: {
12221       // If the comparison is against a constant we can turn this into a
12222       // setule.  With psubus, setule does not require a swap.  This is
12223       // beneficial because the constant in the register is no longer
12224       // destructed as the destination so it can be hoisted out of a loop.
12225       // Only do this pre-AVX since vpcmp* is no longer destructive.
12226       if (Subtarget->hasAVX())
12227         break;
12228       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12229       if (ULEOp1.getNode()) {
12230         Op1 = ULEOp1;
12231         Subus = true; Invert = false; Swap = false;
12232       }
12233       break;
12234     }
12235     // Psubus is better than flip-sign because it requires no inversion.
12236     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12237     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12238     }
12239
12240     if (Subus) {
12241       Opc = X86ISD::SUBUS;
12242       FlipSigns = false;
12243     }
12244   }
12245
12246   if (Swap)
12247     std::swap(Op0, Op1);
12248
12249   // Check that the operation in question is available (most are plain SSE2,
12250   // but PCMPGTQ and PCMPEQQ have different requirements).
12251   if (VT == MVT::v2i64) {
12252     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12253       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12254
12255       // First cast everything to the right type.
12256       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12257       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12258
12259       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12260       // bits of the inputs before performing those operations. The lower
12261       // compare is always unsigned.
12262       SDValue SB;
12263       if (FlipSigns) {
12264         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12265       } else {
12266         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12267         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12268         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12269                          Sign, Zero, Sign, Zero);
12270       }
12271       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12272       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12273
12274       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12275       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12276       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12277
12278       // Create masks for only the low parts/high parts of the 64 bit integers.
12279       static const int MaskHi[] = { 1, 1, 3, 3 };
12280       static const int MaskLo[] = { 0, 0, 2, 2 };
12281       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12282       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12283       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12284
12285       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12286       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12287
12288       if (Invert)
12289         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12290
12291       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12292     }
12293
12294     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12295       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12296       // pcmpeqd + pshufd + pand.
12297       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12298
12299       // First cast everything to the right type.
12300       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12301       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12302
12303       // Do the compare.
12304       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12305
12306       // Make sure the lower and upper halves are both all-ones.
12307       static const int Mask[] = { 1, 0, 3, 2 };
12308       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12309       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12310
12311       if (Invert)
12312         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12313
12314       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12315     }
12316   }
12317
12318   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12319   // bits of the inputs before performing those operations.
12320   if (FlipSigns) {
12321     EVT EltVT = VT.getVectorElementType();
12322     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12323     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12324     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12325   }
12326
12327   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12328
12329   // If the logical-not of the result is required, perform that now.
12330   if (Invert)
12331     Result = DAG.getNOT(dl, Result, VT);
12332
12333   if (MinMax)
12334     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12335
12336   if (Subus)
12337     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12338                          getZeroVector(VT, Subtarget, DAG, dl));
12339
12340   return Result;
12341 }
12342
12343 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12344
12345   MVT VT = Op.getSimpleValueType();
12346
12347   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12348
12349   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12350          && "SetCC type must be 8-bit or 1-bit integer");
12351   SDValue Op0 = Op.getOperand(0);
12352   SDValue Op1 = Op.getOperand(1);
12353   SDLoc dl(Op);
12354   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12355
12356   // Optimize to BT if possible.
12357   // Lower (X & (1 << N)) == 0 to BT(X, N).
12358   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12359   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12360   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12361       Op1.getOpcode() == ISD::Constant &&
12362       cast<ConstantSDNode>(Op1)->isNullValue() &&
12363       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12364     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12365     if (NewSetCC.getNode())
12366       return NewSetCC;
12367   }
12368
12369   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12370   // these.
12371   if (Op1.getOpcode() == ISD::Constant &&
12372       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12373        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12374       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12375
12376     // If the input is a setcc, then reuse the input setcc or use a new one with
12377     // the inverted condition.
12378     if (Op0.getOpcode() == X86ISD::SETCC) {
12379       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12380       bool Invert = (CC == ISD::SETNE) ^
12381         cast<ConstantSDNode>(Op1)->isNullValue();
12382       if (!Invert)
12383         return Op0;
12384
12385       CCode = X86::GetOppositeBranchCondition(CCode);
12386       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12387                                   DAG.getConstant(CCode, MVT::i8),
12388                                   Op0.getOperand(1));
12389       if (VT == MVT::i1)
12390         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12391       return SetCC;
12392     }
12393   }
12394   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12395       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12396       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12397
12398     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12399     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12400   }
12401
12402   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12403   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12404   if (X86CC == X86::COND_INVALID)
12405     return SDValue();
12406
12407   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12408   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12409   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12410                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12411   if (VT == MVT::i1)
12412     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12413   return SetCC;
12414 }
12415
12416 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12417 static bool isX86LogicalCmp(SDValue Op) {
12418   unsigned Opc = Op.getNode()->getOpcode();
12419   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12420       Opc == X86ISD::SAHF)
12421     return true;
12422   if (Op.getResNo() == 1 &&
12423       (Opc == X86ISD::ADD ||
12424        Opc == X86ISD::SUB ||
12425        Opc == X86ISD::ADC ||
12426        Opc == X86ISD::SBB ||
12427        Opc == X86ISD::SMUL ||
12428        Opc == X86ISD::UMUL ||
12429        Opc == X86ISD::INC ||
12430        Opc == X86ISD::DEC ||
12431        Opc == X86ISD::OR ||
12432        Opc == X86ISD::XOR ||
12433        Opc == X86ISD::AND))
12434     return true;
12435
12436   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12437     return true;
12438
12439   return false;
12440 }
12441
12442 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12443   if (V.getOpcode() != ISD::TRUNCATE)
12444     return false;
12445
12446   SDValue VOp0 = V.getOperand(0);
12447   unsigned InBits = VOp0.getValueSizeInBits();
12448   unsigned Bits = V.getValueSizeInBits();
12449   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12450 }
12451
12452 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12453   bool addTest = true;
12454   SDValue Cond  = Op.getOperand(0);
12455   SDValue Op1 = Op.getOperand(1);
12456   SDValue Op2 = Op.getOperand(2);
12457   SDLoc DL(Op);
12458   EVT VT = Op1.getValueType();
12459   SDValue CC;
12460
12461   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12462   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12463   // sequence later on.
12464   if (Cond.getOpcode() == ISD::SETCC &&
12465       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12466        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12467       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12468     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12469     int SSECC = translateX86FSETCC(
12470         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12471
12472     if (SSECC != 8) {
12473       if (Subtarget->hasAVX512()) {
12474         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12475                                   DAG.getConstant(SSECC, MVT::i8));
12476         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12477       }
12478       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12479                                 DAG.getConstant(SSECC, MVT::i8));
12480       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12481       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12482       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12483     }
12484   }
12485
12486   if (Cond.getOpcode() == ISD::SETCC) {
12487     SDValue NewCond = LowerSETCC(Cond, DAG);
12488     if (NewCond.getNode())
12489       Cond = NewCond;
12490   }
12491
12492   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12493   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12494   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12495   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12496   if (Cond.getOpcode() == X86ISD::SETCC &&
12497       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12498       isZero(Cond.getOperand(1).getOperand(1))) {
12499     SDValue Cmp = Cond.getOperand(1);
12500
12501     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12502
12503     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12504         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12505       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12506
12507       SDValue CmpOp0 = Cmp.getOperand(0);
12508       // Apply further optimizations for special cases
12509       // (select (x != 0), -1, 0) -> neg & sbb
12510       // (select (x == 0), 0, -1) -> neg & sbb
12511       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12512         if (YC->isNullValue() &&
12513             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12514           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12515           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12516                                     DAG.getConstant(0, CmpOp0.getValueType()),
12517                                     CmpOp0);
12518           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12519                                     DAG.getConstant(X86::COND_B, MVT::i8),
12520                                     SDValue(Neg.getNode(), 1));
12521           return Res;
12522         }
12523
12524       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12525                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12526       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12527
12528       SDValue Res =   // Res = 0 or -1.
12529         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12530                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12531
12532       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12533         Res = DAG.getNOT(DL, Res, Res.getValueType());
12534
12535       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12536       if (!N2C || !N2C->isNullValue())
12537         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12538       return Res;
12539     }
12540   }
12541
12542   // Look past (and (setcc_carry (cmp ...)), 1).
12543   if (Cond.getOpcode() == ISD::AND &&
12544       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12545     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12546     if (C && C->getAPIntValue() == 1)
12547       Cond = Cond.getOperand(0);
12548   }
12549
12550   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12551   // setting operand in place of the X86ISD::SETCC.
12552   unsigned CondOpcode = Cond.getOpcode();
12553   if (CondOpcode == X86ISD::SETCC ||
12554       CondOpcode == X86ISD::SETCC_CARRY) {
12555     CC = Cond.getOperand(0);
12556
12557     SDValue Cmp = Cond.getOperand(1);
12558     unsigned Opc = Cmp.getOpcode();
12559     MVT VT = Op.getSimpleValueType();
12560
12561     bool IllegalFPCMov = false;
12562     if (VT.isFloatingPoint() && !VT.isVector() &&
12563         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12564       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12565
12566     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12567         Opc == X86ISD::BT) { // FIXME
12568       Cond = Cmp;
12569       addTest = false;
12570     }
12571   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12572              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12573              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12574               Cond.getOperand(0).getValueType() != MVT::i8)) {
12575     SDValue LHS = Cond.getOperand(0);
12576     SDValue RHS = Cond.getOperand(1);
12577     unsigned X86Opcode;
12578     unsigned X86Cond;
12579     SDVTList VTs;
12580     switch (CondOpcode) {
12581     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12582     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12583     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12584     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12585     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12586     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12587     default: llvm_unreachable("unexpected overflowing operator");
12588     }
12589     if (CondOpcode == ISD::UMULO)
12590       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12591                           MVT::i32);
12592     else
12593       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12594
12595     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12596
12597     if (CondOpcode == ISD::UMULO)
12598       Cond = X86Op.getValue(2);
12599     else
12600       Cond = X86Op.getValue(1);
12601
12602     CC = DAG.getConstant(X86Cond, MVT::i8);
12603     addTest = false;
12604   }
12605
12606   if (addTest) {
12607     // Look pass the truncate if the high bits are known zero.
12608     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12609         Cond = Cond.getOperand(0);
12610
12611     // We know the result of AND is compared against zero. Try to match
12612     // it to BT.
12613     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12614       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12615       if (NewSetCC.getNode()) {
12616         CC = NewSetCC.getOperand(0);
12617         Cond = NewSetCC.getOperand(1);
12618         addTest = false;
12619       }
12620     }
12621   }
12622
12623   if (addTest) {
12624     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12625     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12626   }
12627
12628   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12629   // a <  b ?  0 : -1 -> RES = setcc_carry
12630   // a >= b ? -1 :  0 -> RES = setcc_carry
12631   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12632   if (Cond.getOpcode() == X86ISD::SUB) {
12633     Cond = ConvertCmpIfNecessary(Cond, DAG);
12634     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12635
12636     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12637         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12638       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12639                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12640       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12641         return DAG.getNOT(DL, Res, Res.getValueType());
12642       return Res;
12643     }
12644   }
12645
12646   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12647   // widen the cmov and push the truncate through. This avoids introducing a new
12648   // branch during isel and doesn't add any extensions.
12649   if (Op.getValueType() == MVT::i8 &&
12650       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12651     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12652     if (T1.getValueType() == T2.getValueType() &&
12653         // Blacklist CopyFromReg to avoid partial register stalls.
12654         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12655       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12656       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12657       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12658     }
12659   }
12660
12661   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12662   // condition is true.
12663   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12664   SDValue Ops[] = { Op2, Op1, CC, Cond };
12665   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12666 }
12667
12668 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12669   MVT VT = Op->getSimpleValueType(0);
12670   SDValue In = Op->getOperand(0);
12671   MVT InVT = In.getSimpleValueType();
12672   SDLoc dl(Op);
12673
12674   unsigned int NumElts = VT.getVectorNumElements();
12675   if (NumElts != 8 && NumElts != 16)
12676     return SDValue();
12677
12678   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12679     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12680
12681   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12682   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12683
12684   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12685   Constant *C = ConstantInt::get(*DAG.getContext(),
12686     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12687
12688   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12689   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12690   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12691                           MachinePointerInfo::getConstantPool(),
12692                           false, false, false, Alignment);
12693   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12694   if (VT.is512BitVector())
12695     return Brcst;
12696   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12697 }
12698
12699 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12700                                 SelectionDAG &DAG) {
12701   MVT VT = Op->getSimpleValueType(0);
12702   SDValue In = Op->getOperand(0);
12703   MVT InVT = In.getSimpleValueType();
12704   SDLoc dl(Op);
12705
12706   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12707     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12708
12709   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12710       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12711       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12712     return SDValue();
12713
12714   if (Subtarget->hasInt256())
12715     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12716
12717   // Optimize vectors in AVX mode
12718   // Sign extend  v8i16 to v8i32 and
12719   //              v4i32 to v4i64
12720   //
12721   // Divide input vector into two parts
12722   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12723   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12724   // concat the vectors to original VT
12725
12726   unsigned NumElems = InVT.getVectorNumElements();
12727   SDValue Undef = DAG.getUNDEF(InVT);
12728
12729   SmallVector<int,8> ShufMask1(NumElems, -1);
12730   for (unsigned i = 0; i != NumElems/2; ++i)
12731     ShufMask1[i] = i;
12732
12733   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12734
12735   SmallVector<int,8> ShufMask2(NumElems, -1);
12736   for (unsigned i = 0; i != NumElems/2; ++i)
12737     ShufMask2[i] = i + NumElems/2;
12738
12739   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12740
12741   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12742                                 VT.getVectorNumElements()/2);
12743
12744   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12745   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12746
12747   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12748 }
12749
12750 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12751 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12752 // from the AND / OR.
12753 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12754   Opc = Op.getOpcode();
12755   if (Opc != ISD::OR && Opc != ISD::AND)
12756     return false;
12757   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12758           Op.getOperand(0).hasOneUse() &&
12759           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12760           Op.getOperand(1).hasOneUse());
12761 }
12762
12763 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12764 // 1 and that the SETCC node has a single use.
12765 static bool isXor1OfSetCC(SDValue Op) {
12766   if (Op.getOpcode() != ISD::XOR)
12767     return false;
12768   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12769   if (N1C && N1C->getAPIntValue() == 1) {
12770     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12771       Op.getOperand(0).hasOneUse();
12772   }
12773   return false;
12774 }
12775
12776 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12777   bool addTest = true;
12778   SDValue Chain = Op.getOperand(0);
12779   SDValue Cond  = Op.getOperand(1);
12780   SDValue Dest  = Op.getOperand(2);
12781   SDLoc dl(Op);
12782   SDValue CC;
12783   bool Inverted = false;
12784
12785   if (Cond.getOpcode() == ISD::SETCC) {
12786     // Check for setcc([su]{add,sub,mul}o == 0).
12787     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12788         isa<ConstantSDNode>(Cond.getOperand(1)) &&
12789         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12790         Cond.getOperand(0).getResNo() == 1 &&
12791         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12792          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12793          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12794          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12795          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12796          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12797       Inverted = true;
12798       Cond = Cond.getOperand(0);
12799     } else {
12800       SDValue NewCond = LowerSETCC(Cond, DAG);
12801       if (NewCond.getNode())
12802         Cond = NewCond;
12803     }
12804   }
12805 #if 0
12806   // FIXME: LowerXALUO doesn't handle these!!
12807   else if (Cond.getOpcode() == X86ISD::ADD  ||
12808            Cond.getOpcode() == X86ISD::SUB  ||
12809            Cond.getOpcode() == X86ISD::SMUL ||
12810            Cond.getOpcode() == X86ISD::UMUL)
12811     Cond = LowerXALUO(Cond, DAG);
12812 #endif
12813
12814   // Look pass (and (setcc_carry (cmp ...)), 1).
12815   if (Cond.getOpcode() == ISD::AND &&
12816       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12817     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12818     if (C && C->getAPIntValue() == 1)
12819       Cond = Cond.getOperand(0);
12820   }
12821
12822   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12823   // setting operand in place of the X86ISD::SETCC.
12824   unsigned CondOpcode = Cond.getOpcode();
12825   if (CondOpcode == X86ISD::SETCC ||
12826       CondOpcode == X86ISD::SETCC_CARRY) {
12827     CC = Cond.getOperand(0);
12828
12829     SDValue Cmp = Cond.getOperand(1);
12830     unsigned Opc = Cmp.getOpcode();
12831     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12832     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12833       Cond = Cmp;
12834       addTest = false;
12835     } else {
12836       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12837       default: break;
12838       case X86::COND_O:
12839       case X86::COND_B:
12840         // These can only come from an arithmetic instruction with overflow,
12841         // e.g. SADDO, UADDO.
12842         Cond = Cond.getNode()->getOperand(1);
12843         addTest = false;
12844         break;
12845       }
12846     }
12847   }
12848   CondOpcode = Cond.getOpcode();
12849   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12850       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12851       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12852        Cond.getOperand(0).getValueType() != MVT::i8)) {
12853     SDValue LHS = Cond.getOperand(0);
12854     SDValue RHS = Cond.getOperand(1);
12855     unsigned X86Opcode;
12856     unsigned X86Cond;
12857     SDVTList VTs;
12858     // Keep this in sync with LowerXALUO, otherwise we might create redundant
12859     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12860     // X86ISD::INC).
12861     switch (CondOpcode) {
12862     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12863     case ISD::SADDO:
12864       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12865         if (C->isOne()) {
12866           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12867           break;
12868         }
12869       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12870     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12871     case ISD::SSUBO:
12872       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12873         if (C->isOne()) {
12874           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12875           break;
12876         }
12877       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12878     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12879     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12880     default: llvm_unreachable("unexpected overflowing operator");
12881     }
12882     if (Inverted)
12883       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12884     if (CondOpcode == ISD::UMULO)
12885       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12886                           MVT::i32);
12887     else
12888       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12889
12890     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12891
12892     if (CondOpcode == ISD::UMULO)
12893       Cond = X86Op.getValue(2);
12894     else
12895       Cond = X86Op.getValue(1);
12896
12897     CC = DAG.getConstant(X86Cond, MVT::i8);
12898     addTest = false;
12899   } else {
12900     unsigned CondOpc;
12901     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12902       SDValue Cmp = Cond.getOperand(0).getOperand(1);
12903       if (CondOpc == ISD::OR) {
12904         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12905         // two branches instead of an explicit OR instruction with a
12906         // separate test.
12907         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12908             isX86LogicalCmp(Cmp)) {
12909           CC = Cond.getOperand(0).getOperand(0);
12910           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12911                               Chain, Dest, CC, Cmp);
12912           CC = Cond.getOperand(1).getOperand(0);
12913           Cond = Cmp;
12914           addTest = false;
12915         }
12916       } else { // ISD::AND
12917         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12918         // two branches instead of an explicit AND instruction with a
12919         // separate test. However, we only do this if this block doesn't
12920         // have a fall-through edge, because this requires an explicit
12921         // jmp when the condition is false.
12922         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12923             isX86LogicalCmp(Cmp) &&
12924             Op.getNode()->hasOneUse()) {
12925           X86::CondCode CCode =
12926             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12927           CCode = X86::GetOppositeBranchCondition(CCode);
12928           CC = DAG.getConstant(CCode, MVT::i8);
12929           SDNode *User = *Op.getNode()->use_begin();
12930           // Look for an unconditional branch following this conditional branch.
12931           // We need this because we need to reverse the successors in order
12932           // to implement FCMP_OEQ.
12933           if (User->getOpcode() == ISD::BR) {
12934             SDValue FalseBB = User->getOperand(1);
12935             SDNode *NewBR =
12936               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12937             assert(NewBR == User);
12938             (void)NewBR;
12939             Dest = FalseBB;
12940
12941             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12942                                 Chain, Dest, CC, Cmp);
12943             X86::CondCode CCode =
12944               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
12945             CCode = X86::GetOppositeBranchCondition(CCode);
12946             CC = DAG.getConstant(CCode, MVT::i8);
12947             Cond = Cmp;
12948             addTest = false;
12949           }
12950         }
12951       }
12952     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
12953       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
12954       // It should be transformed during dag combiner except when the condition
12955       // is set by a arithmetics with overflow node.
12956       X86::CondCode CCode =
12957         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12958       CCode = X86::GetOppositeBranchCondition(CCode);
12959       CC = DAG.getConstant(CCode, MVT::i8);
12960       Cond = Cond.getOperand(0).getOperand(1);
12961       addTest = false;
12962     } else if (Cond.getOpcode() == ISD::SETCC &&
12963                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
12964       // For FCMP_OEQ, we can emit
12965       // two branches instead of an explicit AND instruction with a
12966       // separate test. However, we only do this if this block doesn't
12967       // have a fall-through edge, because this requires an explicit
12968       // jmp when the condition is false.
12969       if (Op.getNode()->hasOneUse()) {
12970         SDNode *User = *Op.getNode()->use_begin();
12971         // Look for an unconditional branch following this conditional branch.
12972         // We need this because we need to reverse the successors in order
12973         // to implement FCMP_OEQ.
12974         if (User->getOpcode() == ISD::BR) {
12975           SDValue FalseBB = User->getOperand(1);
12976           SDNode *NewBR =
12977             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12978           assert(NewBR == User);
12979           (void)NewBR;
12980           Dest = FalseBB;
12981
12982           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12983                                     Cond.getOperand(0), Cond.getOperand(1));
12984           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12985           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12986           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12987                               Chain, Dest, CC, Cmp);
12988           CC = DAG.getConstant(X86::COND_P, MVT::i8);
12989           Cond = Cmp;
12990           addTest = false;
12991         }
12992       }
12993     } else if (Cond.getOpcode() == ISD::SETCC &&
12994                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
12995       // For FCMP_UNE, we can emit
12996       // two branches instead of an explicit AND instruction with a
12997       // separate test. However, we only do this if this block doesn't
12998       // have a fall-through edge, because this requires an explicit
12999       // jmp when the condition is false.
13000       if (Op.getNode()->hasOneUse()) {
13001         SDNode *User = *Op.getNode()->use_begin();
13002         // Look for an unconditional branch following this conditional branch.
13003         // We need this because we need to reverse the successors in order
13004         // to implement FCMP_UNE.
13005         if (User->getOpcode() == ISD::BR) {
13006           SDValue FalseBB = User->getOperand(1);
13007           SDNode *NewBR =
13008             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13009           assert(NewBR == User);
13010           (void)NewBR;
13011
13012           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13013                                     Cond.getOperand(0), Cond.getOperand(1));
13014           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13015           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13016           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13017                               Chain, Dest, CC, Cmp);
13018           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13019           Cond = Cmp;
13020           addTest = false;
13021           Dest = FalseBB;
13022         }
13023       }
13024     }
13025   }
13026
13027   if (addTest) {
13028     // Look pass the truncate if the high bits are known zero.
13029     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13030         Cond = Cond.getOperand(0);
13031
13032     // We know the result of AND is compared against zero. Try to match
13033     // it to BT.
13034     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13035       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13036       if (NewSetCC.getNode()) {
13037         CC = NewSetCC.getOperand(0);
13038         Cond = NewSetCC.getOperand(1);
13039         addTest = false;
13040       }
13041     }
13042   }
13043
13044   if (addTest) {
13045     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13046     CC = DAG.getConstant(X86Cond, MVT::i8);
13047     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13048   }
13049   Cond = ConvertCmpIfNecessary(Cond, DAG);
13050   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13051                      Chain, Dest, CC, Cond);
13052 }
13053
13054 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13055 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13056 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13057 // that the guard pages used by the OS virtual memory manager are allocated in
13058 // correct sequence.
13059 SDValue
13060 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13061                                            SelectionDAG &DAG) const {
13062   MachineFunction &MF = DAG.getMachineFunction();
13063   bool SplitStack = MF.shouldSplitStack();
13064   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13065                SplitStack;
13066   SDLoc dl(Op);
13067
13068   if (!Lower) {
13069     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13070     SDNode* Node = Op.getNode();
13071
13072     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13073     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13074         " not tell us which reg is the stack pointer!");
13075     EVT VT = Node->getValueType(0);
13076     SDValue Tmp1 = SDValue(Node, 0);
13077     SDValue Tmp2 = SDValue(Node, 1);
13078     SDValue Tmp3 = Node->getOperand(2);
13079     SDValue Chain = Tmp1.getOperand(0);
13080
13081     // Chain the dynamic stack allocation so that it doesn't modify the stack
13082     // pointer when other instructions are using the stack.
13083     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13084         SDLoc(Node));
13085
13086     SDValue Size = Tmp2.getOperand(1);
13087     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13088     Chain = SP.getValue(1);
13089     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13090     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13091     unsigned StackAlign = TFI.getStackAlignment();
13092     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13093     if (Align > StackAlign)
13094       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13095           DAG.getConstant(-(uint64_t)Align, VT));
13096     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13097
13098     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13099         DAG.getIntPtrConstant(0, true), SDValue(),
13100         SDLoc(Node));
13101
13102     SDValue Ops[2] = { Tmp1, Tmp2 };
13103     return DAG.getMergeValues(Ops, dl);
13104   }
13105
13106   // Get the inputs.
13107   SDValue Chain = Op.getOperand(0);
13108   SDValue Size  = Op.getOperand(1);
13109   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13110   EVT VT = Op.getNode()->getValueType(0);
13111
13112   bool Is64Bit = Subtarget->is64Bit();
13113   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13114
13115   if (SplitStack) {
13116     MachineRegisterInfo &MRI = MF.getRegInfo();
13117
13118     if (Is64Bit) {
13119       // The 64 bit implementation of segmented stacks needs to clobber both r10
13120       // r11. This makes it impossible to use it along with nested parameters.
13121       const Function *F = MF.getFunction();
13122
13123       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13124            I != E; ++I)
13125         if (I->hasNestAttr())
13126           report_fatal_error("Cannot use segmented stacks with functions that "
13127                              "have nested arguments.");
13128     }
13129
13130     const TargetRegisterClass *AddrRegClass =
13131       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13132     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13133     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13134     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13135                                 DAG.getRegister(Vreg, SPTy));
13136     SDValue Ops1[2] = { Value, Chain };
13137     return DAG.getMergeValues(Ops1, dl);
13138   } else {
13139     SDValue Flag;
13140     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13141
13142     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13143     Flag = Chain.getValue(1);
13144     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13145
13146     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13147
13148     const X86RegisterInfo *RegInfo =
13149       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13150     unsigned SPReg = RegInfo->getStackRegister();
13151     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13152     Chain = SP.getValue(1);
13153
13154     if (Align) {
13155       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13156                        DAG.getConstant(-(uint64_t)Align, VT));
13157       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13158     }
13159
13160     SDValue Ops1[2] = { SP, Chain };
13161     return DAG.getMergeValues(Ops1, dl);
13162   }
13163 }
13164
13165 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13166   MachineFunction &MF = DAG.getMachineFunction();
13167   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13168
13169   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13170   SDLoc DL(Op);
13171
13172   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13173     // vastart just stores the address of the VarArgsFrameIndex slot into the
13174     // memory location argument.
13175     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13176                                    getPointerTy());
13177     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13178                         MachinePointerInfo(SV), false, false, 0);
13179   }
13180
13181   // __va_list_tag:
13182   //   gp_offset         (0 - 6 * 8)
13183   //   fp_offset         (48 - 48 + 8 * 16)
13184   //   overflow_arg_area (point to parameters coming in memory).
13185   //   reg_save_area
13186   SmallVector<SDValue, 8> MemOps;
13187   SDValue FIN = Op.getOperand(1);
13188   // Store gp_offset
13189   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13190                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13191                                                MVT::i32),
13192                                FIN, MachinePointerInfo(SV), false, false, 0);
13193   MemOps.push_back(Store);
13194
13195   // Store fp_offset
13196   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13197                     FIN, DAG.getIntPtrConstant(4));
13198   Store = DAG.getStore(Op.getOperand(0), DL,
13199                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13200                                        MVT::i32),
13201                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13202   MemOps.push_back(Store);
13203
13204   // Store ptr to overflow_arg_area
13205   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13206                     FIN, DAG.getIntPtrConstant(4));
13207   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13208                                     getPointerTy());
13209   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13210                        MachinePointerInfo(SV, 8),
13211                        false, false, 0);
13212   MemOps.push_back(Store);
13213
13214   // Store ptr to reg_save_area.
13215   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13216                     FIN, DAG.getIntPtrConstant(8));
13217   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13218                                     getPointerTy());
13219   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13220                        MachinePointerInfo(SV, 16), false, false, 0);
13221   MemOps.push_back(Store);
13222   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13223 }
13224
13225 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13226   assert(Subtarget->is64Bit() &&
13227          "LowerVAARG only handles 64-bit va_arg!");
13228   assert((Subtarget->isTargetLinux() ||
13229           Subtarget->isTargetDarwin()) &&
13230           "Unhandled target in LowerVAARG");
13231   assert(Op.getNode()->getNumOperands() == 4);
13232   SDValue Chain = Op.getOperand(0);
13233   SDValue SrcPtr = Op.getOperand(1);
13234   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13235   unsigned Align = Op.getConstantOperandVal(3);
13236   SDLoc dl(Op);
13237
13238   EVT ArgVT = Op.getNode()->getValueType(0);
13239   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13240   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13241   uint8_t ArgMode;
13242
13243   // Decide which area this value should be read from.
13244   // TODO: Implement the AMD64 ABI in its entirety. This simple
13245   // selection mechanism works only for the basic types.
13246   if (ArgVT == MVT::f80) {
13247     llvm_unreachable("va_arg for f80 not yet implemented");
13248   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13249     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13250   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13251     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13252   } else {
13253     llvm_unreachable("Unhandled argument type in LowerVAARG");
13254   }
13255
13256   if (ArgMode == 2) {
13257     // Sanity Check: Make sure using fp_offset makes sense.
13258     assert(!DAG.getTarget().Options.UseSoftFloat &&
13259            !(DAG.getMachineFunction()
13260                 .getFunction()->getAttributes()
13261                 .hasAttribute(AttributeSet::FunctionIndex,
13262                               Attribute::NoImplicitFloat)) &&
13263            Subtarget->hasSSE1());
13264   }
13265
13266   // Insert VAARG_64 node into the DAG
13267   // VAARG_64 returns two values: Variable Argument Address, Chain
13268   SmallVector<SDValue, 11> InstOps;
13269   InstOps.push_back(Chain);
13270   InstOps.push_back(SrcPtr);
13271   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13272   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13273   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13274   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13275   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13276                                           VTs, InstOps, MVT::i64,
13277                                           MachinePointerInfo(SV),
13278                                           /*Align=*/0,
13279                                           /*Volatile=*/false,
13280                                           /*ReadMem=*/true,
13281                                           /*WriteMem=*/true);
13282   Chain = VAARG.getValue(1);
13283
13284   // Load the next argument and return it
13285   return DAG.getLoad(ArgVT, dl,
13286                      Chain,
13287                      VAARG,
13288                      MachinePointerInfo(),
13289                      false, false, false, 0);
13290 }
13291
13292 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13293                            SelectionDAG &DAG) {
13294   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13295   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13296   SDValue Chain = Op.getOperand(0);
13297   SDValue DstPtr = Op.getOperand(1);
13298   SDValue SrcPtr = Op.getOperand(2);
13299   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13300   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13301   SDLoc DL(Op);
13302
13303   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13304                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13305                        false,
13306                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13307 }
13308
13309 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13310 // amount is a constant. Takes immediate version of shift as input.
13311 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13312                                           SDValue SrcOp, uint64_t ShiftAmt,
13313                                           SelectionDAG &DAG) {
13314   MVT ElementType = VT.getVectorElementType();
13315
13316   // Fold this packed shift into its first operand if ShiftAmt is 0.
13317   if (ShiftAmt == 0)
13318     return SrcOp;
13319
13320   // Check for ShiftAmt >= element width
13321   if (ShiftAmt >= ElementType.getSizeInBits()) {
13322     if (Opc == X86ISD::VSRAI)
13323       ShiftAmt = ElementType.getSizeInBits() - 1;
13324     else
13325       return DAG.getConstant(0, VT);
13326   }
13327
13328   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13329          && "Unknown target vector shift-by-constant node");
13330
13331   // Fold this packed vector shift into a build vector if SrcOp is a
13332   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13333   if (VT == SrcOp.getSimpleValueType() &&
13334       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13335     SmallVector<SDValue, 8> Elts;
13336     unsigned NumElts = SrcOp->getNumOperands();
13337     ConstantSDNode *ND;
13338
13339     switch(Opc) {
13340     default: llvm_unreachable(nullptr);
13341     case X86ISD::VSHLI:
13342       for (unsigned i=0; i!=NumElts; ++i) {
13343         SDValue CurrentOp = SrcOp->getOperand(i);
13344         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13345           Elts.push_back(CurrentOp);
13346           continue;
13347         }
13348         ND = cast<ConstantSDNode>(CurrentOp);
13349         const APInt &C = ND->getAPIntValue();
13350         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13351       }
13352       break;
13353     case X86ISD::VSRLI:
13354       for (unsigned i=0; i!=NumElts; ++i) {
13355         SDValue CurrentOp = SrcOp->getOperand(i);
13356         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13357           Elts.push_back(CurrentOp);
13358           continue;
13359         }
13360         ND = cast<ConstantSDNode>(CurrentOp);
13361         const APInt &C = ND->getAPIntValue();
13362         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13363       }
13364       break;
13365     case X86ISD::VSRAI:
13366       for (unsigned i=0; i!=NumElts; ++i) {
13367         SDValue CurrentOp = SrcOp->getOperand(i);
13368         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13369           Elts.push_back(CurrentOp);
13370           continue;
13371         }
13372         ND = cast<ConstantSDNode>(CurrentOp);
13373         const APInt &C = ND->getAPIntValue();
13374         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13375       }
13376       break;
13377     }
13378
13379     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13380   }
13381
13382   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13383 }
13384
13385 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13386 // may or may not be a constant. Takes immediate version of shift as input.
13387 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13388                                    SDValue SrcOp, SDValue ShAmt,
13389                                    SelectionDAG &DAG) {
13390   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13391
13392   // Catch shift-by-constant.
13393   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13394     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13395                                       CShAmt->getZExtValue(), DAG);
13396
13397   // Change opcode to non-immediate version
13398   switch (Opc) {
13399     default: llvm_unreachable("Unknown target vector shift node");
13400     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13401     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13402     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13403   }
13404
13405   // Need to build a vector containing shift amount
13406   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13407   SDValue ShOps[4];
13408   ShOps[0] = ShAmt;
13409   ShOps[1] = DAG.getConstant(0, MVT::i32);
13410   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13411   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13412
13413   // The return type has to be a 128-bit type with the same element
13414   // type as the input type.
13415   MVT EltVT = VT.getVectorElementType();
13416   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13417
13418   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13419   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13420 }
13421
13422 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13423   SDLoc dl(Op);
13424   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13425   switch (IntNo) {
13426   default: return SDValue();    // Don't custom lower most intrinsics.
13427   // Comparison intrinsics.
13428   case Intrinsic::x86_sse_comieq_ss:
13429   case Intrinsic::x86_sse_comilt_ss:
13430   case Intrinsic::x86_sse_comile_ss:
13431   case Intrinsic::x86_sse_comigt_ss:
13432   case Intrinsic::x86_sse_comige_ss:
13433   case Intrinsic::x86_sse_comineq_ss:
13434   case Intrinsic::x86_sse_ucomieq_ss:
13435   case Intrinsic::x86_sse_ucomilt_ss:
13436   case Intrinsic::x86_sse_ucomile_ss:
13437   case Intrinsic::x86_sse_ucomigt_ss:
13438   case Intrinsic::x86_sse_ucomige_ss:
13439   case Intrinsic::x86_sse_ucomineq_ss:
13440   case Intrinsic::x86_sse2_comieq_sd:
13441   case Intrinsic::x86_sse2_comilt_sd:
13442   case Intrinsic::x86_sse2_comile_sd:
13443   case Intrinsic::x86_sse2_comigt_sd:
13444   case Intrinsic::x86_sse2_comige_sd:
13445   case Intrinsic::x86_sse2_comineq_sd:
13446   case Intrinsic::x86_sse2_ucomieq_sd:
13447   case Intrinsic::x86_sse2_ucomilt_sd:
13448   case Intrinsic::x86_sse2_ucomile_sd:
13449   case Intrinsic::x86_sse2_ucomigt_sd:
13450   case Intrinsic::x86_sse2_ucomige_sd:
13451   case Intrinsic::x86_sse2_ucomineq_sd: {
13452     unsigned Opc;
13453     ISD::CondCode CC;
13454     switch (IntNo) {
13455     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13456     case Intrinsic::x86_sse_comieq_ss:
13457     case Intrinsic::x86_sse2_comieq_sd:
13458       Opc = X86ISD::COMI;
13459       CC = ISD::SETEQ;
13460       break;
13461     case Intrinsic::x86_sse_comilt_ss:
13462     case Intrinsic::x86_sse2_comilt_sd:
13463       Opc = X86ISD::COMI;
13464       CC = ISD::SETLT;
13465       break;
13466     case Intrinsic::x86_sse_comile_ss:
13467     case Intrinsic::x86_sse2_comile_sd:
13468       Opc = X86ISD::COMI;
13469       CC = ISD::SETLE;
13470       break;
13471     case Intrinsic::x86_sse_comigt_ss:
13472     case Intrinsic::x86_sse2_comigt_sd:
13473       Opc = X86ISD::COMI;
13474       CC = ISD::SETGT;
13475       break;
13476     case Intrinsic::x86_sse_comige_ss:
13477     case Intrinsic::x86_sse2_comige_sd:
13478       Opc = X86ISD::COMI;
13479       CC = ISD::SETGE;
13480       break;
13481     case Intrinsic::x86_sse_comineq_ss:
13482     case Intrinsic::x86_sse2_comineq_sd:
13483       Opc = X86ISD::COMI;
13484       CC = ISD::SETNE;
13485       break;
13486     case Intrinsic::x86_sse_ucomieq_ss:
13487     case Intrinsic::x86_sse2_ucomieq_sd:
13488       Opc = X86ISD::UCOMI;
13489       CC = ISD::SETEQ;
13490       break;
13491     case Intrinsic::x86_sse_ucomilt_ss:
13492     case Intrinsic::x86_sse2_ucomilt_sd:
13493       Opc = X86ISD::UCOMI;
13494       CC = ISD::SETLT;
13495       break;
13496     case Intrinsic::x86_sse_ucomile_ss:
13497     case Intrinsic::x86_sse2_ucomile_sd:
13498       Opc = X86ISD::UCOMI;
13499       CC = ISD::SETLE;
13500       break;
13501     case Intrinsic::x86_sse_ucomigt_ss:
13502     case Intrinsic::x86_sse2_ucomigt_sd:
13503       Opc = X86ISD::UCOMI;
13504       CC = ISD::SETGT;
13505       break;
13506     case Intrinsic::x86_sse_ucomige_ss:
13507     case Intrinsic::x86_sse2_ucomige_sd:
13508       Opc = X86ISD::UCOMI;
13509       CC = ISD::SETGE;
13510       break;
13511     case Intrinsic::x86_sse_ucomineq_ss:
13512     case Intrinsic::x86_sse2_ucomineq_sd:
13513       Opc = X86ISD::UCOMI;
13514       CC = ISD::SETNE;
13515       break;
13516     }
13517
13518     SDValue LHS = Op.getOperand(1);
13519     SDValue RHS = Op.getOperand(2);
13520     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13521     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13522     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13523     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13524                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13525     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13526   }
13527
13528   // Arithmetic intrinsics.
13529   case Intrinsic::x86_sse2_pmulu_dq:
13530   case Intrinsic::x86_avx2_pmulu_dq:
13531     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13532                        Op.getOperand(1), Op.getOperand(2));
13533
13534   case Intrinsic::x86_sse41_pmuldq:
13535   case Intrinsic::x86_avx2_pmul_dq:
13536     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13537                        Op.getOperand(1), Op.getOperand(2));
13538
13539   case Intrinsic::x86_sse2_pmulhu_w:
13540   case Intrinsic::x86_avx2_pmulhu_w:
13541     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13542                        Op.getOperand(1), Op.getOperand(2));
13543
13544   case Intrinsic::x86_sse2_pmulh_w:
13545   case Intrinsic::x86_avx2_pmulh_w:
13546     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13547                        Op.getOperand(1), Op.getOperand(2));
13548
13549   // SSE2/AVX2 sub with unsigned saturation intrinsics
13550   case Intrinsic::x86_sse2_psubus_b:
13551   case Intrinsic::x86_sse2_psubus_w:
13552   case Intrinsic::x86_avx2_psubus_b:
13553   case Intrinsic::x86_avx2_psubus_w:
13554     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13555                        Op.getOperand(1), Op.getOperand(2));
13556
13557   // SSE3/AVX horizontal add/sub intrinsics
13558   case Intrinsic::x86_sse3_hadd_ps:
13559   case Intrinsic::x86_sse3_hadd_pd:
13560   case Intrinsic::x86_avx_hadd_ps_256:
13561   case Intrinsic::x86_avx_hadd_pd_256:
13562   case Intrinsic::x86_sse3_hsub_ps:
13563   case Intrinsic::x86_sse3_hsub_pd:
13564   case Intrinsic::x86_avx_hsub_ps_256:
13565   case Intrinsic::x86_avx_hsub_pd_256:
13566   case Intrinsic::x86_ssse3_phadd_w_128:
13567   case Intrinsic::x86_ssse3_phadd_d_128:
13568   case Intrinsic::x86_avx2_phadd_w:
13569   case Intrinsic::x86_avx2_phadd_d:
13570   case Intrinsic::x86_ssse3_phsub_w_128:
13571   case Intrinsic::x86_ssse3_phsub_d_128:
13572   case Intrinsic::x86_avx2_phsub_w:
13573   case Intrinsic::x86_avx2_phsub_d: {
13574     unsigned Opcode;
13575     switch (IntNo) {
13576     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13577     case Intrinsic::x86_sse3_hadd_ps:
13578     case Intrinsic::x86_sse3_hadd_pd:
13579     case Intrinsic::x86_avx_hadd_ps_256:
13580     case Intrinsic::x86_avx_hadd_pd_256:
13581       Opcode = X86ISD::FHADD;
13582       break;
13583     case Intrinsic::x86_sse3_hsub_ps:
13584     case Intrinsic::x86_sse3_hsub_pd:
13585     case Intrinsic::x86_avx_hsub_ps_256:
13586     case Intrinsic::x86_avx_hsub_pd_256:
13587       Opcode = X86ISD::FHSUB;
13588       break;
13589     case Intrinsic::x86_ssse3_phadd_w_128:
13590     case Intrinsic::x86_ssse3_phadd_d_128:
13591     case Intrinsic::x86_avx2_phadd_w:
13592     case Intrinsic::x86_avx2_phadd_d:
13593       Opcode = X86ISD::HADD;
13594       break;
13595     case Intrinsic::x86_ssse3_phsub_w_128:
13596     case Intrinsic::x86_ssse3_phsub_d_128:
13597     case Intrinsic::x86_avx2_phsub_w:
13598     case Intrinsic::x86_avx2_phsub_d:
13599       Opcode = X86ISD::HSUB;
13600       break;
13601     }
13602     return DAG.getNode(Opcode, dl, Op.getValueType(),
13603                        Op.getOperand(1), Op.getOperand(2));
13604   }
13605
13606   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13607   case Intrinsic::x86_sse2_pmaxu_b:
13608   case Intrinsic::x86_sse41_pmaxuw:
13609   case Intrinsic::x86_sse41_pmaxud:
13610   case Intrinsic::x86_avx2_pmaxu_b:
13611   case Intrinsic::x86_avx2_pmaxu_w:
13612   case Intrinsic::x86_avx2_pmaxu_d:
13613   case Intrinsic::x86_sse2_pminu_b:
13614   case Intrinsic::x86_sse41_pminuw:
13615   case Intrinsic::x86_sse41_pminud:
13616   case Intrinsic::x86_avx2_pminu_b:
13617   case Intrinsic::x86_avx2_pminu_w:
13618   case Intrinsic::x86_avx2_pminu_d:
13619   case Intrinsic::x86_sse41_pmaxsb:
13620   case Intrinsic::x86_sse2_pmaxs_w:
13621   case Intrinsic::x86_sse41_pmaxsd:
13622   case Intrinsic::x86_avx2_pmaxs_b:
13623   case Intrinsic::x86_avx2_pmaxs_w:
13624   case Intrinsic::x86_avx2_pmaxs_d:
13625   case Intrinsic::x86_sse41_pminsb:
13626   case Intrinsic::x86_sse2_pmins_w:
13627   case Intrinsic::x86_sse41_pminsd:
13628   case Intrinsic::x86_avx2_pmins_b:
13629   case Intrinsic::x86_avx2_pmins_w:
13630   case Intrinsic::x86_avx2_pmins_d: {
13631     unsigned Opcode;
13632     switch (IntNo) {
13633     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13634     case Intrinsic::x86_sse2_pmaxu_b:
13635     case Intrinsic::x86_sse41_pmaxuw:
13636     case Intrinsic::x86_sse41_pmaxud:
13637     case Intrinsic::x86_avx2_pmaxu_b:
13638     case Intrinsic::x86_avx2_pmaxu_w:
13639     case Intrinsic::x86_avx2_pmaxu_d:
13640       Opcode = X86ISD::UMAX;
13641       break;
13642     case Intrinsic::x86_sse2_pminu_b:
13643     case Intrinsic::x86_sse41_pminuw:
13644     case Intrinsic::x86_sse41_pminud:
13645     case Intrinsic::x86_avx2_pminu_b:
13646     case Intrinsic::x86_avx2_pminu_w:
13647     case Intrinsic::x86_avx2_pminu_d:
13648       Opcode = X86ISD::UMIN;
13649       break;
13650     case Intrinsic::x86_sse41_pmaxsb:
13651     case Intrinsic::x86_sse2_pmaxs_w:
13652     case Intrinsic::x86_sse41_pmaxsd:
13653     case Intrinsic::x86_avx2_pmaxs_b:
13654     case Intrinsic::x86_avx2_pmaxs_w:
13655     case Intrinsic::x86_avx2_pmaxs_d:
13656       Opcode = X86ISD::SMAX;
13657       break;
13658     case Intrinsic::x86_sse41_pminsb:
13659     case Intrinsic::x86_sse2_pmins_w:
13660     case Intrinsic::x86_sse41_pminsd:
13661     case Intrinsic::x86_avx2_pmins_b:
13662     case Intrinsic::x86_avx2_pmins_w:
13663     case Intrinsic::x86_avx2_pmins_d:
13664       Opcode = X86ISD::SMIN;
13665       break;
13666     }
13667     return DAG.getNode(Opcode, dl, Op.getValueType(),
13668                        Op.getOperand(1), Op.getOperand(2));
13669   }
13670
13671   // SSE/SSE2/AVX floating point max/min intrinsics.
13672   case Intrinsic::x86_sse_max_ps:
13673   case Intrinsic::x86_sse2_max_pd:
13674   case Intrinsic::x86_avx_max_ps_256:
13675   case Intrinsic::x86_avx_max_pd_256:
13676   case Intrinsic::x86_sse_min_ps:
13677   case Intrinsic::x86_sse2_min_pd:
13678   case Intrinsic::x86_avx_min_ps_256:
13679   case Intrinsic::x86_avx_min_pd_256: {
13680     unsigned Opcode;
13681     switch (IntNo) {
13682     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13683     case Intrinsic::x86_sse_max_ps:
13684     case Intrinsic::x86_sse2_max_pd:
13685     case Intrinsic::x86_avx_max_ps_256:
13686     case Intrinsic::x86_avx_max_pd_256:
13687       Opcode = X86ISD::FMAX;
13688       break;
13689     case Intrinsic::x86_sse_min_ps:
13690     case Intrinsic::x86_sse2_min_pd:
13691     case Intrinsic::x86_avx_min_ps_256:
13692     case Intrinsic::x86_avx_min_pd_256:
13693       Opcode = X86ISD::FMIN;
13694       break;
13695     }
13696     return DAG.getNode(Opcode, dl, Op.getValueType(),
13697                        Op.getOperand(1), Op.getOperand(2));
13698   }
13699
13700   // AVX2 variable shift intrinsics
13701   case Intrinsic::x86_avx2_psllv_d:
13702   case Intrinsic::x86_avx2_psllv_q:
13703   case Intrinsic::x86_avx2_psllv_d_256:
13704   case Intrinsic::x86_avx2_psllv_q_256:
13705   case Intrinsic::x86_avx2_psrlv_d:
13706   case Intrinsic::x86_avx2_psrlv_q:
13707   case Intrinsic::x86_avx2_psrlv_d_256:
13708   case Intrinsic::x86_avx2_psrlv_q_256:
13709   case Intrinsic::x86_avx2_psrav_d:
13710   case Intrinsic::x86_avx2_psrav_d_256: {
13711     unsigned Opcode;
13712     switch (IntNo) {
13713     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13714     case Intrinsic::x86_avx2_psllv_d:
13715     case Intrinsic::x86_avx2_psllv_q:
13716     case Intrinsic::x86_avx2_psllv_d_256:
13717     case Intrinsic::x86_avx2_psllv_q_256:
13718       Opcode = ISD::SHL;
13719       break;
13720     case Intrinsic::x86_avx2_psrlv_d:
13721     case Intrinsic::x86_avx2_psrlv_q:
13722     case Intrinsic::x86_avx2_psrlv_d_256:
13723     case Intrinsic::x86_avx2_psrlv_q_256:
13724       Opcode = ISD::SRL;
13725       break;
13726     case Intrinsic::x86_avx2_psrav_d:
13727     case Intrinsic::x86_avx2_psrav_d_256:
13728       Opcode = ISD::SRA;
13729       break;
13730     }
13731     return DAG.getNode(Opcode, dl, Op.getValueType(),
13732                        Op.getOperand(1), Op.getOperand(2));
13733   }
13734
13735   case Intrinsic::x86_sse2_packssdw_128:
13736   case Intrinsic::x86_sse2_packsswb_128:
13737   case Intrinsic::x86_avx2_packssdw:
13738   case Intrinsic::x86_avx2_packsswb:
13739     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13740                        Op.getOperand(1), Op.getOperand(2));
13741
13742   case Intrinsic::x86_sse2_packuswb_128:
13743   case Intrinsic::x86_sse41_packusdw:
13744   case Intrinsic::x86_avx2_packuswb:
13745   case Intrinsic::x86_avx2_packusdw:
13746     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13747                        Op.getOperand(1), Op.getOperand(2));
13748
13749   case Intrinsic::x86_ssse3_pshuf_b_128:
13750   case Intrinsic::x86_avx2_pshuf_b:
13751     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13752                        Op.getOperand(1), Op.getOperand(2));
13753
13754   case Intrinsic::x86_sse2_pshuf_d:
13755     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13756                        Op.getOperand(1), Op.getOperand(2));
13757
13758   case Intrinsic::x86_sse2_pshufl_w:
13759     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13760                        Op.getOperand(1), Op.getOperand(2));
13761
13762   case Intrinsic::x86_sse2_pshufh_w:
13763     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13764                        Op.getOperand(1), Op.getOperand(2));
13765
13766   case Intrinsic::x86_ssse3_psign_b_128:
13767   case Intrinsic::x86_ssse3_psign_w_128:
13768   case Intrinsic::x86_ssse3_psign_d_128:
13769   case Intrinsic::x86_avx2_psign_b:
13770   case Intrinsic::x86_avx2_psign_w:
13771   case Intrinsic::x86_avx2_psign_d:
13772     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13773                        Op.getOperand(1), Op.getOperand(2));
13774
13775   case Intrinsic::x86_sse41_insertps:
13776     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13777                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13778
13779   case Intrinsic::x86_avx_vperm2f128_ps_256:
13780   case Intrinsic::x86_avx_vperm2f128_pd_256:
13781   case Intrinsic::x86_avx_vperm2f128_si_256:
13782   case Intrinsic::x86_avx2_vperm2i128:
13783     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13784                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13785
13786   case Intrinsic::x86_avx2_permd:
13787   case Intrinsic::x86_avx2_permps:
13788     // Operands intentionally swapped. Mask is last operand to intrinsic,
13789     // but second operand for node/instruction.
13790     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13791                        Op.getOperand(2), Op.getOperand(1));
13792
13793   case Intrinsic::x86_sse_sqrt_ps:
13794   case Intrinsic::x86_sse2_sqrt_pd:
13795   case Intrinsic::x86_avx_sqrt_ps_256:
13796   case Intrinsic::x86_avx_sqrt_pd_256:
13797     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13798
13799   // ptest and testp intrinsics. The intrinsic these come from are designed to
13800   // return an integer value, not just an instruction so lower it to the ptest
13801   // or testp pattern and a setcc for the result.
13802   case Intrinsic::x86_sse41_ptestz:
13803   case Intrinsic::x86_sse41_ptestc:
13804   case Intrinsic::x86_sse41_ptestnzc:
13805   case Intrinsic::x86_avx_ptestz_256:
13806   case Intrinsic::x86_avx_ptestc_256:
13807   case Intrinsic::x86_avx_ptestnzc_256:
13808   case Intrinsic::x86_avx_vtestz_ps:
13809   case Intrinsic::x86_avx_vtestc_ps:
13810   case Intrinsic::x86_avx_vtestnzc_ps:
13811   case Intrinsic::x86_avx_vtestz_pd:
13812   case Intrinsic::x86_avx_vtestc_pd:
13813   case Intrinsic::x86_avx_vtestnzc_pd:
13814   case Intrinsic::x86_avx_vtestz_ps_256:
13815   case Intrinsic::x86_avx_vtestc_ps_256:
13816   case Intrinsic::x86_avx_vtestnzc_ps_256:
13817   case Intrinsic::x86_avx_vtestz_pd_256:
13818   case Intrinsic::x86_avx_vtestc_pd_256:
13819   case Intrinsic::x86_avx_vtestnzc_pd_256: {
13820     bool IsTestPacked = false;
13821     unsigned X86CC;
13822     switch (IntNo) {
13823     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13824     case Intrinsic::x86_avx_vtestz_ps:
13825     case Intrinsic::x86_avx_vtestz_pd:
13826     case Intrinsic::x86_avx_vtestz_ps_256:
13827     case Intrinsic::x86_avx_vtestz_pd_256:
13828       IsTestPacked = true; // Fallthrough
13829     case Intrinsic::x86_sse41_ptestz:
13830     case Intrinsic::x86_avx_ptestz_256:
13831       // ZF = 1
13832       X86CC = X86::COND_E;
13833       break;
13834     case Intrinsic::x86_avx_vtestc_ps:
13835     case Intrinsic::x86_avx_vtestc_pd:
13836     case Intrinsic::x86_avx_vtestc_ps_256:
13837     case Intrinsic::x86_avx_vtestc_pd_256:
13838       IsTestPacked = true; // Fallthrough
13839     case Intrinsic::x86_sse41_ptestc:
13840     case Intrinsic::x86_avx_ptestc_256:
13841       // CF = 1
13842       X86CC = X86::COND_B;
13843       break;
13844     case Intrinsic::x86_avx_vtestnzc_ps:
13845     case Intrinsic::x86_avx_vtestnzc_pd:
13846     case Intrinsic::x86_avx_vtestnzc_ps_256:
13847     case Intrinsic::x86_avx_vtestnzc_pd_256:
13848       IsTestPacked = true; // Fallthrough
13849     case Intrinsic::x86_sse41_ptestnzc:
13850     case Intrinsic::x86_avx_ptestnzc_256:
13851       // ZF and CF = 0
13852       X86CC = X86::COND_A;
13853       break;
13854     }
13855
13856     SDValue LHS = Op.getOperand(1);
13857     SDValue RHS = Op.getOperand(2);
13858     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13859     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13860     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13861     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13862     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13863   }
13864   case Intrinsic::x86_avx512_kortestz_w:
13865   case Intrinsic::x86_avx512_kortestc_w: {
13866     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13867     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13868     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13869     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13870     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13871     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13872     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13873   }
13874
13875   // SSE/AVX shift intrinsics
13876   case Intrinsic::x86_sse2_psll_w:
13877   case Intrinsic::x86_sse2_psll_d:
13878   case Intrinsic::x86_sse2_psll_q:
13879   case Intrinsic::x86_avx2_psll_w:
13880   case Intrinsic::x86_avx2_psll_d:
13881   case Intrinsic::x86_avx2_psll_q:
13882   case Intrinsic::x86_sse2_psrl_w:
13883   case Intrinsic::x86_sse2_psrl_d:
13884   case Intrinsic::x86_sse2_psrl_q:
13885   case Intrinsic::x86_avx2_psrl_w:
13886   case Intrinsic::x86_avx2_psrl_d:
13887   case Intrinsic::x86_avx2_psrl_q:
13888   case Intrinsic::x86_sse2_psra_w:
13889   case Intrinsic::x86_sse2_psra_d:
13890   case Intrinsic::x86_avx2_psra_w:
13891   case Intrinsic::x86_avx2_psra_d: {
13892     unsigned Opcode;
13893     switch (IntNo) {
13894     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13895     case Intrinsic::x86_sse2_psll_w:
13896     case Intrinsic::x86_sse2_psll_d:
13897     case Intrinsic::x86_sse2_psll_q:
13898     case Intrinsic::x86_avx2_psll_w:
13899     case Intrinsic::x86_avx2_psll_d:
13900     case Intrinsic::x86_avx2_psll_q:
13901       Opcode = X86ISD::VSHL;
13902       break;
13903     case Intrinsic::x86_sse2_psrl_w:
13904     case Intrinsic::x86_sse2_psrl_d:
13905     case Intrinsic::x86_sse2_psrl_q:
13906     case Intrinsic::x86_avx2_psrl_w:
13907     case Intrinsic::x86_avx2_psrl_d:
13908     case Intrinsic::x86_avx2_psrl_q:
13909       Opcode = X86ISD::VSRL;
13910       break;
13911     case Intrinsic::x86_sse2_psra_w:
13912     case Intrinsic::x86_sse2_psra_d:
13913     case Intrinsic::x86_avx2_psra_w:
13914     case Intrinsic::x86_avx2_psra_d:
13915       Opcode = X86ISD::VSRA;
13916       break;
13917     }
13918     return DAG.getNode(Opcode, dl, Op.getValueType(),
13919                        Op.getOperand(1), Op.getOperand(2));
13920   }
13921
13922   // SSE/AVX immediate shift intrinsics
13923   case Intrinsic::x86_sse2_pslli_w:
13924   case Intrinsic::x86_sse2_pslli_d:
13925   case Intrinsic::x86_sse2_pslli_q:
13926   case Intrinsic::x86_avx2_pslli_w:
13927   case Intrinsic::x86_avx2_pslli_d:
13928   case Intrinsic::x86_avx2_pslli_q:
13929   case Intrinsic::x86_sse2_psrli_w:
13930   case Intrinsic::x86_sse2_psrli_d:
13931   case Intrinsic::x86_sse2_psrli_q:
13932   case Intrinsic::x86_avx2_psrli_w:
13933   case Intrinsic::x86_avx2_psrli_d:
13934   case Intrinsic::x86_avx2_psrli_q:
13935   case Intrinsic::x86_sse2_psrai_w:
13936   case Intrinsic::x86_sse2_psrai_d:
13937   case Intrinsic::x86_avx2_psrai_w:
13938   case Intrinsic::x86_avx2_psrai_d: {
13939     unsigned Opcode;
13940     switch (IntNo) {
13941     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13942     case Intrinsic::x86_sse2_pslli_w:
13943     case Intrinsic::x86_sse2_pslli_d:
13944     case Intrinsic::x86_sse2_pslli_q:
13945     case Intrinsic::x86_avx2_pslli_w:
13946     case Intrinsic::x86_avx2_pslli_d:
13947     case Intrinsic::x86_avx2_pslli_q:
13948       Opcode = X86ISD::VSHLI;
13949       break;
13950     case Intrinsic::x86_sse2_psrli_w:
13951     case Intrinsic::x86_sse2_psrli_d:
13952     case Intrinsic::x86_sse2_psrli_q:
13953     case Intrinsic::x86_avx2_psrli_w:
13954     case Intrinsic::x86_avx2_psrli_d:
13955     case Intrinsic::x86_avx2_psrli_q:
13956       Opcode = X86ISD::VSRLI;
13957       break;
13958     case Intrinsic::x86_sse2_psrai_w:
13959     case Intrinsic::x86_sse2_psrai_d:
13960     case Intrinsic::x86_avx2_psrai_w:
13961     case Intrinsic::x86_avx2_psrai_d:
13962       Opcode = X86ISD::VSRAI;
13963       break;
13964     }
13965     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
13966                                Op.getOperand(1), Op.getOperand(2), DAG);
13967   }
13968
13969   case Intrinsic::x86_sse42_pcmpistria128:
13970   case Intrinsic::x86_sse42_pcmpestria128:
13971   case Intrinsic::x86_sse42_pcmpistric128:
13972   case Intrinsic::x86_sse42_pcmpestric128:
13973   case Intrinsic::x86_sse42_pcmpistrio128:
13974   case Intrinsic::x86_sse42_pcmpestrio128:
13975   case Intrinsic::x86_sse42_pcmpistris128:
13976   case Intrinsic::x86_sse42_pcmpestris128:
13977   case Intrinsic::x86_sse42_pcmpistriz128:
13978   case Intrinsic::x86_sse42_pcmpestriz128: {
13979     unsigned Opcode;
13980     unsigned X86CC;
13981     switch (IntNo) {
13982     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13983     case Intrinsic::x86_sse42_pcmpistria128:
13984       Opcode = X86ISD::PCMPISTRI;
13985       X86CC = X86::COND_A;
13986       break;
13987     case Intrinsic::x86_sse42_pcmpestria128:
13988       Opcode = X86ISD::PCMPESTRI;
13989       X86CC = X86::COND_A;
13990       break;
13991     case Intrinsic::x86_sse42_pcmpistric128:
13992       Opcode = X86ISD::PCMPISTRI;
13993       X86CC = X86::COND_B;
13994       break;
13995     case Intrinsic::x86_sse42_pcmpestric128:
13996       Opcode = X86ISD::PCMPESTRI;
13997       X86CC = X86::COND_B;
13998       break;
13999     case Intrinsic::x86_sse42_pcmpistrio128:
14000       Opcode = X86ISD::PCMPISTRI;
14001       X86CC = X86::COND_O;
14002       break;
14003     case Intrinsic::x86_sse42_pcmpestrio128:
14004       Opcode = X86ISD::PCMPESTRI;
14005       X86CC = X86::COND_O;
14006       break;
14007     case Intrinsic::x86_sse42_pcmpistris128:
14008       Opcode = X86ISD::PCMPISTRI;
14009       X86CC = X86::COND_S;
14010       break;
14011     case Intrinsic::x86_sse42_pcmpestris128:
14012       Opcode = X86ISD::PCMPESTRI;
14013       X86CC = X86::COND_S;
14014       break;
14015     case Intrinsic::x86_sse42_pcmpistriz128:
14016       Opcode = X86ISD::PCMPISTRI;
14017       X86CC = X86::COND_E;
14018       break;
14019     case Intrinsic::x86_sse42_pcmpestriz128:
14020       Opcode = X86ISD::PCMPESTRI;
14021       X86CC = X86::COND_E;
14022       break;
14023     }
14024     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14025     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14026     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14027     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14028                                 DAG.getConstant(X86CC, MVT::i8),
14029                                 SDValue(PCMP.getNode(), 1));
14030     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14031   }
14032
14033   case Intrinsic::x86_sse42_pcmpistri128:
14034   case Intrinsic::x86_sse42_pcmpestri128: {
14035     unsigned Opcode;
14036     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14037       Opcode = X86ISD::PCMPISTRI;
14038     else
14039       Opcode = X86ISD::PCMPESTRI;
14040
14041     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14042     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14043     return DAG.getNode(Opcode, dl, VTs, NewOps);
14044   }
14045   case Intrinsic::x86_fma_vfmadd_ps:
14046   case Intrinsic::x86_fma_vfmadd_pd:
14047   case Intrinsic::x86_fma_vfmsub_ps:
14048   case Intrinsic::x86_fma_vfmsub_pd:
14049   case Intrinsic::x86_fma_vfnmadd_ps:
14050   case Intrinsic::x86_fma_vfnmadd_pd:
14051   case Intrinsic::x86_fma_vfnmsub_ps:
14052   case Intrinsic::x86_fma_vfnmsub_pd:
14053   case Intrinsic::x86_fma_vfmaddsub_ps:
14054   case Intrinsic::x86_fma_vfmaddsub_pd:
14055   case Intrinsic::x86_fma_vfmsubadd_ps:
14056   case Intrinsic::x86_fma_vfmsubadd_pd:
14057   case Intrinsic::x86_fma_vfmadd_ps_256:
14058   case Intrinsic::x86_fma_vfmadd_pd_256:
14059   case Intrinsic::x86_fma_vfmsub_ps_256:
14060   case Intrinsic::x86_fma_vfmsub_pd_256:
14061   case Intrinsic::x86_fma_vfnmadd_ps_256:
14062   case Intrinsic::x86_fma_vfnmadd_pd_256:
14063   case Intrinsic::x86_fma_vfnmsub_ps_256:
14064   case Intrinsic::x86_fma_vfnmsub_pd_256:
14065   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14066   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14067   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14068   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14069   case Intrinsic::x86_fma_vfmadd_ps_512:
14070   case Intrinsic::x86_fma_vfmadd_pd_512:
14071   case Intrinsic::x86_fma_vfmsub_ps_512:
14072   case Intrinsic::x86_fma_vfmsub_pd_512:
14073   case Intrinsic::x86_fma_vfnmadd_ps_512:
14074   case Intrinsic::x86_fma_vfnmadd_pd_512:
14075   case Intrinsic::x86_fma_vfnmsub_ps_512:
14076   case Intrinsic::x86_fma_vfnmsub_pd_512:
14077   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14078   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14079   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14080   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14081     unsigned Opc;
14082     switch (IntNo) {
14083     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14084     case Intrinsic::x86_fma_vfmadd_ps:
14085     case Intrinsic::x86_fma_vfmadd_pd:
14086     case Intrinsic::x86_fma_vfmadd_ps_256:
14087     case Intrinsic::x86_fma_vfmadd_pd_256:
14088     case Intrinsic::x86_fma_vfmadd_ps_512:
14089     case Intrinsic::x86_fma_vfmadd_pd_512:
14090       Opc = X86ISD::FMADD;
14091       break;
14092     case Intrinsic::x86_fma_vfmsub_ps:
14093     case Intrinsic::x86_fma_vfmsub_pd:
14094     case Intrinsic::x86_fma_vfmsub_ps_256:
14095     case Intrinsic::x86_fma_vfmsub_pd_256:
14096     case Intrinsic::x86_fma_vfmsub_ps_512:
14097     case Intrinsic::x86_fma_vfmsub_pd_512:
14098       Opc = X86ISD::FMSUB;
14099       break;
14100     case Intrinsic::x86_fma_vfnmadd_ps:
14101     case Intrinsic::x86_fma_vfnmadd_pd:
14102     case Intrinsic::x86_fma_vfnmadd_ps_256:
14103     case Intrinsic::x86_fma_vfnmadd_pd_256:
14104     case Intrinsic::x86_fma_vfnmadd_ps_512:
14105     case Intrinsic::x86_fma_vfnmadd_pd_512:
14106       Opc = X86ISD::FNMADD;
14107       break;
14108     case Intrinsic::x86_fma_vfnmsub_ps:
14109     case Intrinsic::x86_fma_vfnmsub_pd:
14110     case Intrinsic::x86_fma_vfnmsub_ps_256:
14111     case Intrinsic::x86_fma_vfnmsub_pd_256:
14112     case Intrinsic::x86_fma_vfnmsub_ps_512:
14113     case Intrinsic::x86_fma_vfnmsub_pd_512:
14114       Opc = X86ISD::FNMSUB;
14115       break;
14116     case Intrinsic::x86_fma_vfmaddsub_ps:
14117     case Intrinsic::x86_fma_vfmaddsub_pd:
14118     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14119     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14120     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14121     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14122       Opc = X86ISD::FMADDSUB;
14123       break;
14124     case Intrinsic::x86_fma_vfmsubadd_ps:
14125     case Intrinsic::x86_fma_vfmsubadd_pd:
14126     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14127     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14128     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14129     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14130       Opc = X86ISD::FMSUBADD;
14131       break;
14132     }
14133
14134     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14135                        Op.getOperand(2), Op.getOperand(3));
14136   }
14137   }
14138 }
14139
14140 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14141                               SDValue Src, SDValue Mask, SDValue Base,
14142                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14143                               const X86Subtarget * Subtarget) {
14144   SDLoc dl(Op);
14145   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14146   assert(C && "Invalid scale type");
14147   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14148   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14149                              Index.getSimpleValueType().getVectorNumElements());
14150   SDValue MaskInReg;
14151   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14152   if (MaskC)
14153     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14154   else
14155     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14156   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14157   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14158   SDValue Segment = DAG.getRegister(0, MVT::i32);
14159   if (Src.getOpcode() == ISD::UNDEF)
14160     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14161   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14162   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14163   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14164   return DAG.getMergeValues(RetOps, dl);
14165 }
14166
14167 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14168                                SDValue Src, SDValue Mask, SDValue Base,
14169                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14170   SDLoc dl(Op);
14171   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14172   assert(C && "Invalid scale type");
14173   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14174   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14175   SDValue Segment = DAG.getRegister(0, MVT::i32);
14176   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14177                              Index.getSimpleValueType().getVectorNumElements());
14178   SDValue MaskInReg;
14179   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14180   if (MaskC)
14181     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14182   else
14183     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14184   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14185   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14186   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14187   return SDValue(Res, 1);
14188 }
14189
14190 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14191                                SDValue Mask, SDValue Base, SDValue Index,
14192                                SDValue ScaleOp, SDValue Chain) {
14193   SDLoc dl(Op);
14194   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14195   assert(C && "Invalid scale type");
14196   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14197   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14198   SDValue Segment = DAG.getRegister(0, MVT::i32);
14199   EVT MaskVT =
14200     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14201   SDValue MaskInReg;
14202   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14203   if (MaskC)
14204     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14205   else
14206     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14207   //SDVTList VTs = DAG.getVTList(MVT::Other);
14208   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14209   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14210   return SDValue(Res, 0);
14211 }
14212
14213 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14214 // read performance monitor counters (x86_rdpmc).
14215 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14216                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14217                               SmallVectorImpl<SDValue> &Results) {
14218   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14219   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14220   SDValue LO, HI;
14221
14222   // The ECX register is used to select the index of the performance counter
14223   // to read.
14224   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14225                                    N->getOperand(2));
14226   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14227
14228   // Reads the content of a 64-bit performance counter and returns it in the
14229   // registers EDX:EAX.
14230   if (Subtarget->is64Bit()) {
14231     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14232     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14233                             LO.getValue(2));
14234   } else {
14235     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14236     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14237                             LO.getValue(2));
14238   }
14239   Chain = HI.getValue(1);
14240
14241   if (Subtarget->is64Bit()) {
14242     // The EAX register is loaded with the low-order 32 bits. The EDX register
14243     // is loaded with the supported high-order bits of the counter.
14244     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14245                               DAG.getConstant(32, MVT::i8));
14246     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14247     Results.push_back(Chain);
14248     return;
14249   }
14250
14251   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14252   SDValue Ops[] = { LO, HI };
14253   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14254   Results.push_back(Pair);
14255   Results.push_back(Chain);
14256 }
14257
14258 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14259 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14260 // also used to custom lower READCYCLECOUNTER nodes.
14261 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14262                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14263                               SmallVectorImpl<SDValue> &Results) {
14264   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14265   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14266   SDValue LO, HI;
14267
14268   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14269   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14270   // and the EAX register is loaded with the low-order 32 bits.
14271   if (Subtarget->is64Bit()) {
14272     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14273     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14274                             LO.getValue(2));
14275   } else {
14276     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14277     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14278                             LO.getValue(2));
14279   }
14280   SDValue Chain = HI.getValue(1);
14281
14282   if (Opcode == X86ISD::RDTSCP_DAG) {
14283     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14284
14285     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14286     // the ECX register. Add 'ecx' explicitly to the chain.
14287     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14288                                      HI.getValue(2));
14289     // Explicitly store the content of ECX at the location passed in input
14290     // to the 'rdtscp' intrinsic.
14291     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14292                          MachinePointerInfo(), false, false, 0);
14293   }
14294
14295   if (Subtarget->is64Bit()) {
14296     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14297     // the EAX register is loaded with the low-order 32 bits.
14298     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14299                               DAG.getConstant(32, MVT::i8));
14300     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14301     Results.push_back(Chain);
14302     return;
14303   }
14304
14305   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14306   SDValue Ops[] = { LO, HI };
14307   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14308   Results.push_back(Pair);
14309   Results.push_back(Chain);
14310 }
14311
14312 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14313                                      SelectionDAG &DAG) {
14314   SmallVector<SDValue, 2> Results;
14315   SDLoc DL(Op);
14316   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14317                           Results);
14318   return DAG.getMergeValues(Results, DL);
14319 }
14320
14321 enum IntrinsicType {
14322   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14323 };
14324
14325 struct IntrinsicData {
14326   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14327     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14328   IntrinsicType Type;
14329   unsigned      Opc0;
14330   unsigned      Opc1;
14331 };
14332
14333 std::map < unsigned, IntrinsicData> IntrMap;
14334 static void InitIntinsicsMap() {
14335   static bool Initialized = false;
14336   if (Initialized) 
14337     return;
14338   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14339                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14340   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14341                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14342   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14343                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14344   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14345                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14346   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14347                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14348   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14349                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14350   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14351                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14352   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14353                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14354   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14355                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14356
14357   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14358                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14359   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14360                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14361   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14362                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14363   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14364                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14365   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14366                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14367   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14368                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14369   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14370                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14371   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14372                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14373    
14374   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14375                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14376                                                         X86::VGATHERPF1QPSm)));
14377   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14378                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14379                                                         X86::VGATHERPF1QPDm)));
14380   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14381                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14382                                                         X86::VGATHERPF1DPDm)));
14383   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14384                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14385                                                         X86::VGATHERPF1DPSm)));
14386   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14387                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14388                                                         X86::VSCATTERPF1QPSm)));
14389   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14390                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14391                                                         X86::VSCATTERPF1QPDm)));
14392   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14393                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14394                                                         X86::VSCATTERPF1DPDm)));
14395   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14396                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14397                                                         X86::VSCATTERPF1DPSm)));
14398   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14399                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14400   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14401                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14402   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14403                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14404   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14405                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14406   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14407                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14408   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14409                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14410   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14411                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14412   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14413                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14414   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14415                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14416   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14417                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14418   Initialized = true;
14419 }
14420
14421 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14422                                       SelectionDAG &DAG) {
14423   InitIntinsicsMap();
14424   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14425   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14426   if (itr == IntrMap.end())
14427     return SDValue();
14428
14429   SDLoc dl(Op);
14430   IntrinsicData Intr = itr->second;
14431   switch(Intr.Type) {
14432   case RDSEED:
14433   case RDRAND: {
14434     // Emit the node with the right value type.
14435     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14436     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14437
14438     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14439     // Otherwise return the value from Rand, which is always 0, casted to i32.
14440     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14441                       DAG.getConstant(1, Op->getValueType(1)),
14442                       DAG.getConstant(X86::COND_B, MVT::i32),
14443                       SDValue(Result.getNode(), 1) };
14444     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14445                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14446                                   Ops);
14447
14448     // Return { result, isValid, chain }.
14449     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14450                        SDValue(Result.getNode(), 2));
14451   }
14452   case GATHER: {
14453   //gather(v1, mask, index, base, scale);
14454     SDValue Chain = Op.getOperand(0);
14455     SDValue Src   = Op.getOperand(2);
14456     SDValue Base  = Op.getOperand(3);
14457     SDValue Index = Op.getOperand(4);
14458     SDValue Mask  = Op.getOperand(5);
14459     SDValue Scale = Op.getOperand(6);
14460     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14461                           Subtarget);
14462   }
14463   case SCATTER: {
14464   //scatter(base, mask, index, v1, scale);
14465     SDValue Chain = Op.getOperand(0);
14466     SDValue Base  = Op.getOperand(2);
14467     SDValue Mask  = Op.getOperand(3);
14468     SDValue Index = Op.getOperand(4);
14469     SDValue Src   = Op.getOperand(5);
14470     SDValue Scale = Op.getOperand(6);
14471     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14472   }
14473   case PREFETCH: {
14474     SDValue Hint = Op.getOperand(6);
14475     unsigned HintVal;
14476     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14477         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14478       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14479     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14480     SDValue Chain = Op.getOperand(0);
14481     SDValue Mask  = Op.getOperand(2);
14482     SDValue Index = Op.getOperand(3);
14483     SDValue Base  = Op.getOperand(4);
14484     SDValue Scale = Op.getOperand(5);
14485     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14486   }
14487   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14488   case RDTSC: {
14489     SmallVector<SDValue, 2> Results;
14490     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14491     return DAG.getMergeValues(Results, dl);
14492   }
14493   // Read Performance Monitoring Counters.
14494   case RDPMC: {
14495     SmallVector<SDValue, 2> Results;
14496     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14497     return DAG.getMergeValues(Results, dl);
14498   }
14499   // XTEST intrinsics.
14500   case XTEST: {
14501     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14502     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14503     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14504                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14505                                 InTrans);
14506     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14507     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14508                        Ret, SDValue(InTrans.getNode(), 1));
14509   }
14510   }
14511   llvm_unreachable("Unknown Intrinsic Type");
14512 }
14513
14514 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14515                                            SelectionDAG &DAG) const {
14516   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14517   MFI->setReturnAddressIsTaken(true);
14518
14519   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14520     return SDValue();
14521
14522   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14523   SDLoc dl(Op);
14524   EVT PtrVT = getPointerTy();
14525
14526   if (Depth > 0) {
14527     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14528     const X86RegisterInfo *RegInfo =
14529       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14530     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14531     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14532                        DAG.getNode(ISD::ADD, dl, PtrVT,
14533                                    FrameAddr, Offset),
14534                        MachinePointerInfo(), false, false, false, 0);
14535   }
14536
14537   // Just load the return address.
14538   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14539   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14540                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14541 }
14542
14543 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14544   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14545   MFI->setFrameAddressIsTaken(true);
14546
14547   EVT VT = Op.getValueType();
14548   SDLoc dl(Op);  // FIXME probably not meaningful
14549   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14550   const X86RegisterInfo *RegInfo =
14551     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14552   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14553   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14554           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14555          "Invalid Frame Register!");
14556   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14557   while (Depth--)
14558     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14559                             MachinePointerInfo(),
14560                             false, false, false, 0);
14561   return FrameAddr;
14562 }
14563
14564 // FIXME? Maybe this could be a TableGen attribute on some registers and
14565 // this table could be generated automatically from RegInfo.
14566 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14567                                               EVT VT) const {
14568   unsigned Reg = StringSwitch<unsigned>(RegName)
14569                        .Case("esp", X86::ESP)
14570                        .Case("rsp", X86::RSP)
14571                        .Default(0);
14572   if (Reg)
14573     return Reg;
14574   report_fatal_error("Invalid register name global variable");
14575 }
14576
14577 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14578                                                      SelectionDAG &DAG) const {
14579   const X86RegisterInfo *RegInfo =
14580     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14581   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14582 }
14583
14584 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14585   SDValue Chain     = Op.getOperand(0);
14586   SDValue Offset    = Op.getOperand(1);
14587   SDValue Handler   = Op.getOperand(2);
14588   SDLoc dl      (Op);
14589
14590   EVT PtrVT = getPointerTy();
14591   const X86RegisterInfo *RegInfo =
14592     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14593   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14594   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14595           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14596          "Invalid Frame Register!");
14597   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14598   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14599
14600   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14601                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14602   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14603   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14604                        false, false, 0);
14605   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14606
14607   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14608                      DAG.getRegister(StoreAddrReg, PtrVT));
14609 }
14610
14611 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14612                                                SelectionDAG &DAG) const {
14613   SDLoc DL(Op);
14614   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14615                      DAG.getVTList(MVT::i32, MVT::Other),
14616                      Op.getOperand(0), Op.getOperand(1));
14617 }
14618
14619 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14620                                                 SelectionDAG &DAG) const {
14621   SDLoc DL(Op);
14622   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14623                      Op.getOperand(0), Op.getOperand(1));
14624 }
14625
14626 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14627   return Op.getOperand(0);
14628 }
14629
14630 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14631                                                 SelectionDAG &DAG) const {
14632   SDValue Root = Op.getOperand(0);
14633   SDValue Trmp = Op.getOperand(1); // trampoline
14634   SDValue FPtr = Op.getOperand(2); // nested function
14635   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14636   SDLoc dl (Op);
14637
14638   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14639   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14640
14641   if (Subtarget->is64Bit()) {
14642     SDValue OutChains[6];
14643
14644     // Large code-model.
14645     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14646     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14647
14648     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14649     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14650
14651     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14652
14653     // Load the pointer to the nested function into R11.
14654     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14655     SDValue Addr = Trmp;
14656     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14657                                 Addr, MachinePointerInfo(TrmpAddr),
14658                                 false, false, 0);
14659
14660     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14661                        DAG.getConstant(2, MVT::i64));
14662     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14663                                 MachinePointerInfo(TrmpAddr, 2),
14664                                 false, false, 2);
14665
14666     // Load the 'nest' parameter value into R10.
14667     // R10 is specified in X86CallingConv.td
14668     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14669     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14670                        DAG.getConstant(10, MVT::i64));
14671     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14672                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14673                                 false, false, 0);
14674
14675     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14676                        DAG.getConstant(12, MVT::i64));
14677     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14678                                 MachinePointerInfo(TrmpAddr, 12),
14679                                 false, false, 2);
14680
14681     // Jump to the nested function.
14682     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14683     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14684                        DAG.getConstant(20, MVT::i64));
14685     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14686                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14687                                 false, false, 0);
14688
14689     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14690     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14691                        DAG.getConstant(22, MVT::i64));
14692     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14693                                 MachinePointerInfo(TrmpAddr, 22),
14694                                 false, false, 0);
14695
14696     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14697   } else {
14698     const Function *Func =
14699       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14700     CallingConv::ID CC = Func->getCallingConv();
14701     unsigned NestReg;
14702
14703     switch (CC) {
14704     default:
14705       llvm_unreachable("Unsupported calling convention");
14706     case CallingConv::C:
14707     case CallingConv::X86_StdCall: {
14708       // Pass 'nest' parameter in ECX.
14709       // Must be kept in sync with X86CallingConv.td
14710       NestReg = X86::ECX;
14711
14712       // Check that ECX wasn't needed by an 'inreg' parameter.
14713       FunctionType *FTy = Func->getFunctionType();
14714       const AttributeSet &Attrs = Func->getAttributes();
14715
14716       if (!Attrs.isEmpty() && !Func->isVarArg()) {
14717         unsigned InRegCount = 0;
14718         unsigned Idx = 1;
14719
14720         for (FunctionType::param_iterator I = FTy->param_begin(),
14721              E = FTy->param_end(); I != E; ++I, ++Idx)
14722           if (Attrs.hasAttribute(Idx, Attribute::InReg))
14723             // FIXME: should only count parameters that are lowered to integers.
14724             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14725
14726         if (InRegCount > 2) {
14727           report_fatal_error("Nest register in use - reduce number of inreg"
14728                              " parameters!");
14729         }
14730       }
14731       break;
14732     }
14733     case CallingConv::X86_FastCall:
14734     case CallingConv::X86_ThisCall:
14735     case CallingConv::Fast:
14736       // Pass 'nest' parameter in EAX.
14737       // Must be kept in sync with X86CallingConv.td
14738       NestReg = X86::EAX;
14739       break;
14740     }
14741
14742     SDValue OutChains[4];
14743     SDValue Addr, Disp;
14744
14745     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14746                        DAG.getConstant(10, MVT::i32));
14747     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14748
14749     // This is storing the opcode for MOV32ri.
14750     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14751     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14752     OutChains[0] = DAG.getStore(Root, dl,
14753                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14754                                 Trmp, MachinePointerInfo(TrmpAddr),
14755                                 false, false, 0);
14756
14757     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14758                        DAG.getConstant(1, MVT::i32));
14759     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14760                                 MachinePointerInfo(TrmpAddr, 1),
14761                                 false, false, 1);
14762
14763     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14764     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14765                        DAG.getConstant(5, MVT::i32));
14766     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14767                                 MachinePointerInfo(TrmpAddr, 5),
14768                                 false, false, 1);
14769
14770     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14771                        DAG.getConstant(6, MVT::i32));
14772     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14773                                 MachinePointerInfo(TrmpAddr, 6),
14774                                 false, false, 1);
14775
14776     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14777   }
14778 }
14779
14780 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14781                                             SelectionDAG &DAG) const {
14782   /*
14783    The rounding mode is in bits 11:10 of FPSR, and has the following
14784    settings:
14785      00 Round to nearest
14786      01 Round to -inf
14787      10 Round to +inf
14788      11 Round to 0
14789
14790   FLT_ROUNDS, on the other hand, expects the following:
14791     -1 Undefined
14792      0 Round to 0
14793      1 Round to nearest
14794      2 Round to +inf
14795      3 Round to -inf
14796
14797   To perform the conversion, we do:
14798     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14799   */
14800
14801   MachineFunction &MF = DAG.getMachineFunction();
14802   const TargetMachine &TM = MF.getTarget();
14803   const TargetFrameLowering &TFI = *TM.getFrameLowering();
14804   unsigned StackAlignment = TFI.getStackAlignment();
14805   MVT VT = Op.getSimpleValueType();
14806   SDLoc DL(Op);
14807
14808   // Save FP Control Word to stack slot
14809   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14810   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14811
14812   MachineMemOperand *MMO =
14813    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14814                            MachineMemOperand::MOStore, 2, 2);
14815
14816   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14817   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14818                                           DAG.getVTList(MVT::Other),
14819                                           Ops, MVT::i16, MMO);
14820
14821   // Load FP Control Word from stack slot
14822   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14823                             MachinePointerInfo(), false, false, false, 0);
14824
14825   // Transform as necessary
14826   SDValue CWD1 =
14827     DAG.getNode(ISD::SRL, DL, MVT::i16,
14828                 DAG.getNode(ISD::AND, DL, MVT::i16,
14829                             CWD, DAG.getConstant(0x800, MVT::i16)),
14830                 DAG.getConstant(11, MVT::i8));
14831   SDValue CWD2 =
14832     DAG.getNode(ISD::SRL, DL, MVT::i16,
14833                 DAG.getNode(ISD::AND, DL, MVT::i16,
14834                             CWD, DAG.getConstant(0x400, MVT::i16)),
14835                 DAG.getConstant(9, MVT::i8));
14836
14837   SDValue RetVal =
14838     DAG.getNode(ISD::AND, DL, MVT::i16,
14839                 DAG.getNode(ISD::ADD, DL, MVT::i16,
14840                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14841                             DAG.getConstant(1, MVT::i16)),
14842                 DAG.getConstant(3, MVT::i16));
14843
14844   return DAG.getNode((VT.getSizeInBits() < 16 ?
14845                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14846 }
14847
14848 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14849   MVT VT = Op.getSimpleValueType();
14850   EVT OpVT = VT;
14851   unsigned NumBits = VT.getSizeInBits();
14852   SDLoc dl(Op);
14853
14854   Op = Op.getOperand(0);
14855   if (VT == MVT::i8) {
14856     // Zero extend to i32 since there is not an i8 bsr.
14857     OpVT = MVT::i32;
14858     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14859   }
14860
14861   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14862   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14863   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14864
14865   // If src is zero (i.e. bsr sets ZF), returns NumBits.
14866   SDValue Ops[] = {
14867     Op,
14868     DAG.getConstant(NumBits+NumBits-1, OpVT),
14869     DAG.getConstant(X86::COND_E, MVT::i8),
14870     Op.getValue(1)
14871   };
14872   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14873
14874   // Finally xor with NumBits-1.
14875   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14876
14877   if (VT == MVT::i8)
14878     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14879   return Op;
14880 }
14881
14882 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14883   MVT VT = Op.getSimpleValueType();
14884   EVT OpVT = VT;
14885   unsigned NumBits = VT.getSizeInBits();
14886   SDLoc dl(Op);
14887
14888   Op = Op.getOperand(0);
14889   if (VT == MVT::i8) {
14890     // Zero extend to i32 since there is not an i8 bsr.
14891     OpVT = MVT::i32;
14892     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14893   }
14894
14895   // Issue a bsr (scan bits in reverse).
14896   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14897   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14898
14899   // And xor with NumBits-1.
14900   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14901
14902   if (VT == MVT::i8)
14903     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14904   return Op;
14905 }
14906
14907 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14908   MVT VT = Op.getSimpleValueType();
14909   unsigned NumBits = VT.getSizeInBits();
14910   SDLoc dl(Op);
14911   Op = Op.getOperand(0);
14912
14913   // Issue a bsf (scan bits forward) which also sets EFLAGS.
14914   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14915   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14916
14917   // If src is zero (i.e. bsf sets ZF), returns NumBits.
14918   SDValue Ops[] = {
14919     Op,
14920     DAG.getConstant(NumBits, VT),
14921     DAG.getConstant(X86::COND_E, MVT::i8),
14922     Op.getValue(1)
14923   };
14924   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14925 }
14926
14927 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14928 // ones, and then concatenate the result back.
14929 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14930   MVT VT = Op.getSimpleValueType();
14931
14932   assert(VT.is256BitVector() && VT.isInteger() &&
14933          "Unsupported value type for operation");
14934
14935   unsigned NumElems = VT.getVectorNumElements();
14936   SDLoc dl(Op);
14937
14938   // Extract the LHS vectors
14939   SDValue LHS = Op.getOperand(0);
14940   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14941   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14942
14943   // Extract the RHS vectors
14944   SDValue RHS = Op.getOperand(1);
14945   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14946   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14947
14948   MVT EltVT = VT.getVectorElementType();
14949   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14950
14951   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14952                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
14953                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
14954 }
14955
14956 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
14957   assert(Op.getSimpleValueType().is256BitVector() &&
14958          Op.getSimpleValueType().isInteger() &&
14959          "Only handle AVX 256-bit vector integer operation");
14960   return Lower256IntArith(Op, DAG);
14961 }
14962
14963 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
14964   assert(Op.getSimpleValueType().is256BitVector() &&
14965          Op.getSimpleValueType().isInteger() &&
14966          "Only handle AVX 256-bit vector integer operation");
14967   return Lower256IntArith(Op, DAG);
14968 }
14969
14970 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
14971                         SelectionDAG &DAG) {
14972   SDLoc dl(Op);
14973   MVT VT = Op.getSimpleValueType();
14974
14975   // Decompose 256-bit ops into smaller 128-bit ops.
14976   if (VT.is256BitVector() && !Subtarget->hasInt256())
14977     return Lower256IntArith(Op, DAG);
14978
14979   SDValue A = Op.getOperand(0);
14980   SDValue B = Op.getOperand(1);
14981
14982   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
14983   if (VT == MVT::v4i32) {
14984     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
14985            "Should not custom lower when pmuldq is available!");
14986
14987     // Extract the odd parts.
14988     static const int UnpackMask[] = { 1, -1, 3, -1 };
14989     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
14990     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
14991
14992     // Multiply the even parts.
14993     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
14994     // Now multiply odd parts.
14995     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
14996
14997     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
14998     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
14999
15000     // Merge the two vectors back together with a shuffle. This expands into 2
15001     // shuffles.
15002     static const int ShufMask[] = { 0, 4, 2, 6 };
15003     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15004   }
15005
15006   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15007          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15008
15009   //  Ahi = psrlqi(a, 32);
15010   //  Bhi = psrlqi(b, 32);
15011   //
15012   //  AloBlo = pmuludq(a, b);
15013   //  AloBhi = pmuludq(a, Bhi);
15014   //  AhiBlo = pmuludq(Ahi, b);
15015
15016   //  AloBhi = psllqi(AloBhi, 32);
15017   //  AhiBlo = psllqi(AhiBlo, 32);
15018   //  return AloBlo + AloBhi + AhiBlo;
15019
15020   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15021   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15022
15023   // Bit cast to 32-bit vectors for MULUDQ
15024   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15025                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15026   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15027   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15028   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15029   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15030
15031   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15032   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15033   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15034
15035   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15036   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15037
15038   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15039   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15040 }
15041
15042 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15043   assert(Subtarget->isTargetWin64() && "Unexpected target");
15044   EVT VT = Op.getValueType();
15045   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15046          "Unexpected return type for lowering");
15047
15048   RTLIB::Libcall LC;
15049   bool isSigned;
15050   switch (Op->getOpcode()) {
15051   default: llvm_unreachable("Unexpected request for libcall!");
15052   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15053   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15054   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15055   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15056   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15057   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15058   }
15059
15060   SDLoc dl(Op);
15061   SDValue InChain = DAG.getEntryNode();
15062
15063   TargetLowering::ArgListTy Args;
15064   TargetLowering::ArgListEntry Entry;
15065   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15066     EVT ArgVT = Op->getOperand(i).getValueType();
15067     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15068            "Unexpected argument type for lowering");
15069     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15070     Entry.Node = StackPtr;
15071     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15072                            false, false, 16);
15073     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15074     Entry.Ty = PointerType::get(ArgTy,0);
15075     Entry.isSExt = false;
15076     Entry.isZExt = false;
15077     Args.push_back(Entry);
15078   }
15079
15080   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15081                                          getPointerTy());
15082
15083   TargetLowering::CallLoweringInfo CLI(DAG);
15084   CLI.setDebugLoc(dl).setChain(InChain)
15085     .setCallee(getLibcallCallingConv(LC),
15086                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15087                Callee, std::move(Args), 0)
15088     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15089
15090   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15091   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15092 }
15093
15094 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15095                              SelectionDAG &DAG) {
15096   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15097   EVT VT = Op0.getValueType();
15098   SDLoc dl(Op);
15099
15100   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15101          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15102
15103   // Get the high parts.
15104   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
15105   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15106   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15107
15108   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15109   // ints.
15110   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15111   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15112   unsigned Opcode =
15113       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15114   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15115                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15116   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15117                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15118
15119   // Shuffle it back into the right order.
15120   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
15121   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15122   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
15123   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15124
15125   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15126   // unsigned multiply.
15127   if (IsSigned && !Subtarget->hasSSE41()) {
15128     SDValue ShAmt =
15129         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15130     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15131                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15132     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15133                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15134
15135     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15136     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15137   }
15138
15139   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15140 }
15141
15142 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15143                                          const X86Subtarget *Subtarget) {
15144   MVT VT = Op.getSimpleValueType();
15145   SDLoc dl(Op);
15146   SDValue R = Op.getOperand(0);
15147   SDValue Amt = Op.getOperand(1);
15148
15149   // Optimize shl/srl/sra with constant shift amount.
15150   if (isSplatVector(Amt.getNode())) {
15151     SDValue SclrAmt = Amt->getOperand(0);
15152     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
15153       uint64_t ShiftAmt = C->getZExtValue();
15154
15155       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15156           (Subtarget->hasInt256() &&
15157            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15158           (Subtarget->hasAVX512() &&
15159            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15160         if (Op.getOpcode() == ISD::SHL)
15161           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15162                                             DAG);
15163         if (Op.getOpcode() == ISD::SRL)
15164           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15165                                             DAG);
15166         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15167           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15168                                             DAG);
15169       }
15170
15171       if (VT == MVT::v16i8) {
15172         if (Op.getOpcode() == ISD::SHL) {
15173           // Make a large shift.
15174           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15175                                                    MVT::v8i16, R, ShiftAmt,
15176                                                    DAG);
15177           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15178           // Zero out the rightmost bits.
15179           SmallVector<SDValue, 16> V(16,
15180                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15181                                                      MVT::i8));
15182           return DAG.getNode(ISD::AND, dl, VT, SHL,
15183                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15184         }
15185         if (Op.getOpcode() == ISD::SRL) {
15186           // Make a large shift.
15187           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15188                                                    MVT::v8i16, R, ShiftAmt,
15189                                                    DAG);
15190           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15191           // Zero out the leftmost bits.
15192           SmallVector<SDValue, 16> V(16,
15193                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15194                                                      MVT::i8));
15195           return DAG.getNode(ISD::AND, dl, VT, SRL,
15196                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15197         }
15198         if (Op.getOpcode() == ISD::SRA) {
15199           if (ShiftAmt == 7) {
15200             // R s>> 7  ===  R s< 0
15201             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15202             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15203           }
15204
15205           // R s>> a === ((R u>> a) ^ m) - m
15206           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15207           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15208                                                          MVT::i8));
15209           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15210           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15211           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15212           return Res;
15213         }
15214         llvm_unreachable("Unknown shift opcode.");
15215       }
15216
15217       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15218         if (Op.getOpcode() == ISD::SHL) {
15219           // Make a large shift.
15220           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15221                                                    MVT::v16i16, R, ShiftAmt,
15222                                                    DAG);
15223           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15224           // Zero out the rightmost bits.
15225           SmallVector<SDValue, 32> V(32,
15226                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15227                                                      MVT::i8));
15228           return DAG.getNode(ISD::AND, dl, VT, SHL,
15229                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15230         }
15231         if (Op.getOpcode() == ISD::SRL) {
15232           // Make a large shift.
15233           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15234                                                    MVT::v16i16, R, ShiftAmt,
15235                                                    DAG);
15236           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15237           // Zero out the leftmost bits.
15238           SmallVector<SDValue, 32> V(32,
15239                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15240                                                      MVT::i8));
15241           return DAG.getNode(ISD::AND, dl, VT, SRL,
15242                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15243         }
15244         if (Op.getOpcode() == ISD::SRA) {
15245           if (ShiftAmt == 7) {
15246             // R s>> 7  ===  R s< 0
15247             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15248             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15249           }
15250
15251           // R s>> a === ((R u>> a) ^ m) - m
15252           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15253           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15254                                                          MVT::i8));
15255           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15256           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15257           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15258           return Res;
15259         }
15260         llvm_unreachable("Unknown shift opcode.");
15261       }
15262     }
15263   }
15264
15265   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15266   if (!Subtarget->is64Bit() &&
15267       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15268       Amt.getOpcode() == ISD::BITCAST &&
15269       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15270     Amt = Amt.getOperand(0);
15271     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15272                      VT.getVectorNumElements();
15273     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15274     uint64_t ShiftAmt = 0;
15275     for (unsigned i = 0; i != Ratio; ++i) {
15276       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15277       if (!C)
15278         return SDValue();
15279       // 6 == Log2(64)
15280       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15281     }
15282     // Check remaining shift amounts.
15283     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15284       uint64_t ShAmt = 0;
15285       for (unsigned j = 0; j != Ratio; ++j) {
15286         ConstantSDNode *C =
15287           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15288         if (!C)
15289           return SDValue();
15290         // 6 == Log2(64)
15291         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15292       }
15293       if (ShAmt != ShiftAmt)
15294         return SDValue();
15295     }
15296     switch (Op.getOpcode()) {
15297     default:
15298       llvm_unreachable("Unknown shift opcode!");
15299     case ISD::SHL:
15300       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15301                                         DAG);
15302     case ISD::SRL:
15303       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15304                                         DAG);
15305     case ISD::SRA:
15306       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15307                                         DAG);
15308     }
15309   }
15310
15311   return SDValue();
15312 }
15313
15314 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15315                                         const X86Subtarget* Subtarget) {
15316   MVT VT = Op.getSimpleValueType();
15317   SDLoc dl(Op);
15318   SDValue R = Op.getOperand(0);
15319   SDValue Amt = Op.getOperand(1);
15320
15321   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15322       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15323       (Subtarget->hasInt256() &&
15324        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15325         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15326        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15327     SDValue BaseShAmt;
15328     EVT EltVT = VT.getVectorElementType();
15329
15330     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15331       unsigned NumElts = VT.getVectorNumElements();
15332       unsigned i, j;
15333       for (i = 0; i != NumElts; ++i) {
15334         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15335           continue;
15336         break;
15337       }
15338       for (j = i; j != NumElts; ++j) {
15339         SDValue Arg = Amt.getOperand(j);
15340         if (Arg.getOpcode() == ISD::UNDEF) continue;
15341         if (Arg != Amt.getOperand(i))
15342           break;
15343       }
15344       if (i != NumElts && j == NumElts)
15345         BaseShAmt = Amt.getOperand(i);
15346     } else {
15347       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15348         Amt = Amt.getOperand(0);
15349       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15350                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15351         SDValue InVec = Amt.getOperand(0);
15352         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15353           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15354           unsigned i = 0;
15355           for (; i != NumElts; ++i) {
15356             SDValue Arg = InVec.getOperand(i);
15357             if (Arg.getOpcode() == ISD::UNDEF) continue;
15358             BaseShAmt = Arg;
15359             break;
15360           }
15361         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15362            if (ConstantSDNode *C =
15363                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15364              unsigned SplatIdx =
15365                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15366              if (C->getZExtValue() == SplatIdx)
15367                BaseShAmt = InVec.getOperand(1);
15368            }
15369         }
15370         if (!BaseShAmt.getNode())
15371           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15372                                   DAG.getIntPtrConstant(0));
15373       }
15374     }
15375
15376     if (BaseShAmt.getNode()) {
15377       if (EltVT.bitsGT(MVT::i32))
15378         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15379       else if (EltVT.bitsLT(MVT::i32))
15380         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15381
15382       switch (Op.getOpcode()) {
15383       default:
15384         llvm_unreachable("Unknown shift opcode!");
15385       case ISD::SHL:
15386         switch (VT.SimpleTy) {
15387         default: return SDValue();
15388         case MVT::v2i64:
15389         case MVT::v4i32:
15390         case MVT::v8i16:
15391         case MVT::v4i64:
15392         case MVT::v8i32:
15393         case MVT::v16i16:
15394         case MVT::v16i32:
15395         case MVT::v8i64:
15396           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15397         }
15398       case ISD::SRA:
15399         switch (VT.SimpleTy) {
15400         default: return SDValue();
15401         case MVT::v4i32:
15402         case MVT::v8i16:
15403         case MVT::v8i32:
15404         case MVT::v16i16:
15405         case MVT::v16i32:
15406         case MVT::v8i64:
15407           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15408         }
15409       case ISD::SRL:
15410         switch (VT.SimpleTy) {
15411         default: return SDValue();
15412         case MVT::v2i64:
15413         case MVT::v4i32:
15414         case MVT::v8i16:
15415         case MVT::v4i64:
15416         case MVT::v8i32:
15417         case MVT::v16i16:
15418         case MVT::v16i32:
15419         case MVT::v8i64:
15420           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15421         }
15422       }
15423     }
15424   }
15425
15426   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15427   if (!Subtarget->is64Bit() &&
15428       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15429       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15430       Amt.getOpcode() == ISD::BITCAST &&
15431       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15432     Amt = Amt.getOperand(0);
15433     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15434                      VT.getVectorNumElements();
15435     std::vector<SDValue> Vals(Ratio);
15436     for (unsigned i = 0; i != Ratio; ++i)
15437       Vals[i] = Amt.getOperand(i);
15438     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15439       for (unsigned j = 0; j != Ratio; ++j)
15440         if (Vals[j] != Amt.getOperand(i + j))
15441           return SDValue();
15442     }
15443     switch (Op.getOpcode()) {
15444     default:
15445       llvm_unreachable("Unknown shift opcode!");
15446     case ISD::SHL:
15447       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15448     case ISD::SRL:
15449       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15450     case ISD::SRA:
15451       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15452     }
15453   }
15454
15455   return SDValue();
15456 }
15457
15458 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15459                           SelectionDAG &DAG) {
15460
15461   MVT VT = Op.getSimpleValueType();
15462   SDLoc dl(Op);
15463   SDValue R = Op.getOperand(0);
15464   SDValue Amt = Op.getOperand(1);
15465   SDValue V;
15466
15467   if (!Subtarget->hasSSE2())
15468     return SDValue();
15469
15470   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15471   if (V.getNode())
15472     return V;
15473
15474   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15475   if (V.getNode())
15476       return V;
15477
15478   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15479     return Op;
15480   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15481   if (Subtarget->hasInt256()) {
15482     if (Op.getOpcode() == ISD::SRL &&
15483         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15484          VT == MVT::v4i64 || VT == MVT::v8i32))
15485       return Op;
15486     if (Op.getOpcode() == ISD::SHL &&
15487         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15488          VT == MVT::v4i64 || VT == MVT::v8i32))
15489       return Op;
15490     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15491       return Op;
15492   }
15493
15494   // If possible, lower this packed shift into a vector multiply instead of
15495   // expanding it into a sequence of scalar shifts.
15496   // Do this only if the vector shift count is a constant build_vector.
15497   if (Op.getOpcode() == ISD::SHL && 
15498       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15499        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15500       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15501     SmallVector<SDValue, 8> Elts;
15502     EVT SVT = VT.getScalarType();
15503     unsigned SVTBits = SVT.getSizeInBits();
15504     const APInt &One = APInt(SVTBits, 1);
15505     unsigned NumElems = VT.getVectorNumElements();
15506
15507     for (unsigned i=0; i !=NumElems; ++i) {
15508       SDValue Op = Amt->getOperand(i);
15509       if (Op->getOpcode() == ISD::UNDEF) {
15510         Elts.push_back(Op);
15511         continue;
15512       }
15513
15514       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15515       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15516       uint64_t ShAmt = C.getZExtValue();
15517       if (ShAmt >= SVTBits) {
15518         Elts.push_back(DAG.getUNDEF(SVT));
15519         continue;
15520       }
15521       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15522     }
15523     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15524     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15525   }
15526
15527   // Lower SHL with variable shift amount.
15528   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15529     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15530
15531     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15532     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15533     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15534     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15535   }
15536
15537   // If possible, lower this shift as a sequence of two shifts by
15538   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15539   // Example:
15540   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15541   //
15542   // Could be rewritten as:
15543   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15544   //
15545   // The advantage is that the two shifts from the example would be
15546   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15547   // the vector shift into four scalar shifts plus four pairs of vector
15548   // insert/extract.
15549   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15550       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15551     unsigned TargetOpcode = X86ISD::MOVSS;
15552     bool CanBeSimplified;
15553     // The splat value for the first packed shift (the 'X' from the example).
15554     SDValue Amt1 = Amt->getOperand(0);
15555     // The splat value for the second packed shift (the 'Y' from the example).
15556     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15557                                         Amt->getOperand(2);
15558
15559     // See if it is possible to replace this node with a sequence of
15560     // two shifts followed by a MOVSS/MOVSD
15561     if (VT == MVT::v4i32) {
15562       // Check if it is legal to use a MOVSS.
15563       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15564                         Amt2 == Amt->getOperand(3);
15565       if (!CanBeSimplified) {
15566         // Otherwise, check if we can still simplify this node using a MOVSD.
15567         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15568                           Amt->getOperand(2) == Amt->getOperand(3);
15569         TargetOpcode = X86ISD::MOVSD;
15570         Amt2 = Amt->getOperand(2);
15571       }
15572     } else {
15573       // Do similar checks for the case where the machine value type
15574       // is MVT::v8i16.
15575       CanBeSimplified = Amt1 == Amt->getOperand(1);
15576       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15577         CanBeSimplified = Amt2 == Amt->getOperand(i);
15578
15579       if (!CanBeSimplified) {
15580         TargetOpcode = X86ISD::MOVSD;
15581         CanBeSimplified = true;
15582         Amt2 = Amt->getOperand(4);
15583         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15584           CanBeSimplified = Amt1 == Amt->getOperand(i);
15585         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15586           CanBeSimplified = Amt2 == Amt->getOperand(j);
15587       }
15588     }
15589     
15590     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15591         isa<ConstantSDNode>(Amt2)) {
15592       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15593       EVT CastVT = MVT::v4i32;
15594       SDValue Splat1 = 
15595         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15596       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15597       SDValue Splat2 = 
15598         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15599       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15600       if (TargetOpcode == X86ISD::MOVSD)
15601         CastVT = MVT::v2i64;
15602       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15603       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15604       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15605                                             BitCast1, DAG);
15606       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15607     }
15608   }
15609
15610   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15611     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15612
15613     // a = a << 5;
15614     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15615     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15616
15617     // Turn 'a' into a mask suitable for VSELECT
15618     SDValue VSelM = DAG.getConstant(0x80, VT);
15619     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15620     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15621
15622     SDValue CM1 = DAG.getConstant(0x0f, VT);
15623     SDValue CM2 = DAG.getConstant(0x3f, VT);
15624
15625     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15626     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15627     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15628     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15629     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15630
15631     // a += a
15632     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15633     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15634     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15635
15636     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15637     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15638     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15639     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15640     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15641
15642     // a += a
15643     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15644     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15645     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15646
15647     // return VSELECT(r, r+r, a);
15648     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15649                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15650     return R;
15651   }
15652
15653   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15654   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15655   // solution better.
15656   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15657     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15658     unsigned ExtOpc =
15659         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15660     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15661     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15662     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15663                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15664     }
15665
15666   // Decompose 256-bit shifts into smaller 128-bit shifts.
15667   if (VT.is256BitVector()) {
15668     unsigned NumElems = VT.getVectorNumElements();
15669     MVT EltVT = VT.getVectorElementType();
15670     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15671
15672     // Extract the two vectors
15673     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15674     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15675
15676     // Recreate the shift amount vectors
15677     SDValue Amt1, Amt2;
15678     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15679       // Constant shift amount
15680       SmallVector<SDValue, 4> Amt1Csts;
15681       SmallVector<SDValue, 4> Amt2Csts;
15682       for (unsigned i = 0; i != NumElems/2; ++i)
15683         Amt1Csts.push_back(Amt->getOperand(i));
15684       for (unsigned i = NumElems/2; i != NumElems; ++i)
15685         Amt2Csts.push_back(Amt->getOperand(i));
15686
15687       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15688       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15689     } else {
15690       // Variable shift amount
15691       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15692       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15693     }
15694
15695     // Issue new vector shifts for the smaller types
15696     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15697     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15698
15699     // Concatenate the result back
15700     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15701   }
15702
15703   return SDValue();
15704 }
15705
15706 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15707   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15708   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15709   // looks for this combo and may remove the "setcc" instruction if the "setcc"
15710   // has only one use.
15711   SDNode *N = Op.getNode();
15712   SDValue LHS = N->getOperand(0);
15713   SDValue RHS = N->getOperand(1);
15714   unsigned BaseOp = 0;
15715   unsigned Cond = 0;
15716   SDLoc DL(Op);
15717   switch (Op.getOpcode()) {
15718   default: llvm_unreachable("Unknown ovf instruction!");
15719   case ISD::SADDO:
15720     // A subtract of one will be selected as a INC. Note that INC doesn't
15721     // set CF, so we can't do this for UADDO.
15722     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15723       if (C->isOne()) {
15724         BaseOp = X86ISD::INC;
15725         Cond = X86::COND_O;
15726         break;
15727       }
15728     BaseOp = X86ISD::ADD;
15729     Cond = X86::COND_O;
15730     break;
15731   case ISD::UADDO:
15732     BaseOp = X86ISD::ADD;
15733     Cond = X86::COND_B;
15734     break;
15735   case ISD::SSUBO:
15736     // A subtract of one will be selected as a DEC. Note that DEC doesn't
15737     // set CF, so we can't do this for USUBO.
15738     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15739       if (C->isOne()) {
15740         BaseOp = X86ISD::DEC;
15741         Cond = X86::COND_O;
15742         break;
15743       }
15744     BaseOp = X86ISD::SUB;
15745     Cond = X86::COND_O;
15746     break;
15747   case ISD::USUBO:
15748     BaseOp = X86ISD::SUB;
15749     Cond = X86::COND_B;
15750     break;
15751   case ISD::SMULO:
15752     BaseOp = X86ISD::SMUL;
15753     Cond = X86::COND_O;
15754     break;
15755   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15756     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15757                                  MVT::i32);
15758     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15759
15760     SDValue SetCC =
15761       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15762                   DAG.getConstant(X86::COND_O, MVT::i32),
15763                   SDValue(Sum.getNode(), 2));
15764
15765     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15766   }
15767   }
15768
15769   // Also sets EFLAGS.
15770   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15771   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15772
15773   SDValue SetCC =
15774     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15775                 DAG.getConstant(Cond, MVT::i32),
15776                 SDValue(Sum.getNode(), 1));
15777
15778   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15779 }
15780
15781 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15782                                                   SelectionDAG &DAG) const {
15783   SDLoc dl(Op);
15784   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15785   MVT VT = Op.getSimpleValueType();
15786
15787   if (!Subtarget->hasSSE2() || !VT.isVector())
15788     return SDValue();
15789
15790   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15791                       ExtraVT.getScalarType().getSizeInBits();
15792
15793   switch (VT.SimpleTy) {
15794     default: return SDValue();
15795     case MVT::v8i32:
15796     case MVT::v16i16:
15797       if (!Subtarget->hasFp256())
15798         return SDValue();
15799       if (!Subtarget->hasInt256()) {
15800         // needs to be split
15801         unsigned NumElems = VT.getVectorNumElements();
15802
15803         // Extract the LHS vectors
15804         SDValue LHS = Op.getOperand(0);
15805         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15806         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15807
15808         MVT EltVT = VT.getVectorElementType();
15809         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15810
15811         EVT ExtraEltVT = ExtraVT.getVectorElementType();
15812         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15813         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15814                                    ExtraNumElems/2);
15815         SDValue Extra = DAG.getValueType(ExtraVT);
15816
15817         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15818         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15819
15820         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15821       }
15822       // fall through
15823     case MVT::v4i32:
15824     case MVT::v8i16: {
15825       SDValue Op0 = Op.getOperand(0);
15826       SDValue Op00 = Op0.getOperand(0);
15827       SDValue Tmp1;
15828       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15829       if (Op0.getOpcode() == ISD::BITCAST &&
15830           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15831         // (sext (vzext x)) -> (vsext x)
15832         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15833         if (Tmp1.getNode()) {
15834           EVT ExtraEltVT = ExtraVT.getVectorElementType();
15835           // This folding is only valid when the in-reg type is a vector of i8,
15836           // i16, or i32.
15837           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15838               ExtraEltVT == MVT::i32) {
15839             SDValue Tmp1Op0 = Tmp1.getOperand(0);
15840             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15841                    "This optimization is invalid without a VZEXT.");
15842             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15843           }
15844           Op0 = Tmp1;
15845         }
15846       }
15847
15848       // If the above didn't work, then just use Shift-Left + Shift-Right.
15849       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15850                                         DAG);
15851       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15852                                         DAG);
15853     }
15854   }
15855 }
15856
15857 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15858                                  SelectionDAG &DAG) {
15859   SDLoc dl(Op);
15860   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15861     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15862   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15863     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15864
15865   // The only fence that needs an instruction is a sequentially-consistent
15866   // cross-thread fence.
15867   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15868     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15869     // no-sse2). There isn't any reason to disable it if the target processor
15870     // supports it.
15871     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15872       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15873
15874     SDValue Chain = Op.getOperand(0);
15875     SDValue Zero = DAG.getConstant(0, MVT::i32);
15876     SDValue Ops[] = {
15877       DAG.getRegister(X86::ESP, MVT::i32), // Base
15878       DAG.getTargetConstant(1, MVT::i8),   // Scale
15879       DAG.getRegister(0, MVT::i32),        // Index
15880       DAG.getTargetConstant(0, MVT::i32),  // Disp
15881       DAG.getRegister(0, MVT::i32),        // Segment.
15882       Zero,
15883       Chain
15884     };
15885     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15886     return SDValue(Res, 0);
15887   }
15888
15889   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15890   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15891 }
15892
15893 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15894                              SelectionDAG &DAG) {
15895   MVT T = Op.getSimpleValueType();
15896   SDLoc DL(Op);
15897   unsigned Reg = 0;
15898   unsigned size = 0;
15899   switch(T.SimpleTy) {
15900   default: llvm_unreachable("Invalid value type!");
15901   case MVT::i8:  Reg = X86::AL;  size = 1; break;
15902   case MVT::i16: Reg = X86::AX;  size = 2; break;
15903   case MVT::i32: Reg = X86::EAX; size = 4; break;
15904   case MVT::i64:
15905     assert(Subtarget->is64Bit() && "Node not type legal!");
15906     Reg = X86::RAX; size = 8;
15907     break;
15908   }
15909   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15910                                   Op.getOperand(2), SDValue());
15911   SDValue Ops[] = { cpIn.getValue(0),
15912                     Op.getOperand(1),
15913                     Op.getOperand(3),
15914                     DAG.getTargetConstant(size, MVT::i8),
15915                     cpIn.getValue(1) };
15916   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15917   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15918   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15919                                            Ops, T, MMO);
15920
15921   SDValue cpOut =
15922     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15923   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15924                                       MVT::i32, cpOut.getValue(2));
15925   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15926                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15927
15928   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15929   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15930   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15931   return SDValue();
15932 }
15933
15934 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15935                             SelectionDAG &DAG) {
15936   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
15937   MVT DstVT = Op.getSimpleValueType();
15938
15939   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
15940     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15941     if (DstVT != MVT::f64)
15942       // This conversion needs to be expanded.
15943       return SDValue();
15944
15945     SDValue InVec = Op->getOperand(0);
15946     SDLoc dl(Op);
15947     unsigned NumElts = SrcVT.getVectorNumElements();
15948     EVT SVT = SrcVT.getVectorElementType();
15949
15950     // Widen the vector in input in the case of MVT::v2i32.
15951     // Example: from MVT::v2i32 to MVT::v4i32.
15952     SmallVector<SDValue, 16> Elts;
15953     for (unsigned i = 0, e = NumElts; i != e; ++i)
15954       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
15955                                  DAG.getIntPtrConstant(i)));
15956
15957     // Explicitly mark the extra elements as Undef.
15958     SDValue Undef = DAG.getUNDEF(SVT);
15959     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
15960       Elts.push_back(Undef);
15961
15962     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15963     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
15964     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
15965     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
15966                        DAG.getIntPtrConstant(0));
15967   }
15968
15969   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
15970          Subtarget->hasMMX() && "Unexpected custom BITCAST");
15971   assert((DstVT == MVT::i64 ||
15972           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
15973          "Unexpected custom BITCAST");
15974   // i64 <=> MMX conversions are Legal.
15975   if (SrcVT==MVT::i64 && DstVT.isVector())
15976     return Op;
15977   if (DstVT==MVT::i64 && SrcVT.isVector())
15978     return Op;
15979   // MMX <=> MMX conversions are Legal.
15980   if (SrcVT.isVector() && DstVT.isVector())
15981     return Op;
15982   // All other conversions need to be expanded.
15983   return SDValue();
15984 }
15985
15986 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
15987   SDNode *Node = Op.getNode();
15988   SDLoc dl(Node);
15989   EVT T = Node->getValueType(0);
15990   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
15991                               DAG.getConstant(0, T), Node->getOperand(2));
15992   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
15993                        cast<AtomicSDNode>(Node)->getMemoryVT(),
15994                        Node->getOperand(0),
15995                        Node->getOperand(1), negOp,
15996                        cast<AtomicSDNode>(Node)->getMemOperand(),
15997                        cast<AtomicSDNode>(Node)->getOrdering(),
15998                        cast<AtomicSDNode>(Node)->getSynchScope());
15999 }
16000
16001 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16002   SDNode *Node = Op.getNode();
16003   SDLoc dl(Node);
16004   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16005
16006   // Convert seq_cst store -> xchg
16007   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16008   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16009   //        (The only way to get a 16-byte store is cmpxchg16b)
16010   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16011   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16012       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16013     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16014                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16015                                  Node->getOperand(0),
16016                                  Node->getOperand(1), Node->getOperand(2),
16017                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16018                                  cast<AtomicSDNode>(Node)->getOrdering(),
16019                                  cast<AtomicSDNode>(Node)->getSynchScope());
16020     return Swap.getValue(1);
16021   }
16022   // Other atomic stores have a simple pattern.
16023   return Op;
16024 }
16025
16026 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16027   EVT VT = Op.getNode()->getSimpleValueType(0);
16028
16029   // Let legalize expand this if it isn't a legal type yet.
16030   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16031     return SDValue();
16032
16033   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16034
16035   unsigned Opc;
16036   bool ExtraOp = false;
16037   switch (Op.getOpcode()) {
16038   default: llvm_unreachable("Invalid code");
16039   case ISD::ADDC: Opc = X86ISD::ADD; break;
16040   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16041   case ISD::SUBC: Opc = X86ISD::SUB; break;
16042   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16043   }
16044
16045   if (!ExtraOp)
16046     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16047                        Op.getOperand(1));
16048   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16049                      Op.getOperand(1), Op.getOperand(2));
16050 }
16051
16052 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16053                             SelectionDAG &DAG) {
16054   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16055
16056   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16057   // which returns the values as { float, float } (in XMM0) or
16058   // { double, double } (which is returned in XMM0, XMM1).
16059   SDLoc dl(Op);
16060   SDValue Arg = Op.getOperand(0);
16061   EVT ArgVT = Arg.getValueType();
16062   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16063
16064   TargetLowering::ArgListTy Args;
16065   TargetLowering::ArgListEntry Entry;
16066
16067   Entry.Node = Arg;
16068   Entry.Ty = ArgTy;
16069   Entry.isSExt = false;
16070   Entry.isZExt = false;
16071   Args.push_back(Entry);
16072
16073   bool isF64 = ArgVT == MVT::f64;
16074   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16075   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16076   // the results are returned via SRet in memory.
16077   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16078   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16079   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16080
16081   Type *RetTy = isF64
16082     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16083     : (Type*)VectorType::get(ArgTy, 4);
16084
16085   TargetLowering::CallLoweringInfo CLI(DAG);
16086   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16087     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16088
16089   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16090
16091   if (isF64)
16092     // Returned in xmm0 and xmm1.
16093     return CallResult.first;
16094
16095   // Returned in bits 0:31 and 32:64 xmm0.
16096   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16097                                CallResult.first, DAG.getIntPtrConstant(0));
16098   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16099                                CallResult.first, DAG.getIntPtrConstant(1));
16100   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16101   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16102 }
16103
16104 /// LowerOperation - Provide custom lowering hooks for some operations.
16105 ///
16106 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16107   switch (Op.getOpcode()) {
16108   default: llvm_unreachable("Should not custom lower this!");
16109   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16110   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16111   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16112     return LowerCMP_SWAP(Op, Subtarget, DAG);
16113   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16114   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16115   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16116   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16117   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16118   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16119   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16120   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16121   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16122   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16123   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16124   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16125   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16126   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16127   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16128   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16129   case ISD::SHL_PARTS:
16130   case ISD::SRA_PARTS:
16131   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16132   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16133   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16134   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16135   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16136   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16137   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16138   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16139   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16140   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16141   case ISD::FABS:               return LowerFABS(Op, DAG);
16142   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16143   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16144   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16145   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16146   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16147   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16148   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16149   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16150   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16151   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16152   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16153   case ISD::INTRINSIC_VOID:
16154   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16155   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16156   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16157   case ISD::FRAME_TO_ARGS_OFFSET:
16158                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16159   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16160   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16161   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16162   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16163   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16164   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16165   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16166   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16167   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16168   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16169   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16170   case ISD::UMUL_LOHI:
16171   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16172   case ISD::SRA:
16173   case ISD::SRL:
16174   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16175   case ISD::SADDO:
16176   case ISD::UADDO:
16177   case ISD::SSUBO:
16178   case ISD::USUBO:
16179   case ISD::SMULO:
16180   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16181   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16182   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16183   case ISD::ADDC:
16184   case ISD::ADDE:
16185   case ISD::SUBC:
16186   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16187   case ISD::ADD:                return LowerADD(Op, DAG);
16188   case ISD::SUB:                return LowerSUB(Op, DAG);
16189   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16190   }
16191 }
16192
16193 static void ReplaceATOMIC_LOAD(SDNode *Node,
16194                                SmallVectorImpl<SDValue> &Results,
16195                                SelectionDAG &DAG) {
16196   SDLoc dl(Node);
16197   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16198
16199   // Convert wide load -> cmpxchg8b/cmpxchg16b
16200   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16201   //        (The only way to get a 16-byte load is cmpxchg16b)
16202   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16203   SDValue Zero = DAG.getConstant(0, VT);
16204   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16205   SDValue Swap =
16206       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16207                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16208                            cast<AtomicSDNode>(Node)->getMemOperand(),
16209                            cast<AtomicSDNode>(Node)->getOrdering(),
16210                            cast<AtomicSDNode>(Node)->getOrdering(),
16211                            cast<AtomicSDNode>(Node)->getSynchScope());
16212   Results.push_back(Swap.getValue(0));
16213   Results.push_back(Swap.getValue(2));
16214 }
16215
16216 /// ReplaceNodeResults - Replace a node with an illegal result type
16217 /// with a new node built out of custom code.
16218 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16219                                            SmallVectorImpl<SDValue>&Results,
16220                                            SelectionDAG &DAG) const {
16221   SDLoc dl(N);
16222   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16223   switch (N->getOpcode()) {
16224   default:
16225     llvm_unreachable("Do not know how to custom type legalize this operation!");
16226   case ISD::SIGN_EXTEND_INREG:
16227   case ISD::ADDC:
16228   case ISD::ADDE:
16229   case ISD::SUBC:
16230   case ISD::SUBE:
16231     // We don't want to expand or promote these.
16232     return;
16233   case ISD::SDIV:
16234   case ISD::UDIV:
16235   case ISD::SREM:
16236   case ISD::UREM:
16237   case ISD::SDIVREM:
16238   case ISD::UDIVREM: {
16239     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16240     Results.push_back(V);
16241     return;
16242   }
16243   case ISD::FP_TO_SINT:
16244   case ISD::FP_TO_UINT: {
16245     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16246
16247     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16248       return;
16249
16250     std::pair<SDValue,SDValue> Vals =
16251         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16252     SDValue FIST = Vals.first, StackSlot = Vals.second;
16253     if (FIST.getNode()) {
16254       EVT VT = N->getValueType(0);
16255       // Return a load from the stack slot.
16256       if (StackSlot.getNode())
16257         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16258                                       MachinePointerInfo(),
16259                                       false, false, false, 0));
16260       else
16261         Results.push_back(FIST);
16262     }
16263     return;
16264   }
16265   case ISD::UINT_TO_FP: {
16266     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16267     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16268         N->getValueType(0) != MVT::v2f32)
16269       return;
16270     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16271                                  N->getOperand(0));
16272     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16273                                      MVT::f64);
16274     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16275     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16276                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16277     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16278     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16279     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16280     return;
16281   }
16282   case ISD::FP_ROUND: {
16283     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16284         return;
16285     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16286     Results.push_back(V);
16287     return;
16288   }
16289   case ISD::INTRINSIC_W_CHAIN: {
16290     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16291     switch (IntNo) {
16292     default : llvm_unreachable("Do not know how to custom type "
16293                                "legalize this intrinsic operation!");
16294     case Intrinsic::x86_rdtsc:
16295       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16296                                      Results);
16297     case Intrinsic::x86_rdtscp:
16298       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16299                                      Results);
16300     case Intrinsic::x86_rdpmc:
16301       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16302     }
16303   }
16304   case ISD::READCYCLECOUNTER: {
16305     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16306                                    Results);
16307   }
16308   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16309     EVT T = N->getValueType(0);
16310     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16311     bool Regs64bit = T == MVT::i128;
16312     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16313     SDValue cpInL, cpInH;
16314     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16315                         DAG.getConstant(0, HalfT));
16316     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16317                         DAG.getConstant(1, HalfT));
16318     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16319                              Regs64bit ? X86::RAX : X86::EAX,
16320                              cpInL, SDValue());
16321     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16322                              Regs64bit ? X86::RDX : X86::EDX,
16323                              cpInH, cpInL.getValue(1));
16324     SDValue swapInL, swapInH;
16325     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16326                           DAG.getConstant(0, HalfT));
16327     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16328                           DAG.getConstant(1, HalfT));
16329     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16330                                Regs64bit ? X86::RBX : X86::EBX,
16331                                swapInL, cpInH.getValue(1));
16332     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16333                                Regs64bit ? X86::RCX : X86::ECX,
16334                                swapInH, swapInL.getValue(1));
16335     SDValue Ops[] = { swapInH.getValue(0),
16336                       N->getOperand(1),
16337                       swapInH.getValue(1) };
16338     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16339     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16340     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16341                                   X86ISD::LCMPXCHG8_DAG;
16342     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16343     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16344                                         Regs64bit ? X86::RAX : X86::EAX,
16345                                         HalfT, Result.getValue(1));
16346     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16347                                         Regs64bit ? X86::RDX : X86::EDX,
16348                                         HalfT, cpOutL.getValue(2));
16349     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16350
16351     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16352                                         MVT::i32, cpOutH.getValue(2));
16353     SDValue Success =
16354         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16355                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16356     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16357
16358     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16359     Results.push_back(Success);
16360     Results.push_back(EFLAGS.getValue(1));
16361     return;
16362   }
16363   case ISD::ATOMIC_SWAP:
16364   case ISD::ATOMIC_LOAD_ADD:
16365   case ISD::ATOMIC_LOAD_SUB:
16366   case ISD::ATOMIC_LOAD_AND:
16367   case ISD::ATOMIC_LOAD_OR:
16368   case ISD::ATOMIC_LOAD_XOR:
16369   case ISD::ATOMIC_LOAD_NAND:
16370   case ISD::ATOMIC_LOAD_MIN:
16371   case ISD::ATOMIC_LOAD_MAX:
16372   case ISD::ATOMIC_LOAD_UMIN:
16373   case ISD::ATOMIC_LOAD_UMAX:
16374     // Delegate to generic TypeLegalization. Situations we can really handle
16375     // should have already been dealt with by X86AtomicExpand.cpp.
16376     break;
16377   case ISD::ATOMIC_LOAD: {
16378     ReplaceATOMIC_LOAD(N, Results, DAG);
16379     return;
16380   }
16381   case ISD::BITCAST: {
16382     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16383     EVT DstVT = N->getValueType(0);
16384     EVT SrcVT = N->getOperand(0)->getValueType(0);
16385
16386     if (SrcVT != MVT::f64 ||
16387         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16388       return;
16389
16390     unsigned NumElts = DstVT.getVectorNumElements();
16391     EVT SVT = DstVT.getVectorElementType();
16392     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16393     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16394                                    MVT::v2f64, N->getOperand(0));
16395     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16396
16397     SmallVector<SDValue, 8> Elts;
16398     for (unsigned i = 0, e = NumElts; i != e; ++i)
16399       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16400                                    ToVecInt, DAG.getIntPtrConstant(i)));
16401
16402     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16403   }
16404   }
16405 }
16406
16407 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16408   switch (Opcode) {
16409   default: return nullptr;
16410   case X86ISD::BSF:                return "X86ISD::BSF";
16411   case X86ISD::BSR:                return "X86ISD::BSR";
16412   case X86ISD::SHLD:               return "X86ISD::SHLD";
16413   case X86ISD::SHRD:               return "X86ISD::SHRD";
16414   case X86ISD::FAND:               return "X86ISD::FAND";
16415   case X86ISD::FANDN:              return "X86ISD::FANDN";
16416   case X86ISD::FOR:                return "X86ISD::FOR";
16417   case X86ISD::FXOR:               return "X86ISD::FXOR";
16418   case X86ISD::FSRL:               return "X86ISD::FSRL";
16419   case X86ISD::FILD:               return "X86ISD::FILD";
16420   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16421   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16422   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16423   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16424   case X86ISD::FLD:                return "X86ISD::FLD";
16425   case X86ISD::FST:                return "X86ISD::FST";
16426   case X86ISD::CALL:               return "X86ISD::CALL";
16427   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16428   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16429   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16430   case X86ISD::BT:                 return "X86ISD::BT";
16431   case X86ISD::CMP:                return "X86ISD::CMP";
16432   case X86ISD::COMI:               return "X86ISD::COMI";
16433   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16434   case X86ISD::CMPM:               return "X86ISD::CMPM";
16435   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16436   case X86ISD::SETCC:              return "X86ISD::SETCC";
16437   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16438   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16439   case X86ISD::CMOV:               return "X86ISD::CMOV";
16440   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16441   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16442   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16443   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16444   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16445   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16446   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16447   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16448   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16449   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16450   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16451   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16452   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16453   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16454   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16455   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16456   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16457   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16458   case X86ISD::HADD:               return "X86ISD::HADD";
16459   case X86ISD::HSUB:               return "X86ISD::HSUB";
16460   case X86ISD::FHADD:              return "X86ISD::FHADD";
16461   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16462   case X86ISD::UMAX:               return "X86ISD::UMAX";
16463   case X86ISD::UMIN:               return "X86ISD::UMIN";
16464   case X86ISD::SMAX:               return "X86ISD::SMAX";
16465   case X86ISD::SMIN:               return "X86ISD::SMIN";
16466   case X86ISD::FMAX:               return "X86ISD::FMAX";
16467   case X86ISD::FMIN:               return "X86ISD::FMIN";
16468   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16469   case X86ISD::FMINC:              return "X86ISD::FMINC";
16470   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16471   case X86ISD::FRCP:               return "X86ISD::FRCP";
16472   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16473   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16474   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16475   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16476   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16477   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16478   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16479   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16480   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16481   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16482   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16483   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16484   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16485   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16486   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16487   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16488   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16489   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16490   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16491   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16492   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16493   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16494   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16495   case X86ISD::VSHL:               return "X86ISD::VSHL";
16496   case X86ISD::VSRL:               return "X86ISD::VSRL";
16497   case X86ISD::VSRA:               return "X86ISD::VSRA";
16498   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16499   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16500   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16501   case X86ISD::CMPP:               return "X86ISD::CMPP";
16502   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16503   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16504   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16505   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16506   case X86ISD::ADD:                return "X86ISD::ADD";
16507   case X86ISD::SUB:                return "X86ISD::SUB";
16508   case X86ISD::ADC:                return "X86ISD::ADC";
16509   case X86ISD::SBB:                return "X86ISD::SBB";
16510   case X86ISD::SMUL:               return "X86ISD::SMUL";
16511   case X86ISD::UMUL:               return "X86ISD::UMUL";
16512   case X86ISD::INC:                return "X86ISD::INC";
16513   case X86ISD::DEC:                return "X86ISD::DEC";
16514   case X86ISD::OR:                 return "X86ISD::OR";
16515   case X86ISD::XOR:                return "X86ISD::XOR";
16516   case X86ISD::AND:                return "X86ISD::AND";
16517   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16518   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16519   case X86ISD::PTEST:              return "X86ISD::PTEST";
16520   case X86ISD::TESTP:              return "X86ISD::TESTP";
16521   case X86ISD::TESTM:              return "X86ISD::TESTM";
16522   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16523   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16524   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16525   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16526   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16527   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16528   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16529   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16530   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16531   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16532   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16533   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16534   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16535   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16536   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16537   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16538   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16539   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16540   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16541   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16542   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16543   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16544   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16545   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16546   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16547   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16548   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16549   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16550   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16551   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16552   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16553   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16554   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16555   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16556   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16557   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16558   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16559   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16560   case X86ISD::SAHF:               return "X86ISD::SAHF";
16561   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16562   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16563   case X86ISD::FMADD:              return "X86ISD::FMADD";
16564   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16565   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16566   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16567   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16568   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16569   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16570   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16571   case X86ISD::XTEST:              return "X86ISD::XTEST";
16572   }
16573 }
16574
16575 // isLegalAddressingMode - Return true if the addressing mode represented
16576 // by AM is legal for this target, for a load/store of the specified type.
16577 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16578                                               Type *Ty) const {
16579   // X86 supports extremely general addressing modes.
16580   CodeModel::Model M = getTargetMachine().getCodeModel();
16581   Reloc::Model R = getTargetMachine().getRelocationModel();
16582
16583   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16584   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16585     return false;
16586
16587   if (AM.BaseGV) {
16588     unsigned GVFlags =
16589       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16590
16591     // If a reference to this global requires an extra load, we can't fold it.
16592     if (isGlobalStubReference(GVFlags))
16593       return false;
16594
16595     // If BaseGV requires a register for the PIC base, we cannot also have a
16596     // BaseReg specified.
16597     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16598       return false;
16599
16600     // If lower 4G is not available, then we must use rip-relative addressing.
16601     if ((M != CodeModel::Small || R != Reloc::Static) &&
16602         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16603       return false;
16604   }
16605
16606   switch (AM.Scale) {
16607   case 0:
16608   case 1:
16609   case 2:
16610   case 4:
16611   case 8:
16612     // These scales always work.
16613     break;
16614   case 3:
16615   case 5:
16616   case 9:
16617     // These scales are formed with basereg+scalereg.  Only accept if there is
16618     // no basereg yet.
16619     if (AM.HasBaseReg)
16620       return false;
16621     break;
16622   default:  // Other stuff never works.
16623     return false;
16624   }
16625
16626   return true;
16627 }
16628
16629 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16630   unsigned Bits = Ty->getScalarSizeInBits();
16631
16632   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16633   // particularly cheaper than those without.
16634   if (Bits == 8)
16635     return false;
16636
16637   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16638   // variable shifts just as cheap as scalar ones.
16639   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16640     return false;
16641
16642   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16643   // fully general vector.
16644   return true;
16645 }
16646
16647 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16648   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16649     return false;
16650   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16651   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16652   return NumBits1 > NumBits2;
16653 }
16654
16655 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16656   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16657     return false;
16658
16659   if (!isTypeLegal(EVT::getEVT(Ty1)))
16660     return false;
16661
16662   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16663
16664   // Assuming the caller doesn't have a zeroext or signext return parameter,
16665   // truncation all the way down to i1 is valid.
16666   return true;
16667 }
16668
16669 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16670   return isInt<32>(Imm);
16671 }
16672
16673 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16674   // Can also use sub to handle negated immediates.
16675   return isInt<32>(Imm);
16676 }
16677
16678 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16679   if (!VT1.isInteger() || !VT2.isInteger())
16680     return false;
16681   unsigned NumBits1 = VT1.getSizeInBits();
16682   unsigned NumBits2 = VT2.getSizeInBits();
16683   return NumBits1 > NumBits2;
16684 }
16685
16686 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16687   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16688   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16689 }
16690
16691 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16692   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16693   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16694 }
16695
16696 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16697   EVT VT1 = Val.getValueType();
16698   if (isZExtFree(VT1, VT2))
16699     return true;
16700
16701   if (Val.getOpcode() != ISD::LOAD)
16702     return false;
16703
16704   if (!VT1.isSimple() || !VT1.isInteger() ||
16705       !VT2.isSimple() || !VT2.isInteger())
16706     return false;
16707
16708   switch (VT1.getSimpleVT().SimpleTy) {
16709   default: break;
16710   case MVT::i8:
16711   case MVT::i16:
16712   case MVT::i32:
16713     // X86 has 8, 16, and 32-bit zero-extending loads.
16714     return true;
16715   }
16716
16717   return false;
16718 }
16719
16720 bool
16721 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16722   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16723     return false;
16724
16725   VT = VT.getScalarType();
16726
16727   if (!VT.isSimple())
16728     return false;
16729
16730   switch (VT.getSimpleVT().SimpleTy) {
16731   case MVT::f32:
16732   case MVT::f64:
16733     return true;
16734   default:
16735     break;
16736   }
16737
16738   return false;
16739 }
16740
16741 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16742   // i16 instructions are longer (0x66 prefix) and potentially slower.
16743   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16744 }
16745
16746 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16747 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16748 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16749 /// are assumed to be legal.
16750 bool
16751 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16752                                       EVT VT) const {
16753   if (!VT.isSimple())
16754     return false;
16755
16756   MVT SVT = VT.getSimpleVT();
16757
16758   // Very little shuffling can be done for 64-bit vectors right now.
16759   if (VT.getSizeInBits() == 64)
16760     return false;
16761
16762   // If this is a single-input shuffle with no 128 bit lane crossings we can
16763   // lower it into pshufb.
16764   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16765       (SVT.is256BitVector() && Subtarget->hasInt256())) {
16766     bool isLegal = true;
16767     for (unsigned I = 0, E = M.size(); I != E; ++I) {
16768       if (M[I] >= (int)SVT.getVectorNumElements() ||
16769           ShuffleCrosses128bitLane(SVT, I, M[I])) {
16770         isLegal = false;
16771         break;
16772       }
16773     }
16774     if (isLegal)
16775       return true;
16776   }
16777
16778   // FIXME: blends, shifts.
16779   return (SVT.getVectorNumElements() == 2 ||
16780           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16781           isMOVLMask(M, SVT) ||
16782           isSHUFPMask(M, SVT) ||
16783           isPSHUFDMask(M, SVT) ||
16784           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16785           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16786           isPALIGNRMask(M, SVT, Subtarget) ||
16787           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16788           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16789           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16790           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16791           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16792 }
16793
16794 bool
16795 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16796                                           EVT VT) const {
16797   if (!VT.isSimple())
16798     return false;
16799
16800   MVT SVT = VT.getSimpleVT();
16801   unsigned NumElts = SVT.getVectorNumElements();
16802   // FIXME: This collection of masks seems suspect.
16803   if (NumElts == 2)
16804     return true;
16805   if (NumElts == 4 && SVT.is128BitVector()) {
16806     return (isMOVLMask(Mask, SVT)  ||
16807             isCommutedMOVLMask(Mask, SVT, true) ||
16808             isSHUFPMask(Mask, SVT) ||
16809             isSHUFPMask(Mask, SVT, /* Commuted */ true));
16810   }
16811   return false;
16812 }
16813
16814 //===----------------------------------------------------------------------===//
16815 //                           X86 Scheduler Hooks
16816 //===----------------------------------------------------------------------===//
16817
16818 /// Utility function to emit xbegin specifying the start of an RTM region.
16819 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16820                                      const TargetInstrInfo *TII) {
16821   DebugLoc DL = MI->getDebugLoc();
16822
16823   const BasicBlock *BB = MBB->getBasicBlock();
16824   MachineFunction::iterator I = MBB;
16825   ++I;
16826
16827   // For the v = xbegin(), we generate
16828   //
16829   // thisMBB:
16830   //  xbegin sinkMBB
16831   //
16832   // mainMBB:
16833   //  eax = -1
16834   //
16835   // sinkMBB:
16836   //  v = eax
16837
16838   MachineBasicBlock *thisMBB = MBB;
16839   MachineFunction *MF = MBB->getParent();
16840   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16841   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16842   MF->insert(I, mainMBB);
16843   MF->insert(I, sinkMBB);
16844
16845   // Transfer the remainder of BB and its successor edges to sinkMBB.
16846   sinkMBB->splice(sinkMBB->begin(), MBB,
16847                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16848   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16849
16850   // thisMBB:
16851   //  xbegin sinkMBB
16852   //  # fallthrough to mainMBB
16853   //  # abortion to sinkMBB
16854   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16855   thisMBB->addSuccessor(mainMBB);
16856   thisMBB->addSuccessor(sinkMBB);
16857
16858   // mainMBB:
16859   //  EAX = -1
16860   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16861   mainMBB->addSuccessor(sinkMBB);
16862
16863   // sinkMBB:
16864   // EAX is live into the sinkMBB
16865   sinkMBB->addLiveIn(X86::EAX);
16866   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16867           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16868     .addReg(X86::EAX);
16869
16870   MI->eraseFromParent();
16871   return sinkMBB;
16872 }
16873
16874 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16875 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16876 // in the .td file.
16877 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16878                                        const TargetInstrInfo *TII) {
16879   unsigned Opc;
16880   switch (MI->getOpcode()) {
16881   default: llvm_unreachable("illegal opcode!");
16882   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16883   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16884   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16885   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16886   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16887   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16888   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16889   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16890   }
16891
16892   DebugLoc dl = MI->getDebugLoc();
16893   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16894
16895   unsigned NumArgs = MI->getNumOperands();
16896   for (unsigned i = 1; i < NumArgs; ++i) {
16897     MachineOperand &Op = MI->getOperand(i);
16898     if (!(Op.isReg() && Op.isImplicit()))
16899       MIB.addOperand(Op);
16900   }
16901   if (MI->hasOneMemOperand())
16902     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16903
16904   BuildMI(*BB, MI, dl,
16905     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16906     .addReg(X86::XMM0);
16907
16908   MI->eraseFromParent();
16909   return BB;
16910 }
16911
16912 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16913 // defs in an instruction pattern
16914 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16915                                        const TargetInstrInfo *TII) {
16916   unsigned Opc;
16917   switch (MI->getOpcode()) {
16918   default: llvm_unreachable("illegal opcode!");
16919   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16920   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16921   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16922   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16923   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16924   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16925   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16926   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16927   }
16928
16929   DebugLoc dl = MI->getDebugLoc();
16930   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16931
16932   unsigned NumArgs = MI->getNumOperands(); // remove the results
16933   for (unsigned i = 1; i < NumArgs; ++i) {
16934     MachineOperand &Op = MI->getOperand(i);
16935     if (!(Op.isReg() && Op.isImplicit()))
16936       MIB.addOperand(Op);
16937   }
16938   if (MI->hasOneMemOperand())
16939     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16940
16941   BuildMI(*BB, MI, dl,
16942     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16943     .addReg(X86::ECX);
16944
16945   MI->eraseFromParent();
16946   return BB;
16947 }
16948
16949 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16950                                        const TargetInstrInfo *TII,
16951                                        const X86Subtarget* Subtarget) {
16952   DebugLoc dl = MI->getDebugLoc();
16953
16954   // Address into RAX/EAX, other two args into ECX, EDX.
16955   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16956   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16957   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16958   for (int i = 0; i < X86::AddrNumOperands; ++i)
16959     MIB.addOperand(MI->getOperand(i));
16960
16961   unsigned ValOps = X86::AddrNumOperands;
16962   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16963     .addReg(MI->getOperand(ValOps).getReg());
16964   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16965     .addReg(MI->getOperand(ValOps+1).getReg());
16966
16967   // The instruction doesn't actually take any operands though.
16968   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16969
16970   MI->eraseFromParent(); // The pseudo is gone now.
16971   return BB;
16972 }
16973
16974 MachineBasicBlock *
16975 X86TargetLowering::EmitVAARG64WithCustomInserter(
16976                    MachineInstr *MI,
16977                    MachineBasicBlock *MBB) const {
16978   // Emit va_arg instruction on X86-64.
16979
16980   // Operands to this pseudo-instruction:
16981   // 0  ) Output        : destination address (reg)
16982   // 1-5) Input         : va_list address (addr, i64mem)
16983   // 6  ) ArgSize       : Size (in bytes) of vararg type
16984   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16985   // 8  ) Align         : Alignment of type
16986   // 9  ) EFLAGS (implicit-def)
16987
16988   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16989   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16990
16991   unsigned DestReg = MI->getOperand(0).getReg();
16992   MachineOperand &Base = MI->getOperand(1);
16993   MachineOperand &Scale = MI->getOperand(2);
16994   MachineOperand &Index = MI->getOperand(3);
16995   MachineOperand &Disp = MI->getOperand(4);
16996   MachineOperand &Segment = MI->getOperand(5);
16997   unsigned ArgSize = MI->getOperand(6).getImm();
16998   unsigned ArgMode = MI->getOperand(7).getImm();
16999   unsigned Align = MI->getOperand(8).getImm();
17000
17001   // Memory Reference
17002   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17003   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17004   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17005
17006   // Machine Information
17007   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17008   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17009   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17010   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17011   DebugLoc DL = MI->getDebugLoc();
17012
17013   // struct va_list {
17014   //   i32   gp_offset
17015   //   i32   fp_offset
17016   //   i64   overflow_area (address)
17017   //   i64   reg_save_area (address)
17018   // }
17019   // sizeof(va_list) = 24
17020   // alignment(va_list) = 8
17021
17022   unsigned TotalNumIntRegs = 6;
17023   unsigned TotalNumXMMRegs = 8;
17024   bool UseGPOffset = (ArgMode == 1);
17025   bool UseFPOffset = (ArgMode == 2);
17026   unsigned MaxOffset = TotalNumIntRegs * 8 +
17027                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17028
17029   /* Align ArgSize to a multiple of 8 */
17030   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17031   bool NeedsAlign = (Align > 8);
17032
17033   MachineBasicBlock *thisMBB = MBB;
17034   MachineBasicBlock *overflowMBB;
17035   MachineBasicBlock *offsetMBB;
17036   MachineBasicBlock *endMBB;
17037
17038   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17039   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17040   unsigned OffsetReg = 0;
17041
17042   if (!UseGPOffset && !UseFPOffset) {
17043     // If we only pull from the overflow region, we don't create a branch.
17044     // We don't need to alter control flow.
17045     OffsetDestReg = 0; // unused
17046     OverflowDestReg = DestReg;
17047
17048     offsetMBB = nullptr;
17049     overflowMBB = thisMBB;
17050     endMBB = thisMBB;
17051   } else {
17052     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17053     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17054     // If not, pull from overflow_area. (branch to overflowMBB)
17055     //
17056     //       thisMBB
17057     //         |     .
17058     //         |        .
17059     //     offsetMBB   overflowMBB
17060     //         |        .
17061     //         |     .
17062     //        endMBB
17063
17064     // Registers for the PHI in endMBB
17065     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17066     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17067
17068     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17069     MachineFunction *MF = MBB->getParent();
17070     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17071     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17072     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17073
17074     MachineFunction::iterator MBBIter = MBB;
17075     ++MBBIter;
17076
17077     // Insert the new basic blocks
17078     MF->insert(MBBIter, offsetMBB);
17079     MF->insert(MBBIter, overflowMBB);
17080     MF->insert(MBBIter, endMBB);
17081
17082     // Transfer the remainder of MBB and its successor edges to endMBB.
17083     endMBB->splice(endMBB->begin(), thisMBB,
17084                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17085     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17086
17087     // Make offsetMBB and overflowMBB successors of thisMBB
17088     thisMBB->addSuccessor(offsetMBB);
17089     thisMBB->addSuccessor(overflowMBB);
17090
17091     // endMBB is a successor of both offsetMBB and overflowMBB
17092     offsetMBB->addSuccessor(endMBB);
17093     overflowMBB->addSuccessor(endMBB);
17094
17095     // Load the offset value into a register
17096     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17097     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17098       .addOperand(Base)
17099       .addOperand(Scale)
17100       .addOperand(Index)
17101       .addDisp(Disp, UseFPOffset ? 4 : 0)
17102       .addOperand(Segment)
17103       .setMemRefs(MMOBegin, MMOEnd);
17104
17105     // Check if there is enough room left to pull this argument.
17106     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17107       .addReg(OffsetReg)
17108       .addImm(MaxOffset + 8 - ArgSizeA8);
17109
17110     // Branch to "overflowMBB" if offset >= max
17111     // Fall through to "offsetMBB" otherwise
17112     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17113       .addMBB(overflowMBB);
17114   }
17115
17116   // In offsetMBB, emit code to use the reg_save_area.
17117   if (offsetMBB) {
17118     assert(OffsetReg != 0);
17119
17120     // Read the reg_save_area address.
17121     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17122     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17123       .addOperand(Base)
17124       .addOperand(Scale)
17125       .addOperand(Index)
17126       .addDisp(Disp, 16)
17127       .addOperand(Segment)
17128       .setMemRefs(MMOBegin, MMOEnd);
17129
17130     // Zero-extend the offset
17131     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17132       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17133         .addImm(0)
17134         .addReg(OffsetReg)
17135         .addImm(X86::sub_32bit);
17136
17137     // Add the offset to the reg_save_area to get the final address.
17138     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17139       .addReg(OffsetReg64)
17140       .addReg(RegSaveReg);
17141
17142     // Compute the offset for the next argument
17143     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17144     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17145       .addReg(OffsetReg)
17146       .addImm(UseFPOffset ? 16 : 8);
17147
17148     // Store it back into the va_list.
17149     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17150       .addOperand(Base)
17151       .addOperand(Scale)
17152       .addOperand(Index)
17153       .addDisp(Disp, UseFPOffset ? 4 : 0)
17154       .addOperand(Segment)
17155       .addReg(NextOffsetReg)
17156       .setMemRefs(MMOBegin, MMOEnd);
17157
17158     // Jump to endMBB
17159     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17160       .addMBB(endMBB);
17161   }
17162
17163   //
17164   // Emit code to use overflow area
17165   //
17166
17167   // Load the overflow_area address into a register.
17168   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17169   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17170     .addOperand(Base)
17171     .addOperand(Scale)
17172     .addOperand(Index)
17173     .addDisp(Disp, 8)
17174     .addOperand(Segment)
17175     .setMemRefs(MMOBegin, MMOEnd);
17176
17177   // If we need to align it, do so. Otherwise, just copy the address
17178   // to OverflowDestReg.
17179   if (NeedsAlign) {
17180     // Align the overflow address
17181     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17182     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17183
17184     // aligned_addr = (addr + (align-1)) & ~(align-1)
17185     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17186       .addReg(OverflowAddrReg)
17187       .addImm(Align-1);
17188
17189     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17190       .addReg(TmpReg)
17191       .addImm(~(uint64_t)(Align-1));
17192   } else {
17193     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17194       .addReg(OverflowAddrReg);
17195   }
17196
17197   // Compute the next overflow address after this argument.
17198   // (the overflow address should be kept 8-byte aligned)
17199   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17200   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17201     .addReg(OverflowDestReg)
17202     .addImm(ArgSizeA8);
17203
17204   // Store the new overflow address.
17205   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17206     .addOperand(Base)
17207     .addOperand(Scale)
17208     .addOperand(Index)
17209     .addDisp(Disp, 8)
17210     .addOperand(Segment)
17211     .addReg(NextAddrReg)
17212     .setMemRefs(MMOBegin, MMOEnd);
17213
17214   // If we branched, emit the PHI to the front of endMBB.
17215   if (offsetMBB) {
17216     BuildMI(*endMBB, endMBB->begin(), DL,
17217             TII->get(X86::PHI), DestReg)
17218       .addReg(OffsetDestReg).addMBB(offsetMBB)
17219       .addReg(OverflowDestReg).addMBB(overflowMBB);
17220   }
17221
17222   // Erase the pseudo instruction
17223   MI->eraseFromParent();
17224
17225   return endMBB;
17226 }
17227
17228 MachineBasicBlock *
17229 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17230                                                  MachineInstr *MI,
17231                                                  MachineBasicBlock *MBB) const {
17232   // Emit code to save XMM registers to the stack. The ABI says that the
17233   // number of registers to save is given in %al, so it's theoretically
17234   // possible to do an indirect jump trick to avoid saving all of them,
17235   // however this code takes a simpler approach and just executes all
17236   // of the stores if %al is non-zero. It's less code, and it's probably
17237   // easier on the hardware branch predictor, and stores aren't all that
17238   // expensive anyway.
17239
17240   // Create the new basic blocks. One block contains all the XMM stores,
17241   // and one block is the final destination regardless of whether any
17242   // stores were performed.
17243   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17244   MachineFunction *F = MBB->getParent();
17245   MachineFunction::iterator MBBIter = MBB;
17246   ++MBBIter;
17247   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17248   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17249   F->insert(MBBIter, XMMSaveMBB);
17250   F->insert(MBBIter, EndMBB);
17251
17252   // Transfer the remainder of MBB and its successor edges to EndMBB.
17253   EndMBB->splice(EndMBB->begin(), MBB,
17254                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17255   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17256
17257   // The original block will now fall through to the XMM save block.
17258   MBB->addSuccessor(XMMSaveMBB);
17259   // The XMMSaveMBB will fall through to the end block.
17260   XMMSaveMBB->addSuccessor(EndMBB);
17261
17262   // Now add the instructions.
17263   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17264   DebugLoc DL = MI->getDebugLoc();
17265
17266   unsigned CountReg = MI->getOperand(0).getReg();
17267   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17268   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17269
17270   if (!Subtarget->isTargetWin64()) {
17271     // If %al is 0, branch around the XMM save block.
17272     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17273     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17274     MBB->addSuccessor(EndMBB);
17275   }
17276
17277   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17278   // that was just emitted, but clearly shouldn't be "saved".
17279   assert((MI->getNumOperands() <= 3 ||
17280           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17281           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17282          && "Expected last argument to be EFLAGS");
17283   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17284   // In the XMM save block, save all the XMM argument registers.
17285   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17286     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17287     MachineMemOperand *MMO =
17288       F->getMachineMemOperand(
17289           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17290         MachineMemOperand::MOStore,
17291         /*Size=*/16, /*Align=*/16);
17292     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17293       .addFrameIndex(RegSaveFrameIndex)
17294       .addImm(/*Scale=*/1)
17295       .addReg(/*IndexReg=*/0)
17296       .addImm(/*Disp=*/Offset)
17297       .addReg(/*Segment=*/0)
17298       .addReg(MI->getOperand(i).getReg())
17299       .addMemOperand(MMO);
17300   }
17301
17302   MI->eraseFromParent();   // The pseudo instruction is gone now.
17303
17304   return EndMBB;
17305 }
17306
17307 // The EFLAGS operand of SelectItr might be missing a kill marker
17308 // because there were multiple uses of EFLAGS, and ISel didn't know
17309 // which to mark. Figure out whether SelectItr should have had a
17310 // kill marker, and set it if it should. Returns the correct kill
17311 // marker value.
17312 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17313                                      MachineBasicBlock* BB,
17314                                      const TargetRegisterInfo* TRI) {
17315   // Scan forward through BB for a use/def of EFLAGS.
17316   MachineBasicBlock::iterator miI(std::next(SelectItr));
17317   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17318     const MachineInstr& mi = *miI;
17319     if (mi.readsRegister(X86::EFLAGS))
17320       return false;
17321     if (mi.definesRegister(X86::EFLAGS))
17322       break; // Should have kill-flag - update below.
17323   }
17324
17325   // If we hit the end of the block, check whether EFLAGS is live into a
17326   // successor.
17327   if (miI == BB->end()) {
17328     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17329                                           sEnd = BB->succ_end();
17330          sItr != sEnd; ++sItr) {
17331       MachineBasicBlock* succ = *sItr;
17332       if (succ->isLiveIn(X86::EFLAGS))
17333         return false;
17334     }
17335   }
17336
17337   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17338   // out. SelectMI should have a kill flag on EFLAGS.
17339   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17340   return true;
17341 }
17342
17343 MachineBasicBlock *
17344 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17345                                      MachineBasicBlock *BB) const {
17346   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17347   DebugLoc DL = MI->getDebugLoc();
17348
17349   // To "insert" a SELECT_CC instruction, we actually have to insert the
17350   // diamond control-flow pattern.  The incoming instruction knows the
17351   // destination vreg to set, the condition code register to branch on, the
17352   // true/false values to select between, and a branch opcode to use.
17353   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17354   MachineFunction::iterator It = BB;
17355   ++It;
17356
17357   //  thisMBB:
17358   //  ...
17359   //   TrueVal = ...
17360   //   cmpTY ccX, r1, r2
17361   //   bCC copy1MBB
17362   //   fallthrough --> copy0MBB
17363   MachineBasicBlock *thisMBB = BB;
17364   MachineFunction *F = BB->getParent();
17365   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17366   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17367   F->insert(It, copy0MBB);
17368   F->insert(It, sinkMBB);
17369
17370   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17371   // live into the sink and copy blocks.
17372   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17373   if (!MI->killsRegister(X86::EFLAGS) &&
17374       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17375     copy0MBB->addLiveIn(X86::EFLAGS);
17376     sinkMBB->addLiveIn(X86::EFLAGS);
17377   }
17378
17379   // Transfer the remainder of BB and its successor edges to sinkMBB.
17380   sinkMBB->splice(sinkMBB->begin(), BB,
17381                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17382   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17383
17384   // Add the true and fallthrough blocks as its successors.
17385   BB->addSuccessor(copy0MBB);
17386   BB->addSuccessor(sinkMBB);
17387
17388   // Create the conditional branch instruction.
17389   unsigned Opc =
17390     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17391   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17392
17393   //  copy0MBB:
17394   //   %FalseValue = ...
17395   //   # fallthrough to sinkMBB
17396   copy0MBB->addSuccessor(sinkMBB);
17397
17398   //  sinkMBB:
17399   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17400   //  ...
17401   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17402           TII->get(X86::PHI), MI->getOperand(0).getReg())
17403     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17404     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17405
17406   MI->eraseFromParent();   // The pseudo instruction is gone now.
17407   return sinkMBB;
17408 }
17409
17410 MachineBasicBlock *
17411 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17412                                         bool Is64Bit) const {
17413   MachineFunction *MF = BB->getParent();
17414   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17415   DebugLoc DL = MI->getDebugLoc();
17416   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17417
17418   assert(MF->shouldSplitStack());
17419
17420   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17421   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17422
17423   // BB:
17424   //  ... [Till the alloca]
17425   // If stacklet is not large enough, jump to mallocMBB
17426   //
17427   // bumpMBB:
17428   //  Allocate by subtracting from RSP
17429   //  Jump to continueMBB
17430   //
17431   // mallocMBB:
17432   //  Allocate by call to runtime
17433   //
17434   // continueMBB:
17435   //  ...
17436   //  [rest of original BB]
17437   //
17438
17439   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17440   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17441   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17442
17443   MachineRegisterInfo &MRI = MF->getRegInfo();
17444   const TargetRegisterClass *AddrRegClass =
17445     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17446
17447   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17448     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17449     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17450     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17451     sizeVReg = MI->getOperand(1).getReg(),
17452     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17453
17454   MachineFunction::iterator MBBIter = BB;
17455   ++MBBIter;
17456
17457   MF->insert(MBBIter, bumpMBB);
17458   MF->insert(MBBIter, mallocMBB);
17459   MF->insert(MBBIter, continueMBB);
17460
17461   continueMBB->splice(continueMBB->begin(), BB,
17462                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17463   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17464
17465   // Add code to the main basic block to check if the stack limit has been hit,
17466   // and if so, jump to mallocMBB otherwise to bumpMBB.
17467   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17468   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17469     .addReg(tmpSPVReg).addReg(sizeVReg);
17470   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17471     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17472     .addReg(SPLimitVReg);
17473   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17474
17475   // bumpMBB simply decreases the stack pointer, since we know the current
17476   // stacklet has enough space.
17477   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17478     .addReg(SPLimitVReg);
17479   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17480     .addReg(SPLimitVReg);
17481   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17482
17483   // Calls into a routine in libgcc to allocate more space from the heap.
17484   const uint32_t *RegMask =
17485     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17486   if (Is64Bit) {
17487     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17488       .addReg(sizeVReg);
17489     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17490       .addExternalSymbol("__morestack_allocate_stack_space")
17491       .addRegMask(RegMask)
17492       .addReg(X86::RDI, RegState::Implicit)
17493       .addReg(X86::RAX, RegState::ImplicitDefine);
17494   } else {
17495     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17496       .addImm(12);
17497     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17498     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17499       .addExternalSymbol("__morestack_allocate_stack_space")
17500       .addRegMask(RegMask)
17501       .addReg(X86::EAX, RegState::ImplicitDefine);
17502   }
17503
17504   if (!Is64Bit)
17505     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17506       .addImm(16);
17507
17508   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17509     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17510   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17511
17512   // Set up the CFG correctly.
17513   BB->addSuccessor(bumpMBB);
17514   BB->addSuccessor(mallocMBB);
17515   mallocMBB->addSuccessor(continueMBB);
17516   bumpMBB->addSuccessor(continueMBB);
17517
17518   // Take care of the PHI nodes.
17519   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17520           MI->getOperand(0).getReg())
17521     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17522     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17523
17524   // Delete the original pseudo instruction.
17525   MI->eraseFromParent();
17526
17527   // And we're done.
17528   return continueMBB;
17529 }
17530
17531 MachineBasicBlock *
17532 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17533                                         MachineBasicBlock *BB) const {
17534   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17535   DebugLoc DL = MI->getDebugLoc();
17536
17537   assert(!Subtarget->isTargetMacho());
17538
17539   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17540   // non-trivial part is impdef of ESP.
17541
17542   if (Subtarget->isTargetWin64()) {
17543     if (Subtarget->isTargetCygMing()) {
17544       // ___chkstk(Mingw64):
17545       // Clobbers R10, R11, RAX and EFLAGS.
17546       // Updates RSP.
17547       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17548         .addExternalSymbol("___chkstk")
17549         .addReg(X86::RAX, RegState::Implicit)
17550         .addReg(X86::RSP, RegState::Implicit)
17551         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17552         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17553         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17554     } else {
17555       // __chkstk(MSVCRT): does not update stack pointer.
17556       // Clobbers R10, R11 and EFLAGS.
17557       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17558         .addExternalSymbol("__chkstk")
17559         .addReg(X86::RAX, RegState::Implicit)
17560         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17561       // RAX has the offset to be subtracted from RSP.
17562       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17563         .addReg(X86::RSP)
17564         .addReg(X86::RAX);
17565     }
17566   } else {
17567     const char *StackProbeSymbol =
17568       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17569
17570     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17571       .addExternalSymbol(StackProbeSymbol)
17572       .addReg(X86::EAX, RegState::Implicit)
17573       .addReg(X86::ESP, RegState::Implicit)
17574       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17575       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17576       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17577   }
17578
17579   MI->eraseFromParent();   // The pseudo instruction is gone now.
17580   return BB;
17581 }
17582
17583 MachineBasicBlock *
17584 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17585                                       MachineBasicBlock *BB) const {
17586   // This is pretty easy.  We're taking the value that we received from
17587   // our load from the relocation, sticking it in either RDI (x86-64)
17588   // or EAX and doing an indirect call.  The return value will then
17589   // be in the normal return register.
17590   MachineFunction *F = BB->getParent();
17591   const X86InstrInfo *TII
17592     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17593   DebugLoc DL = MI->getDebugLoc();
17594
17595   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17596   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17597
17598   // Get a register mask for the lowered call.
17599   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17600   // proper register mask.
17601   const uint32_t *RegMask =
17602     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17603   if (Subtarget->is64Bit()) {
17604     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17605                                       TII->get(X86::MOV64rm), X86::RDI)
17606     .addReg(X86::RIP)
17607     .addImm(0).addReg(0)
17608     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17609                       MI->getOperand(3).getTargetFlags())
17610     .addReg(0);
17611     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17612     addDirectMem(MIB, X86::RDI);
17613     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17614   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17615     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17616                                       TII->get(X86::MOV32rm), X86::EAX)
17617     .addReg(0)
17618     .addImm(0).addReg(0)
17619     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17620                       MI->getOperand(3).getTargetFlags())
17621     .addReg(0);
17622     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17623     addDirectMem(MIB, X86::EAX);
17624     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17625   } else {
17626     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17627                                       TII->get(X86::MOV32rm), X86::EAX)
17628     .addReg(TII->getGlobalBaseReg(F))
17629     .addImm(0).addReg(0)
17630     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17631                       MI->getOperand(3).getTargetFlags())
17632     .addReg(0);
17633     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17634     addDirectMem(MIB, X86::EAX);
17635     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17636   }
17637
17638   MI->eraseFromParent(); // The pseudo instruction is gone now.
17639   return BB;
17640 }
17641
17642 MachineBasicBlock *
17643 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17644                                     MachineBasicBlock *MBB) const {
17645   DebugLoc DL = MI->getDebugLoc();
17646   MachineFunction *MF = MBB->getParent();
17647   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17648   MachineRegisterInfo &MRI = MF->getRegInfo();
17649
17650   const BasicBlock *BB = MBB->getBasicBlock();
17651   MachineFunction::iterator I = MBB;
17652   ++I;
17653
17654   // Memory Reference
17655   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17656   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17657
17658   unsigned DstReg;
17659   unsigned MemOpndSlot = 0;
17660
17661   unsigned CurOp = 0;
17662
17663   DstReg = MI->getOperand(CurOp++).getReg();
17664   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17665   assert(RC->hasType(MVT::i32) && "Invalid destination!");
17666   unsigned mainDstReg = MRI.createVirtualRegister(RC);
17667   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17668
17669   MemOpndSlot = CurOp;
17670
17671   MVT PVT = getPointerTy();
17672   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17673          "Invalid Pointer Size!");
17674
17675   // For v = setjmp(buf), we generate
17676   //
17677   // thisMBB:
17678   //  buf[LabelOffset] = restoreMBB
17679   //  SjLjSetup restoreMBB
17680   //
17681   // mainMBB:
17682   //  v_main = 0
17683   //
17684   // sinkMBB:
17685   //  v = phi(main, restore)
17686   //
17687   // restoreMBB:
17688   //  v_restore = 1
17689
17690   MachineBasicBlock *thisMBB = MBB;
17691   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17692   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17693   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17694   MF->insert(I, mainMBB);
17695   MF->insert(I, sinkMBB);
17696   MF->push_back(restoreMBB);
17697
17698   MachineInstrBuilder MIB;
17699
17700   // Transfer the remainder of BB and its successor edges to sinkMBB.
17701   sinkMBB->splice(sinkMBB->begin(), MBB,
17702                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17703   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17704
17705   // thisMBB:
17706   unsigned PtrStoreOpc = 0;
17707   unsigned LabelReg = 0;
17708   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17709   Reloc::Model RM = MF->getTarget().getRelocationModel();
17710   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17711                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17712
17713   // Prepare IP either in reg or imm.
17714   if (!UseImmLabel) {
17715     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17716     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17717     LabelReg = MRI.createVirtualRegister(PtrRC);
17718     if (Subtarget->is64Bit()) {
17719       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17720               .addReg(X86::RIP)
17721               .addImm(0)
17722               .addReg(0)
17723               .addMBB(restoreMBB)
17724               .addReg(0);
17725     } else {
17726       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17727       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17728               .addReg(XII->getGlobalBaseReg(MF))
17729               .addImm(0)
17730               .addReg(0)
17731               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17732               .addReg(0);
17733     }
17734   } else
17735     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17736   // Store IP
17737   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17738   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17739     if (i == X86::AddrDisp)
17740       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17741     else
17742       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17743   }
17744   if (!UseImmLabel)
17745     MIB.addReg(LabelReg);
17746   else
17747     MIB.addMBB(restoreMBB);
17748   MIB.setMemRefs(MMOBegin, MMOEnd);
17749   // Setup
17750   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17751           .addMBB(restoreMBB);
17752
17753   const X86RegisterInfo *RegInfo =
17754     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17755   MIB.addRegMask(RegInfo->getNoPreservedMask());
17756   thisMBB->addSuccessor(mainMBB);
17757   thisMBB->addSuccessor(restoreMBB);
17758
17759   // mainMBB:
17760   //  EAX = 0
17761   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17762   mainMBB->addSuccessor(sinkMBB);
17763
17764   // sinkMBB:
17765   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17766           TII->get(X86::PHI), DstReg)
17767     .addReg(mainDstReg).addMBB(mainMBB)
17768     .addReg(restoreDstReg).addMBB(restoreMBB);
17769
17770   // restoreMBB:
17771   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17772   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17773   restoreMBB->addSuccessor(sinkMBB);
17774
17775   MI->eraseFromParent();
17776   return sinkMBB;
17777 }
17778
17779 MachineBasicBlock *
17780 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17781                                      MachineBasicBlock *MBB) const {
17782   DebugLoc DL = MI->getDebugLoc();
17783   MachineFunction *MF = MBB->getParent();
17784   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17785   MachineRegisterInfo &MRI = MF->getRegInfo();
17786
17787   // Memory Reference
17788   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17789   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17790
17791   MVT PVT = getPointerTy();
17792   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17793          "Invalid Pointer Size!");
17794
17795   const TargetRegisterClass *RC =
17796     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17797   unsigned Tmp = MRI.createVirtualRegister(RC);
17798   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17799   const X86RegisterInfo *RegInfo =
17800     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17801   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17802   unsigned SP = RegInfo->getStackRegister();
17803
17804   MachineInstrBuilder MIB;
17805
17806   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17807   const int64_t SPOffset = 2 * PVT.getStoreSize();
17808
17809   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17810   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17811
17812   // Reload FP
17813   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17814   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17815     MIB.addOperand(MI->getOperand(i));
17816   MIB.setMemRefs(MMOBegin, MMOEnd);
17817   // Reload IP
17818   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17819   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17820     if (i == X86::AddrDisp)
17821       MIB.addDisp(MI->getOperand(i), LabelOffset);
17822     else
17823       MIB.addOperand(MI->getOperand(i));
17824   }
17825   MIB.setMemRefs(MMOBegin, MMOEnd);
17826   // Reload SP
17827   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17828   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17829     if (i == X86::AddrDisp)
17830       MIB.addDisp(MI->getOperand(i), SPOffset);
17831     else
17832       MIB.addOperand(MI->getOperand(i));
17833   }
17834   MIB.setMemRefs(MMOBegin, MMOEnd);
17835   // Jump
17836   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17837
17838   MI->eraseFromParent();
17839   return MBB;
17840 }
17841
17842 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17843 // accumulator loops. Writing back to the accumulator allows the coalescer
17844 // to remove extra copies in the loop.   
17845 MachineBasicBlock *
17846 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17847                                  MachineBasicBlock *MBB) const {
17848   MachineOperand &AddendOp = MI->getOperand(3);
17849
17850   // Bail out early if the addend isn't a register - we can't switch these.
17851   if (!AddendOp.isReg())
17852     return MBB;
17853
17854   MachineFunction &MF = *MBB->getParent();
17855   MachineRegisterInfo &MRI = MF.getRegInfo();
17856
17857   // Check whether the addend is defined by a PHI:
17858   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17859   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17860   if (!AddendDef.isPHI())
17861     return MBB;
17862
17863   // Look for the following pattern:
17864   // loop:
17865   //   %addend = phi [%entry, 0], [%loop, %result]
17866   //   ...
17867   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17868
17869   // Replace with:
17870   //   loop:
17871   //   %addend = phi [%entry, 0], [%loop, %result]
17872   //   ...
17873   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17874
17875   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17876     assert(AddendDef.getOperand(i).isReg());
17877     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17878     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17879     if (&PHISrcInst == MI) {
17880       // Found a matching instruction.
17881       unsigned NewFMAOpc = 0;
17882       switch (MI->getOpcode()) {
17883         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17884         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17885         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17886         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17887         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17888         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17889         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17890         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17891         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17892         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17893         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17894         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17895         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17896         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17897         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17898         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17899         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17900         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17901         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17902         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17903         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17904         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17905         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17906         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17907         default: llvm_unreachable("Unrecognized FMA variant.");
17908       }
17909
17910       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17911       MachineInstrBuilder MIB =
17912         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17913         .addOperand(MI->getOperand(0))
17914         .addOperand(MI->getOperand(3))
17915         .addOperand(MI->getOperand(2))
17916         .addOperand(MI->getOperand(1));
17917       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17918       MI->eraseFromParent();
17919     }
17920   }
17921
17922   return MBB;
17923 }
17924
17925 MachineBasicBlock *
17926 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17927                                                MachineBasicBlock *BB) const {
17928   switch (MI->getOpcode()) {
17929   default: llvm_unreachable("Unexpected instr type to insert");
17930   case X86::TAILJMPd64:
17931   case X86::TAILJMPr64:
17932   case X86::TAILJMPm64:
17933     llvm_unreachable("TAILJMP64 would not be touched here.");
17934   case X86::TCRETURNdi64:
17935   case X86::TCRETURNri64:
17936   case X86::TCRETURNmi64:
17937     return BB;
17938   case X86::WIN_ALLOCA:
17939     return EmitLoweredWinAlloca(MI, BB);
17940   case X86::SEG_ALLOCA_32:
17941     return EmitLoweredSegAlloca(MI, BB, false);
17942   case X86::SEG_ALLOCA_64:
17943     return EmitLoweredSegAlloca(MI, BB, true);
17944   case X86::TLSCall_32:
17945   case X86::TLSCall_64:
17946     return EmitLoweredTLSCall(MI, BB);
17947   case X86::CMOV_GR8:
17948   case X86::CMOV_FR32:
17949   case X86::CMOV_FR64:
17950   case X86::CMOV_V4F32:
17951   case X86::CMOV_V2F64:
17952   case X86::CMOV_V2I64:
17953   case X86::CMOV_V8F32:
17954   case X86::CMOV_V4F64:
17955   case X86::CMOV_V4I64:
17956   case X86::CMOV_V16F32:
17957   case X86::CMOV_V8F64:
17958   case X86::CMOV_V8I64:
17959   case X86::CMOV_GR16:
17960   case X86::CMOV_GR32:
17961   case X86::CMOV_RFP32:
17962   case X86::CMOV_RFP64:
17963   case X86::CMOV_RFP80:
17964     return EmitLoweredSelect(MI, BB);
17965
17966   case X86::FP32_TO_INT16_IN_MEM:
17967   case X86::FP32_TO_INT32_IN_MEM:
17968   case X86::FP32_TO_INT64_IN_MEM:
17969   case X86::FP64_TO_INT16_IN_MEM:
17970   case X86::FP64_TO_INT32_IN_MEM:
17971   case X86::FP64_TO_INT64_IN_MEM:
17972   case X86::FP80_TO_INT16_IN_MEM:
17973   case X86::FP80_TO_INT32_IN_MEM:
17974   case X86::FP80_TO_INT64_IN_MEM: {
17975     MachineFunction *F = BB->getParent();
17976     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17977     DebugLoc DL = MI->getDebugLoc();
17978
17979     // Change the floating point control register to use "round towards zero"
17980     // mode when truncating to an integer value.
17981     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17982     addFrameReference(BuildMI(*BB, MI, DL,
17983                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17984
17985     // Load the old value of the high byte of the control word...
17986     unsigned OldCW =
17987       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17988     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17989                       CWFrameIdx);
17990
17991     // Set the high part to be round to zero...
17992     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17993       .addImm(0xC7F);
17994
17995     // Reload the modified control word now...
17996     addFrameReference(BuildMI(*BB, MI, DL,
17997                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17998
17999     // Restore the memory image of control word to original value
18000     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18001       .addReg(OldCW);
18002
18003     // Get the X86 opcode to use.
18004     unsigned Opc;
18005     switch (MI->getOpcode()) {
18006     default: llvm_unreachable("illegal opcode!");
18007     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18008     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18009     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18010     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18011     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18012     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18013     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18014     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18015     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18016     }
18017
18018     X86AddressMode AM;
18019     MachineOperand &Op = MI->getOperand(0);
18020     if (Op.isReg()) {
18021       AM.BaseType = X86AddressMode::RegBase;
18022       AM.Base.Reg = Op.getReg();
18023     } else {
18024       AM.BaseType = X86AddressMode::FrameIndexBase;
18025       AM.Base.FrameIndex = Op.getIndex();
18026     }
18027     Op = MI->getOperand(1);
18028     if (Op.isImm())
18029       AM.Scale = Op.getImm();
18030     Op = MI->getOperand(2);
18031     if (Op.isImm())
18032       AM.IndexReg = Op.getImm();
18033     Op = MI->getOperand(3);
18034     if (Op.isGlobal()) {
18035       AM.GV = Op.getGlobal();
18036     } else {
18037       AM.Disp = Op.getImm();
18038     }
18039     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18040                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18041
18042     // Reload the original control word now.
18043     addFrameReference(BuildMI(*BB, MI, DL,
18044                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18045
18046     MI->eraseFromParent();   // The pseudo instruction is gone now.
18047     return BB;
18048   }
18049     // String/text processing lowering.
18050   case X86::PCMPISTRM128REG:
18051   case X86::VPCMPISTRM128REG:
18052   case X86::PCMPISTRM128MEM:
18053   case X86::VPCMPISTRM128MEM:
18054   case X86::PCMPESTRM128REG:
18055   case X86::VPCMPESTRM128REG:
18056   case X86::PCMPESTRM128MEM:
18057   case X86::VPCMPESTRM128MEM:
18058     assert(Subtarget->hasSSE42() &&
18059            "Target must have SSE4.2 or AVX features enabled");
18060     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18061
18062   // String/text processing lowering.
18063   case X86::PCMPISTRIREG:
18064   case X86::VPCMPISTRIREG:
18065   case X86::PCMPISTRIMEM:
18066   case X86::VPCMPISTRIMEM:
18067   case X86::PCMPESTRIREG:
18068   case X86::VPCMPESTRIREG:
18069   case X86::PCMPESTRIMEM:
18070   case X86::VPCMPESTRIMEM:
18071     assert(Subtarget->hasSSE42() &&
18072            "Target must have SSE4.2 or AVX features enabled");
18073     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18074
18075   // Thread synchronization.
18076   case X86::MONITOR:
18077     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18078
18079   // xbegin
18080   case X86::XBEGIN:
18081     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18082
18083   case X86::VASTART_SAVE_XMM_REGS:
18084     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18085
18086   case X86::VAARG_64:
18087     return EmitVAARG64WithCustomInserter(MI, BB);
18088
18089   case X86::EH_SjLj_SetJmp32:
18090   case X86::EH_SjLj_SetJmp64:
18091     return emitEHSjLjSetJmp(MI, BB);
18092
18093   case X86::EH_SjLj_LongJmp32:
18094   case X86::EH_SjLj_LongJmp64:
18095     return emitEHSjLjLongJmp(MI, BB);
18096
18097   case TargetOpcode::STACKMAP:
18098   case TargetOpcode::PATCHPOINT:
18099     return emitPatchPoint(MI, BB);
18100
18101   case X86::VFMADDPDr213r:
18102   case X86::VFMADDPSr213r:
18103   case X86::VFMADDSDr213r:
18104   case X86::VFMADDSSr213r:
18105   case X86::VFMSUBPDr213r:
18106   case X86::VFMSUBPSr213r:
18107   case X86::VFMSUBSDr213r:
18108   case X86::VFMSUBSSr213r:
18109   case X86::VFNMADDPDr213r:
18110   case X86::VFNMADDPSr213r:
18111   case X86::VFNMADDSDr213r:
18112   case X86::VFNMADDSSr213r:
18113   case X86::VFNMSUBPDr213r:
18114   case X86::VFNMSUBPSr213r:
18115   case X86::VFNMSUBSDr213r:
18116   case X86::VFNMSUBSSr213r:
18117   case X86::VFMADDPDr213rY:
18118   case X86::VFMADDPSr213rY:
18119   case X86::VFMSUBPDr213rY:
18120   case X86::VFMSUBPSr213rY:
18121   case X86::VFNMADDPDr213rY:
18122   case X86::VFNMADDPSr213rY:
18123   case X86::VFNMSUBPDr213rY:
18124   case X86::VFNMSUBPSr213rY:
18125     return emitFMA3Instr(MI, BB);
18126   }
18127 }
18128
18129 //===----------------------------------------------------------------------===//
18130 //                           X86 Optimization Hooks
18131 //===----------------------------------------------------------------------===//
18132
18133 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18134                                                       APInt &KnownZero,
18135                                                       APInt &KnownOne,
18136                                                       const SelectionDAG &DAG,
18137                                                       unsigned Depth) const {
18138   unsigned BitWidth = KnownZero.getBitWidth();
18139   unsigned Opc = Op.getOpcode();
18140   assert((Opc >= ISD::BUILTIN_OP_END ||
18141           Opc == ISD::INTRINSIC_WO_CHAIN ||
18142           Opc == ISD::INTRINSIC_W_CHAIN ||
18143           Opc == ISD::INTRINSIC_VOID) &&
18144          "Should use MaskedValueIsZero if you don't know whether Op"
18145          " is a target node!");
18146
18147   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18148   switch (Opc) {
18149   default: break;
18150   case X86ISD::ADD:
18151   case X86ISD::SUB:
18152   case X86ISD::ADC:
18153   case X86ISD::SBB:
18154   case X86ISD::SMUL:
18155   case X86ISD::UMUL:
18156   case X86ISD::INC:
18157   case X86ISD::DEC:
18158   case X86ISD::OR:
18159   case X86ISD::XOR:
18160   case X86ISD::AND:
18161     // These nodes' second result is a boolean.
18162     if (Op.getResNo() == 0)
18163       break;
18164     // Fallthrough
18165   case X86ISD::SETCC:
18166     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18167     break;
18168   case ISD::INTRINSIC_WO_CHAIN: {
18169     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18170     unsigned NumLoBits = 0;
18171     switch (IntId) {
18172     default: break;
18173     case Intrinsic::x86_sse_movmsk_ps:
18174     case Intrinsic::x86_avx_movmsk_ps_256:
18175     case Intrinsic::x86_sse2_movmsk_pd:
18176     case Intrinsic::x86_avx_movmsk_pd_256:
18177     case Intrinsic::x86_mmx_pmovmskb:
18178     case Intrinsic::x86_sse2_pmovmskb_128:
18179     case Intrinsic::x86_avx2_pmovmskb: {
18180       // High bits of movmskp{s|d}, pmovmskb are known zero.
18181       switch (IntId) {
18182         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18183         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18184         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18185         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18186         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18187         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18188         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18189         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18190       }
18191       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18192       break;
18193     }
18194     }
18195     break;
18196   }
18197   }
18198 }
18199
18200 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18201   SDValue Op,
18202   const SelectionDAG &,
18203   unsigned Depth) const {
18204   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18205   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18206     return Op.getValueType().getScalarType().getSizeInBits();
18207
18208   // Fallback case.
18209   return 1;
18210 }
18211
18212 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18213 /// node is a GlobalAddress + offset.
18214 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18215                                        const GlobalValue* &GA,
18216                                        int64_t &Offset) const {
18217   if (N->getOpcode() == X86ISD::Wrapper) {
18218     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18219       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18220       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18221       return true;
18222     }
18223   }
18224   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18225 }
18226
18227 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18228 /// same as extracting the high 128-bit part of 256-bit vector and then
18229 /// inserting the result into the low part of a new 256-bit vector
18230 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18231   EVT VT = SVOp->getValueType(0);
18232   unsigned NumElems = VT.getVectorNumElements();
18233
18234   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18235   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18236     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18237         SVOp->getMaskElt(j) >= 0)
18238       return false;
18239
18240   return true;
18241 }
18242
18243 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18244 /// same as extracting the low 128-bit part of 256-bit vector and then
18245 /// inserting the result into the high part of a new 256-bit vector
18246 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18247   EVT VT = SVOp->getValueType(0);
18248   unsigned NumElems = VT.getVectorNumElements();
18249
18250   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18251   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18252     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18253         SVOp->getMaskElt(j) >= 0)
18254       return false;
18255
18256   return true;
18257 }
18258
18259 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18260 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18261                                         TargetLowering::DAGCombinerInfo &DCI,
18262                                         const X86Subtarget* Subtarget) {
18263   SDLoc dl(N);
18264   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18265   SDValue V1 = SVOp->getOperand(0);
18266   SDValue V2 = SVOp->getOperand(1);
18267   EVT VT = SVOp->getValueType(0);
18268   unsigned NumElems = VT.getVectorNumElements();
18269
18270   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18271       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18272     //
18273     //                   0,0,0,...
18274     //                      |
18275     //    V      UNDEF    BUILD_VECTOR    UNDEF
18276     //     \      /           \           /
18277     //  CONCAT_VECTOR         CONCAT_VECTOR
18278     //         \                  /
18279     //          \                /
18280     //          RESULT: V + zero extended
18281     //
18282     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18283         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18284         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18285       return SDValue();
18286
18287     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18288       return SDValue();
18289
18290     // To match the shuffle mask, the first half of the mask should
18291     // be exactly the first vector, and all the rest a splat with the
18292     // first element of the second one.
18293     for (unsigned i = 0; i != NumElems/2; ++i)
18294       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18295           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18296         return SDValue();
18297
18298     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18299     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18300       if (Ld->hasNUsesOfValue(1, 0)) {
18301         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18302         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18303         SDValue ResNode =
18304           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18305                                   Ld->getMemoryVT(),
18306                                   Ld->getPointerInfo(),
18307                                   Ld->getAlignment(),
18308                                   false/*isVolatile*/, true/*ReadMem*/,
18309                                   false/*WriteMem*/);
18310
18311         // Make sure the newly-created LOAD is in the same position as Ld in
18312         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18313         // and update uses of Ld's output chain to use the TokenFactor.
18314         if (Ld->hasAnyUseOfValue(1)) {
18315           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18316                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18317           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18318           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18319                                  SDValue(ResNode.getNode(), 1));
18320         }
18321
18322         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18323       }
18324     }
18325
18326     // Emit a zeroed vector and insert the desired subvector on its
18327     // first half.
18328     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18329     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18330     return DCI.CombineTo(N, InsV);
18331   }
18332
18333   //===--------------------------------------------------------------------===//
18334   // Combine some shuffles into subvector extracts and inserts:
18335   //
18336
18337   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18338   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18339     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18340     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18341     return DCI.CombineTo(N, InsV);
18342   }
18343
18344   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18345   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18346     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18347     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18348     return DCI.CombineTo(N, InsV);
18349   }
18350
18351   return SDValue();
18352 }
18353
18354 /// \brief Get the PSHUF-style mask from PSHUF node.
18355 ///
18356 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18357 /// PSHUF-style masks that can be reused with such instructions.
18358 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18359   SmallVector<int, 4> Mask;
18360   bool IsUnary;
18361   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18362   (void)HaveMask;
18363   assert(HaveMask);
18364
18365   switch (N.getOpcode()) {
18366   case X86ISD::PSHUFD:
18367     return Mask;
18368   case X86ISD::PSHUFLW:
18369     Mask.resize(4);
18370     return Mask;
18371   case X86ISD::PSHUFHW:
18372     Mask.erase(Mask.begin(), Mask.begin() + 4);
18373     for (int &M : Mask)
18374       M -= 4;
18375     return Mask;
18376   default:
18377     llvm_unreachable("No valid shuffle instruction found!");
18378   }
18379 }
18380
18381 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18382 ///
18383 /// We walk up the chain and look for a combinable shuffle, skipping over
18384 /// shuffles that we could hoist this shuffle's transformation past without
18385 /// altering anything.
18386 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18387                                          SelectionDAG &DAG,
18388                                          TargetLowering::DAGCombinerInfo &DCI) {
18389   assert(N.getOpcode() == X86ISD::PSHUFD &&
18390          "Called with something other than an x86 128-bit half shuffle!");
18391   SDLoc DL(N);
18392
18393   // Walk up a single-use chain looking for a combinable shuffle.
18394   SDValue V = N.getOperand(0);
18395   for (; V.hasOneUse(); V = V.getOperand(0)) {
18396     switch (V.getOpcode()) {
18397     default:
18398       return false; // Nothing combined!
18399
18400     case ISD::BITCAST:
18401       // Skip bitcasts as we always know the type for the target specific
18402       // instructions.
18403       continue;
18404
18405     case X86ISD::PSHUFD:
18406       // Found another dword shuffle.
18407       break;
18408
18409     case X86ISD::PSHUFLW:
18410       // Check that the low words (being shuffled) are the identity in the
18411       // dword shuffle, and the high words are self-contained.
18412       if (Mask[0] != 0 || Mask[1] != 1 ||
18413           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18414         return false;
18415
18416       continue;
18417
18418     case X86ISD::PSHUFHW:
18419       // Check that the high words (being shuffled) are the identity in the
18420       // dword shuffle, and the low words are self-contained.
18421       if (Mask[2] != 2 || Mask[3] != 3 ||
18422           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18423         return false;
18424
18425       continue;
18426     }
18427     // Break out of the loop if we break out of the switch.
18428     break;
18429   }
18430
18431   if (!V.hasOneUse())
18432     // We fell out of the loop without finding a viable combining instruction.
18433     return false;
18434
18435   // Record the old value to use in RAUW-ing.
18436   SDValue Old = V;
18437
18438   // Merge this node's mask and our incoming mask.
18439   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18440   for (int &M : Mask)
18441     M = VMask[M];
18442   V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V.getOperand(0),
18443                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18444
18445   // It is possible that one of the combinable shuffles was completely absorbed
18446   // by the other, just replace it and revisit all users in that case.
18447   if (Old.getNode() == V.getNode()) {
18448     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18449     return true;
18450   }
18451
18452   // Replace N with its operand as we're going to combine that shuffle away.
18453   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18454
18455   // Replace the combinable shuffle with the combined one, updating all users
18456   // so that we re-evaluate the chain here.
18457   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18458   return true;
18459 }
18460
18461 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18462 ///
18463 /// We walk up the chain, skipping shuffles of the other half and looking
18464 /// through shuffles which switch halves trying to find a shuffle of the same
18465 /// pair of dwords.
18466 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18467                                         SelectionDAG &DAG,
18468                                         TargetLowering::DAGCombinerInfo &DCI) {
18469   assert(
18470       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18471       "Called with something other than an x86 128-bit half shuffle!");
18472   SDLoc DL(N);
18473   unsigned CombineOpcode = N.getOpcode();
18474
18475   // Walk up a single-use chain looking for a combinable shuffle.
18476   SDValue V = N.getOperand(0);
18477   for (; V.hasOneUse(); V = V.getOperand(0)) {
18478     switch (V.getOpcode()) {
18479     default:
18480       return false; // Nothing combined!
18481
18482     case ISD::BITCAST:
18483       // Skip bitcasts as we always know the type for the target specific
18484       // instructions.
18485       continue;
18486
18487     case X86ISD::PSHUFLW:
18488     case X86ISD::PSHUFHW:
18489       if (V.getOpcode() == CombineOpcode)
18490         break;
18491
18492       // Other-half shuffles are no-ops.
18493       continue;
18494
18495     case X86ISD::PSHUFD: {
18496       // We can only handle pshufd if the half we are combining either stays in
18497       // its half, or switches to the other half. Bail if one of these isn't
18498       // true.
18499       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18500       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18501       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18502             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18503         return false;
18504
18505       // Map the mask through the pshufd and keep walking up the chain.
18506       for (int i = 0; i < 4; ++i)
18507         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18508
18509       // Switch halves if the pshufd does.
18510       CombineOpcode =
18511           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18512       continue;
18513     }
18514     }
18515     // Break out of the loop if we break out of the switch.
18516     break;
18517   }
18518
18519   if (!V.hasOneUse())
18520     // We fell out of the loop without finding a viable combining instruction.
18521     return false;
18522
18523   // Record the old value to use in RAUW-ing.
18524   SDValue Old = V;
18525
18526   // Merge this node's mask and our incoming mask (adjusted to account for all
18527   // the pshufd instructions encountered).
18528   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18529   for (int &M : Mask)
18530     M = VMask[M];
18531   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18532                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18533
18534   // Replace N with its operand as we're going to combine that shuffle away.
18535   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18536
18537   // Replace the combinable shuffle with the combined one, updating all users
18538   // so that we re-evaluate the chain here.
18539   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18540   return true;
18541 }
18542
18543 /// \brief Try to combine x86 target specific shuffles.
18544 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18545                                            TargetLowering::DAGCombinerInfo &DCI,
18546                                            const X86Subtarget *Subtarget) {
18547   SDLoc DL(N);
18548   MVT VT = N.getSimpleValueType();
18549   SmallVector<int, 4> Mask;
18550
18551   switch (N.getOpcode()) {
18552   case X86ISD::PSHUFD:
18553   case X86ISD::PSHUFLW:
18554   case X86ISD::PSHUFHW:
18555     Mask = getPSHUFShuffleMask(N);
18556     assert(Mask.size() == 4);
18557     break;
18558   default:
18559     return SDValue();
18560   }
18561
18562   // Nuke no-op shuffles that show up after combining.
18563   if (isNoopShuffleMask(Mask))
18564     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18565
18566   // Look for simplifications involving one or two shuffle instructions.
18567   SDValue V = N.getOperand(0);
18568   switch (N.getOpcode()) {
18569   default:
18570     break;
18571   case X86ISD::PSHUFLW:
18572   case X86ISD::PSHUFHW:
18573     assert(VT == MVT::v8i16);
18574     (void)VT;
18575
18576     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18577       return SDValue(); // We combined away this shuffle, so we're done.
18578
18579     // See if this reduces to a PSHUFD which is no more expensive and can
18580     // combine with more operations.
18581     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18582         areAdjacentMasksSequential(Mask)) {
18583       int DMask[] = {-1, -1, -1, -1};
18584       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18585       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18586       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18587       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18588       DCI.AddToWorklist(V.getNode());
18589       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18590                       getV4X86ShuffleImm8ForMask(DMask, DAG));
18591       DCI.AddToWorklist(V.getNode());
18592       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18593     }
18594
18595     break;
18596
18597   case X86ISD::PSHUFD:
18598     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18599       return SDValue(); // We combined away this shuffle.
18600
18601     break;
18602   }
18603
18604   return SDValue();
18605 }
18606
18607 /// PerformShuffleCombine - Performs several different shuffle combines.
18608 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18609                                      TargetLowering::DAGCombinerInfo &DCI,
18610                                      const X86Subtarget *Subtarget) {
18611   SDLoc dl(N);
18612   SDValue N0 = N->getOperand(0);
18613   SDValue N1 = N->getOperand(1);
18614   EVT VT = N->getValueType(0);
18615
18616   // Canonicalize shuffles that perform 'addsub' on packed float vectors
18617   // according to the rule:
18618   //  (shuffle (FADD A, B), (FSUB A, B), Mask) ->
18619   //  (shuffle (FSUB A, -B), (FADD A, -B), Mask)
18620   //
18621   // Where 'Mask' is:
18622   //  <0,5,2,7>             -- for v4f32 and v4f64 shuffles;
18623   //  <0,3>                 -- for v2f64 shuffles;
18624   //  <0,9,2,11,4,13,6,15>  -- for v8f32 shuffles.
18625   //
18626   // This helps pattern-matching more SSE3/AVX ADDSUB instructions
18627   // during ISel stage.
18628   if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
18629       ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18630        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18631       N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
18632       // Operands to the FADD and FSUB must be the same.
18633       ((N0->getOperand(0) == N1->getOperand(0) &&
18634         N0->getOperand(1) == N1->getOperand(1)) ||
18635        // FADD is commutable. See if by commuting the operands of the FADD
18636        // we would still be able to match the operands of the FSUB dag node.
18637        (N0->getOperand(1) == N1->getOperand(0) &&
18638         N0->getOperand(0) == N1->getOperand(1))) &&
18639       N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
18640       N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
18641     
18642     ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
18643     unsigned NumElts = VT.getVectorNumElements();
18644     ArrayRef<int> Mask = SV->getMask();
18645     bool CanFold = true;
18646
18647     for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
18648       CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
18649
18650     if (CanFold) {
18651       SDValue Op0 = N1->getOperand(0);
18652       SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
18653       SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
18654       SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
18655       return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
18656     }
18657   }
18658
18659   // Don't create instructions with illegal types after legalize types has run.
18660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18661   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18662     return SDValue();
18663
18664   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18665   if (Subtarget->hasFp256() && VT.is256BitVector() &&
18666       N->getOpcode() == ISD::VECTOR_SHUFFLE)
18667     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18668
18669   // During Type Legalization, when promoting illegal vector types,
18670   // the backend might introduce new shuffle dag nodes and bitcasts.
18671   //
18672   // This code performs the following transformation:
18673   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18674   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18675   //
18676   // We do this only if both the bitcast and the BINOP dag nodes have
18677   // one use. Also, perform this transformation only if the new binary
18678   // operation is legal. This is to avoid introducing dag nodes that
18679   // potentially need to be further expanded (or custom lowered) into a
18680   // less optimal sequence of dag nodes.
18681   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18682       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18683       N0.getOpcode() == ISD::BITCAST) {
18684     SDValue BC0 = N0.getOperand(0);
18685     EVT SVT = BC0.getValueType();
18686     unsigned Opcode = BC0.getOpcode();
18687     unsigned NumElts = VT.getVectorNumElements();
18688     
18689     if (BC0.hasOneUse() && SVT.isVector() &&
18690         SVT.getVectorNumElements() * 2 == NumElts &&
18691         TLI.isOperationLegal(Opcode, VT)) {
18692       bool CanFold = false;
18693       switch (Opcode) {
18694       default : break;
18695       case ISD::ADD :
18696       case ISD::FADD :
18697       case ISD::SUB :
18698       case ISD::FSUB :
18699       case ISD::MUL :
18700       case ISD::FMUL :
18701         CanFold = true;
18702       }
18703
18704       unsigned SVTNumElts = SVT.getVectorNumElements();
18705       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18706       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18707         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18708       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18709         CanFold = SVOp->getMaskElt(i) < 0;
18710
18711       if (CanFold) {
18712         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18713         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18714         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18715         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18716       }
18717     }
18718   }
18719
18720   // Only handle 128 wide vector from here on.
18721   if (!VT.is128BitVector())
18722     return SDValue();
18723
18724   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18725   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18726   // consecutive, non-overlapping, and in the right order.
18727   SmallVector<SDValue, 16> Elts;
18728   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18729     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18730
18731   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18732   if (LD.getNode())
18733     return LD;
18734
18735   if (isTargetShuffle(N->getOpcode())) {
18736     SDValue Shuffle =
18737         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18738     if (Shuffle.getNode())
18739       return Shuffle;
18740   }
18741
18742   return SDValue();
18743 }
18744
18745 /// PerformTruncateCombine - Converts truncate operation to
18746 /// a sequence of vector shuffle operations.
18747 /// It is possible when we truncate 256-bit vector to 128-bit vector
18748 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18749                                       TargetLowering::DAGCombinerInfo &DCI,
18750                                       const X86Subtarget *Subtarget)  {
18751   return SDValue();
18752 }
18753
18754 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18755 /// specific shuffle of a load can be folded into a single element load.
18756 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18757 /// shuffles have been customed lowered so we need to handle those here.
18758 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18759                                          TargetLowering::DAGCombinerInfo &DCI) {
18760   if (DCI.isBeforeLegalizeOps())
18761     return SDValue();
18762
18763   SDValue InVec = N->getOperand(0);
18764   SDValue EltNo = N->getOperand(1);
18765
18766   if (!isa<ConstantSDNode>(EltNo))
18767     return SDValue();
18768
18769   EVT VT = InVec.getValueType();
18770
18771   bool HasShuffleIntoBitcast = false;
18772   if (InVec.getOpcode() == ISD::BITCAST) {
18773     // Don't duplicate a load with other uses.
18774     if (!InVec.hasOneUse())
18775       return SDValue();
18776     EVT BCVT = InVec.getOperand(0).getValueType();
18777     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18778       return SDValue();
18779     InVec = InVec.getOperand(0);
18780     HasShuffleIntoBitcast = true;
18781   }
18782
18783   if (!isTargetShuffle(InVec.getOpcode()))
18784     return SDValue();
18785
18786   // Don't duplicate a load with other uses.
18787   if (!InVec.hasOneUse())
18788     return SDValue();
18789
18790   SmallVector<int, 16> ShuffleMask;
18791   bool UnaryShuffle;
18792   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18793                             UnaryShuffle))
18794     return SDValue();
18795
18796   // Select the input vector, guarding against out of range extract vector.
18797   unsigned NumElems = VT.getVectorNumElements();
18798   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18799   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18800   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18801                                          : InVec.getOperand(1);
18802
18803   // If inputs to shuffle are the same for both ops, then allow 2 uses
18804   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18805
18806   if (LdNode.getOpcode() == ISD::BITCAST) {
18807     // Don't duplicate a load with other uses.
18808     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18809       return SDValue();
18810
18811     AllowedUses = 1; // only allow 1 load use if we have a bitcast
18812     LdNode = LdNode.getOperand(0);
18813   }
18814
18815   if (!ISD::isNormalLoad(LdNode.getNode()))
18816     return SDValue();
18817
18818   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18819
18820   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18821     return SDValue();
18822
18823   if (HasShuffleIntoBitcast) {
18824     // If there's a bitcast before the shuffle, check if the load type and
18825     // alignment is valid.
18826     unsigned Align = LN0->getAlignment();
18827     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18828     unsigned NewAlign = TLI.getDataLayout()->
18829       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18830
18831     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18832       return SDValue();
18833   }
18834
18835   // All checks match so transform back to vector_shuffle so that DAG combiner
18836   // can finish the job
18837   SDLoc dl(N);
18838
18839   // Create shuffle node taking into account the case that its a unary shuffle
18840   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18841   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18842                                  InVec.getOperand(0), Shuffle,
18843                                  &ShuffleMask[0]);
18844   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18845   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18846                      EltNo);
18847 }
18848
18849 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18850 /// generation and convert it from being a bunch of shuffles and extracts
18851 /// to a simple store and scalar loads to extract the elements.
18852 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18853                                          TargetLowering::DAGCombinerInfo &DCI) {
18854   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18855   if (NewOp.getNode())
18856     return NewOp;
18857
18858   SDValue InputVector = N->getOperand(0);
18859
18860   // Detect whether we are trying to convert from mmx to i32 and the bitcast
18861   // from mmx to v2i32 has a single usage.
18862   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18863       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18864       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18865     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18866                        N->getValueType(0),
18867                        InputVector.getNode()->getOperand(0));
18868
18869   // Only operate on vectors of 4 elements, where the alternative shuffling
18870   // gets to be more expensive.
18871   if (InputVector.getValueType() != MVT::v4i32)
18872     return SDValue();
18873
18874   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18875   // single use which is a sign-extend or zero-extend, and all elements are
18876   // used.
18877   SmallVector<SDNode *, 4> Uses;
18878   unsigned ExtractedElements = 0;
18879   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18880        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18881     if (UI.getUse().getResNo() != InputVector.getResNo())
18882       return SDValue();
18883
18884     SDNode *Extract = *UI;
18885     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18886       return SDValue();
18887
18888     if (Extract->getValueType(0) != MVT::i32)
18889       return SDValue();
18890     if (!Extract->hasOneUse())
18891       return SDValue();
18892     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18893         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18894       return SDValue();
18895     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18896       return SDValue();
18897
18898     // Record which element was extracted.
18899     ExtractedElements |=
18900       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18901
18902     Uses.push_back(Extract);
18903   }
18904
18905   // If not all the elements were used, this may not be worthwhile.
18906   if (ExtractedElements != 15)
18907     return SDValue();
18908
18909   // Ok, we've now decided to do the transformation.
18910   SDLoc dl(InputVector);
18911
18912   // Store the value to a temporary stack slot.
18913   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18914   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18915                             MachinePointerInfo(), false, false, 0);
18916
18917   // Replace each use (extract) with a load of the appropriate element.
18918   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18919        UE = Uses.end(); UI != UE; ++UI) {
18920     SDNode *Extract = *UI;
18921
18922     // cOMpute the element's address.
18923     SDValue Idx = Extract->getOperand(1);
18924     unsigned EltSize =
18925         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18926     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18927     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18928     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18929
18930     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18931                                      StackPtr, OffsetVal);
18932
18933     // Load the scalar.
18934     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18935                                      ScalarAddr, MachinePointerInfo(),
18936                                      false, false, false, 0);
18937
18938     // Replace the exact with the load.
18939     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18940   }
18941
18942   // The replacement was made in place; don't return anything.
18943   return SDValue();
18944 }
18945
18946 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18947 static std::pair<unsigned, bool>
18948 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18949                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18950   if (!VT.isVector())
18951     return std::make_pair(0, false);
18952
18953   bool NeedSplit = false;
18954   switch (VT.getSimpleVT().SimpleTy) {
18955   default: return std::make_pair(0, false);
18956   case MVT::v32i8:
18957   case MVT::v16i16:
18958   case MVT::v8i32:
18959     if (!Subtarget->hasAVX2())
18960       NeedSplit = true;
18961     if (!Subtarget->hasAVX())
18962       return std::make_pair(0, false);
18963     break;
18964   case MVT::v16i8:
18965   case MVT::v8i16:
18966   case MVT::v4i32:
18967     if (!Subtarget->hasSSE2())
18968       return std::make_pair(0, false);
18969   }
18970
18971   // SSE2 has only a small subset of the operations.
18972   bool hasUnsigned = Subtarget->hasSSE41() ||
18973                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
18974   bool hasSigned = Subtarget->hasSSE41() ||
18975                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
18976
18977   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18978
18979   unsigned Opc = 0;
18980   // Check for x CC y ? x : y.
18981   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18982       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18983     switch (CC) {
18984     default: break;
18985     case ISD::SETULT:
18986     case ISD::SETULE:
18987       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18988     case ISD::SETUGT:
18989     case ISD::SETUGE:
18990       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18991     case ISD::SETLT:
18992     case ISD::SETLE:
18993       Opc = hasSigned ? X86ISD::SMIN : 0; break;
18994     case ISD::SETGT:
18995     case ISD::SETGE:
18996       Opc = hasSigned ? X86ISD::SMAX : 0; break;
18997     }
18998   // Check for x CC y ? y : x -- a min/max with reversed arms.
18999   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19000              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19001     switch (CC) {
19002     default: break;
19003     case ISD::SETULT:
19004     case ISD::SETULE:
19005       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19006     case ISD::SETUGT:
19007     case ISD::SETUGE:
19008       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19009     case ISD::SETLT:
19010     case ISD::SETLE:
19011       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19012     case ISD::SETGT:
19013     case ISD::SETGE:
19014       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19015     }
19016   }
19017
19018   return std::make_pair(Opc, NeedSplit);
19019 }
19020
19021 static SDValue
19022 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19023                                       const X86Subtarget *Subtarget) {
19024   SDLoc dl(N);
19025   SDValue Cond = N->getOperand(0);
19026   SDValue LHS = N->getOperand(1);
19027   SDValue RHS = N->getOperand(2);
19028
19029   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19030     SDValue CondSrc = Cond->getOperand(0);
19031     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19032       Cond = CondSrc->getOperand(0);
19033   }
19034
19035   MVT VT = N->getSimpleValueType(0);
19036   MVT EltVT = VT.getVectorElementType();
19037   unsigned NumElems = VT.getVectorNumElements();
19038   // There is no blend with immediate in AVX-512.
19039   if (VT.is512BitVector())
19040     return SDValue();
19041
19042   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19043     return SDValue();
19044   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19045     return SDValue();
19046
19047   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19048     return SDValue();
19049
19050   unsigned MaskValue = 0;
19051   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19052     return SDValue();
19053
19054   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19055   for (unsigned i = 0; i < NumElems; ++i) {
19056     // Be sure we emit undef where we can.
19057     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19058       ShuffleMask[i] = -1;
19059     else
19060       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19061   }
19062
19063   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19064 }
19065
19066 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19067 /// nodes.
19068 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19069                                     TargetLowering::DAGCombinerInfo &DCI,
19070                                     const X86Subtarget *Subtarget) {
19071   SDLoc DL(N);
19072   SDValue Cond = N->getOperand(0);
19073   // Get the LHS/RHS of the select.
19074   SDValue LHS = N->getOperand(1);
19075   SDValue RHS = N->getOperand(2);
19076   EVT VT = LHS.getValueType();
19077   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19078
19079   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19080   // instructions match the semantics of the common C idiom x<y?x:y but not
19081   // x<=y?x:y, because of how they handle negative zero (which can be
19082   // ignored in unsafe-math mode).
19083   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19084       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19085       (Subtarget->hasSSE2() ||
19086        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19087     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19088
19089     unsigned Opcode = 0;
19090     // Check for x CC y ? x : y.
19091     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19092         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19093       switch (CC) {
19094       default: break;
19095       case ISD::SETULT:
19096         // Converting this to a min would handle NaNs incorrectly, and swapping
19097         // the operands would cause it to handle comparisons between positive
19098         // and negative zero incorrectly.
19099         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19100           if (!DAG.getTarget().Options.UnsafeFPMath &&
19101               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19102             break;
19103           std::swap(LHS, RHS);
19104         }
19105         Opcode = X86ISD::FMIN;
19106         break;
19107       case ISD::SETOLE:
19108         // Converting this to a min would handle comparisons between positive
19109         // and negative zero incorrectly.
19110         if (!DAG.getTarget().Options.UnsafeFPMath &&
19111             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19112           break;
19113         Opcode = X86ISD::FMIN;
19114         break;
19115       case ISD::SETULE:
19116         // Converting this to a min would handle both negative zeros and NaNs
19117         // incorrectly, but we can swap the operands to fix both.
19118         std::swap(LHS, RHS);
19119       case ISD::SETOLT:
19120       case ISD::SETLT:
19121       case ISD::SETLE:
19122         Opcode = X86ISD::FMIN;
19123         break;
19124
19125       case ISD::SETOGE:
19126         // Converting this to a max would handle comparisons between positive
19127         // and negative zero incorrectly.
19128         if (!DAG.getTarget().Options.UnsafeFPMath &&
19129             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19130           break;
19131         Opcode = X86ISD::FMAX;
19132         break;
19133       case ISD::SETUGT:
19134         // Converting this to a max would handle NaNs incorrectly, and swapping
19135         // the operands would cause it to handle comparisons between positive
19136         // and negative zero incorrectly.
19137         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19138           if (!DAG.getTarget().Options.UnsafeFPMath &&
19139               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19140             break;
19141           std::swap(LHS, RHS);
19142         }
19143         Opcode = X86ISD::FMAX;
19144         break;
19145       case ISD::SETUGE:
19146         // Converting this to a max would handle both negative zeros and NaNs
19147         // incorrectly, but we can swap the operands to fix both.
19148         std::swap(LHS, RHS);
19149       case ISD::SETOGT:
19150       case ISD::SETGT:
19151       case ISD::SETGE:
19152         Opcode = X86ISD::FMAX;
19153         break;
19154       }
19155     // Check for x CC y ? y : x -- a min/max with reversed arms.
19156     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19157                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19158       switch (CC) {
19159       default: break;
19160       case ISD::SETOGE:
19161         // Converting this to a min would handle comparisons between positive
19162         // and negative zero incorrectly, and swapping the operands would
19163         // cause it to handle NaNs incorrectly.
19164         if (!DAG.getTarget().Options.UnsafeFPMath &&
19165             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19166           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19167             break;
19168           std::swap(LHS, RHS);
19169         }
19170         Opcode = X86ISD::FMIN;
19171         break;
19172       case ISD::SETUGT:
19173         // Converting this to a min would handle NaNs incorrectly.
19174         if (!DAG.getTarget().Options.UnsafeFPMath &&
19175             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19176           break;
19177         Opcode = X86ISD::FMIN;
19178         break;
19179       case ISD::SETUGE:
19180         // Converting this to a min would handle both negative zeros and NaNs
19181         // incorrectly, but we can swap the operands to fix both.
19182         std::swap(LHS, RHS);
19183       case ISD::SETOGT:
19184       case ISD::SETGT:
19185       case ISD::SETGE:
19186         Opcode = X86ISD::FMIN;
19187         break;
19188
19189       case ISD::SETULT:
19190         // Converting this to a max would handle NaNs incorrectly.
19191         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19192           break;
19193         Opcode = X86ISD::FMAX;
19194         break;
19195       case ISD::SETOLE:
19196         // Converting this to a max would handle comparisons between positive
19197         // and negative zero incorrectly, and swapping the operands would
19198         // cause it to handle NaNs incorrectly.
19199         if (!DAG.getTarget().Options.UnsafeFPMath &&
19200             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19201           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19202             break;
19203           std::swap(LHS, RHS);
19204         }
19205         Opcode = X86ISD::FMAX;
19206         break;
19207       case ISD::SETULE:
19208         // Converting this to a max would handle both negative zeros and NaNs
19209         // incorrectly, but we can swap the operands to fix both.
19210         std::swap(LHS, RHS);
19211       case ISD::SETOLT:
19212       case ISD::SETLT:
19213       case ISD::SETLE:
19214         Opcode = X86ISD::FMAX;
19215         break;
19216       }
19217     }
19218
19219     if (Opcode)
19220       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19221   }
19222
19223   EVT CondVT = Cond.getValueType();
19224   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19225       CondVT.getVectorElementType() == MVT::i1) {
19226     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19227     // lowering on AVX-512. In this case we convert it to
19228     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19229     // The same situation for all 128 and 256-bit vectors of i8 and i16
19230     EVT OpVT = LHS.getValueType();
19231     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19232         (OpVT.getVectorElementType() == MVT::i8 ||
19233          OpVT.getVectorElementType() == MVT::i16)) {
19234       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19235       DCI.AddToWorklist(Cond.getNode());
19236       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19237     }
19238   }
19239   // If this is a select between two integer constants, try to do some
19240   // optimizations.
19241   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19242     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19243       // Don't do this for crazy integer types.
19244       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19245         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19246         // so that TrueC (the true value) is larger than FalseC.
19247         bool NeedsCondInvert = false;
19248
19249         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19250             // Efficiently invertible.
19251             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19252              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19253               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19254           NeedsCondInvert = true;
19255           std::swap(TrueC, FalseC);
19256         }
19257
19258         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19259         if (FalseC->getAPIntValue() == 0 &&
19260             TrueC->getAPIntValue().isPowerOf2()) {
19261           if (NeedsCondInvert) // Invert the condition if needed.
19262             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19263                                DAG.getConstant(1, Cond.getValueType()));
19264
19265           // Zero extend the condition if needed.
19266           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19267
19268           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19269           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19270                              DAG.getConstant(ShAmt, MVT::i8));
19271         }
19272
19273         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19274         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19275           if (NeedsCondInvert) // Invert the condition if needed.
19276             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19277                                DAG.getConstant(1, Cond.getValueType()));
19278
19279           // Zero extend the condition if needed.
19280           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19281                              FalseC->getValueType(0), Cond);
19282           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19283                              SDValue(FalseC, 0));
19284         }
19285
19286         // Optimize cases that will turn into an LEA instruction.  This requires
19287         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19288         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19289           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19290           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19291
19292           bool isFastMultiplier = false;
19293           if (Diff < 10) {
19294             switch ((unsigned char)Diff) {
19295               default: break;
19296               case 1:  // result = add base, cond
19297               case 2:  // result = lea base(    , cond*2)
19298               case 3:  // result = lea base(cond, cond*2)
19299               case 4:  // result = lea base(    , cond*4)
19300               case 5:  // result = lea base(cond, cond*4)
19301               case 8:  // result = lea base(    , cond*8)
19302               case 9:  // result = lea base(cond, cond*8)
19303                 isFastMultiplier = true;
19304                 break;
19305             }
19306           }
19307
19308           if (isFastMultiplier) {
19309             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19310             if (NeedsCondInvert) // Invert the condition if needed.
19311               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19312                                  DAG.getConstant(1, Cond.getValueType()));
19313
19314             // Zero extend the condition if needed.
19315             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19316                                Cond);
19317             // Scale the condition by the difference.
19318             if (Diff != 1)
19319               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19320                                  DAG.getConstant(Diff, Cond.getValueType()));
19321
19322             // Add the base if non-zero.
19323             if (FalseC->getAPIntValue() != 0)
19324               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19325                                  SDValue(FalseC, 0));
19326             return Cond;
19327           }
19328         }
19329       }
19330   }
19331
19332   // Canonicalize max and min:
19333   // (x > y) ? x : y -> (x >= y) ? x : y
19334   // (x < y) ? x : y -> (x <= y) ? x : y
19335   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19336   // the need for an extra compare
19337   // against zero. e.g.
19338   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19339   // subl   %esi, %edi
19340   // testl  %edi, %edi
19341   // movl   $0, %eax
19342   // cmovgl %edi, %eax
19343   // =>
19344   // xorl   %eax, %eax
19345   // subl   %esi, $edi
19346   // cmovsl %eax, %edi
19347   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19348       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19349       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19350     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19351     switch (CC) {
19352     default: break;
19353     case ISD::SETLT:
19354     case ISD::SETGT: {
19355       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19356       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19357                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
19358       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19359     }
19360     }
19361   }
19362
19363   // Early exit check
19364   if (!TLI.isTypeLegal(VT))
19365     return SDValue();
19366
19367   // Match VSELECTs into subs with unsigned saturation.
19368   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19369       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19370       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19371        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19372     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19373
19374     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19375     // left side invert the predicate to simplify logic below.
19376     SDValue Other;
19377     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19378       Other = RHS;
19379       CC = ISD::getSetCCInverse(CC, true);
19380     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19381       Other = LHS;
19382     }
19383
19384     if (Other.getNode() && Other->getNumOperands() == 2 &&
19385         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19386       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19387       SDValue CondRHS = Cond->getOperand(1);
19388
19389       // Look for a general sub with unsigned saturation first.
19390       // x >= y ? x-y : 0 --> subus x, y
19391       // x >  y ? x-y : 0 --> subus x, y
19392       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19393           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19394         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19395
19396       // If the RHS is a constant we have to reverse the const canonicalization.
19397       // x > C-1 ? x+-C : 0 --> subus x, C
19398       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19399           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
19400         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
19401         if (CondRHS.getConstantOperandVal(0) == -A-1)
19402           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
19403                              DAG.getConstant(-A, VT));
19404       }
19405
19406       // Another special case: If C was a sign bit, the sub has been
19407       // canonicalized into a xor.
19408       // FIXME: Would it be better to use computeKnownBits to determine whether
19409       //        it's safe to decanonicalize the xor?
19410       // x s< 0 ? x^C : 0 --> subus x, C
19411       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19412           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19413           isSplatVector(OpRHS.getNode())) {
19414         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
19415         if (A.isSignBit())
19416           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19417       }
19418     }
19419   }
19420
19421   // Try to match a min/max vector operation.
19422   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19423     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19424     unsigned Opc = ret.first;
19425     bool NeedSplit = ret.second;
19426
19427     if (Opc && NeedSplit) {
19428       unsigned NumElems = VT.getVectorNumElements();
19429       // Extract the LHS vectors
19430       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19431       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19432
19433       // Extract the RHS vectors
19434       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19435       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19436
19437       // Create min/max for each subvector
19438       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19439       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19440
19441       // Merge the result
19442       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19443     } else if (Opc)
19444       return DAG.getNode(Opc, DL, VT, LHS, RHS);
19445   }
19446
19447   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19448   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19449       // Check if SETCC has already been promoted
19450       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19451       // Check that condition value type matches vselect operand type
19452       CondVT == VT) { 
19453
19454     assert(Cond.getValueType().isVector() &&
19455            "vector select expects a vector selector!");
19456
19457     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19458     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19459
19460     if (!TValIsAllOnes && !FValIsAllZeros) {
19461       // Try invert the condition if true value is not all 1s and false value
19462       // is not all 0s.
19463       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19464       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19465
19466       if (TValIsAllZeros || FValIsAllOnes) {
19467         SDValue CC = Cond.getOperand(2);
19468         ISD::CondCode NewCC =
19469           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19470                                Cond.getOperand(0).getValueType().isInteger());
19471         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19472         std::swap(LHS, RHS);
19473         TValIsAllOnes = FValIsAllOnes;
19474         FValIsAllZeros = TValIsAllZeros;
19475       }
19476     }
19477
19478     if (TValIsAllOnes || FValIsAllZeros) {
19479       SDValue Ret;
19480
19481       if (TValIsAllOnes && FValIsAllZeros)
19482         Ret = Cond;
19483       else if (TValIsAllOnes)
19484         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19485                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19486       else if (FValIsAllZeros)
19487         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19488                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19489
19490       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19491     }
19492   }
19493
19494   // Try to fold this VSELECT into a MOVSS/MOVSD
19495   if (N->getOpcode() == ISD::VSELECT &&
19496       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19497     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19498         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19499       bool CanFold = false;
19500       unsigned NumElems = Cond.getNumOperands();
19501       SDValue A = LHS;
19502       SDValue B = RHS;
19503       
19504       if (isZero(Cond.getOperand(0))) {
19505         CanFold = true;
19506
19507         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19508         // fold (vselect <0,-1> -> (movsd A, B)
19509         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19510           CanFold = isAllOnes(Cond.getOperand(i));
19511       } else if (isAllOnes(Cond.getOperand(0))) {
19512         CanFold = true;
19513         std::swap(A, B);
19514
19515         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19516         // fold (vselect <-1,0> -> (movsd B, A)
19517         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19518           CanFold = isZero(Cond.getOperand(i));
19519       }
19520
19521       if (CanFold) {
19522         if (VT == MVT::v4i32 || VT == MVT::v4f32)
19523           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19524         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19525       }
19526
19527       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19528         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19529         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19530         //                             (v2i64 (bitcast B)))))
19531         //
19532         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19533         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19534         //                             (v2f64 (bitcast B)))))
19535         //
19536         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19537         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19538         //                             (v2i64 (bitcast A)))))
19539         //
19540         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19541         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19542         //                             (v2f64 (bitcast A)))))
19543
19544         CanFold = (isZero(Cond.getOperand(0)) &&
19545                    isZero(Cond.getOperand(1)) &&
19546                    isAllOnes(Cond.getOperand(2)) &&
19547                    isAllOnes(Cond.getOperand(3)));
19548
19549         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19550             isAllOnes(Cond.getOperand(1)) &&
19551             isZero(Cond.getOperand(2)) &&
19552             isZero(Cond.getOperand(3))) {
19553           CanFold = true;
19554           std::swap(LHS, RHS);
19555         }
19556
19557         if (CanFold) {
19558           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19559           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19560           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19561           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19562                                                 NewB, DAG);
19563           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19564         }
19565       }
19566     }
19567   }
19568
19569   // If we know that this node is legal then we know that it is going to be
19570   // matched by one of the SSE/AVX BLEND instructions. These instructions only
19571   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19572   // to simplify previous instructions.
19573   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19574       !DCI.isBeforeLegalize() &&
19575       // We explicitly check against v8i16 and v16i16 because, although
19576       // they're marked as Custom, they might only be legal when Cond is a
19577       // build_vector of constants. This will be taken care in a later
19578       // condition.
19579       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19580        VT != MVT::v8i16)) {
19581     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19582
19583     // Don't optimize vector selects that map to mask-registers.
19584     if (BitWidth == 1)
19585       return SDValue();
19586
19587     // Check all uses of that condition operand to check whether it will be
19588     // consumed by non-BLEND instructions, which may depend on all bits are set
19589     // properly.
19590     for (SDNode::use_iterator I = Cond->use_begin(),
19591                               E = Cond->use_end(); I != E; ++I)
19592       if (I->getOpcode() != ISD::VSELECT)
19593         // TODO: Add other opcodes eventually lowered into BLEND.
19594         return SDValue();
19595
19596     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19597     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19598
19599     APInt KnownZero, KnownOne;
19600     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19601                                           DCI.isBeforeLegalizeOps());
19602     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19603         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19604       DCI.CommitTargetLoweringOpt(TLO);
19605   }
19606
19607   // We should generate an X86ISD::BLENDI from a vselect if its argument
19608   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19609   // constants. This specific pattern gets generated when we split a
19610   // selector for a 512 bit vector in a machine without AVX512 (but with
19611   // 256-bit vectors), during legalization:
19612   //
19613   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19614   //
19615   // Iff we find this pattern and the build_vectors are built from
19616   // constants, we translate the vselect into a shuffle_vector that we
19617   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19618   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19619     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19620     if (Shuffle.getNode())
19621       return Shuffle;
19622   }
19623
19624   return SDValue();
19625 }
19626
19627 // Check whether a boolean test is testing a boolean value generated by
19628 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19629 // code.
19630 //
19631 // Simplify the following patterns:
19632 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19633 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19634 // to (Op EFLAGS Cond)
19635 //
19636 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19637 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19638 // to (Op EFLAGS !Cond)
19639 //
19640 // where Op could be BRCOND or CMOV.
19641 //
19642 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19643   // Quit if not CMP and SUB with its value result used.
19644   if (Cmp.getOpcode() != X86ISD::CMP &&
19645       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19646       return SDValue();
19647
19648   // Quit if not used as a boolean value.
19649   if (CC != X86::COND_E && CC != X86::COND_NE)
19650     return SDValue();
19651
19652   // Check CMP operands. One of them should be 0 or 1 and the other should be
19653   // an SetCC or extended from it.
19654   SDValue Op1 = Cmp.getOperand(0);
19655   SDValue Op2 = Cmp.getOperand(1);
19656
19657   SDValue SetCC;
19658   const ConstantSDNode* C = nullptr;
19659   bool needOppositeCond = (CC == X86::COND_E);
19660   bool checkAgainstTrue = false; // Is it a comparison against 1?
19661
19662   if ((C = dyn_cast<ConstantSDNode>(Op1)))
19663     SetCC = Op2;
19664   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19665     SetCC = Op1;
19666   else // Quit if all operands are not constants.
19667     return SDValue();
19668
19669   if (C->getZExtValue() == 1) {
19670     needOppositeCond = !needOppositeCond;
19671     checkAgainstTrue = true;
19672   } else if (C->getZExtValue() != 0)
19673     // Quit if the constant is neither 0 or 1.
19674     return SDValue();
19675
19676   bool truncatedToBoolWithAnd = false;
19677   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19678   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19679          SetCC.getOpcode() == ISD::TRUNCATE ||
19680          SetCC.getOpcode() == ISD::AND) {
19681     if (SetCC.getOpcode() == ISD::AND) {
19682       int OpIdx = -1;
19683       ConstantSDNode *CS;
19684       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19685           CS->getZExtValue() == 1)
19686         OpIdx = 1;
19687       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19688           CS->getZExtValue() == 1)
19689         OpIdx = 0;
19690       if (OpIdx == -1)
19691         break;
19692       SetCC = SetCC.getOperand(OpIdx);
19693       truncatedToBoolWithAnd = true;
19694     } else
19695       SetCC = SetCC.getOperand(0);
19696   }
19697
19698   switch (SetCC.getOpcode()) {
19699   case X86ISD::SETCC_CARRY:
19700     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19701     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19702     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19703     // truncated to i1 using 'and'.
19704     if (checkAgainstTrue && !truncatedToBoolWithAnd)
19705       break;
19706     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19707            "Invalid use of SETCC_CARRY!");
19708     // FALL THROUGH
19709   case X86ISD::SETCC:
19710     // Set the condition code or opposite one if necessary.
19711     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19712     if (needOppositeCond)
19713       CC = X86::GetOppositeBranchCondition(CC);
19714     return SetCC.getOperand(1);
19715   case X86ISD::CMOV: {
19716     // Check whether false/true value has canonical one, i.e. 0 or 1.
19717     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19718     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19719     // Quit if true value is not a constant.
19720     if (!TVal)
19721       return SDValue();
19722     // Quit if false value is not a constant.
19723     if (!FVal) {
19724       SDValue Op = SetCC.getOperand(0);
19725       // Skip 'zext' or 'trunc' node.
19726       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19727           Op.getOpcode() == ISD::TRUNCATE)
19728         Op = Op.getOperand(0);
19729       // A special case for rdrand/rdseed, where 0 is set if false cond is
19730       // found.
19731       if ((Op.getOpcode() != X86ISD::RDRAND &&
19732            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19733         return SDValue();
19734     }
19735     // Quit if false value is not the constant 0 or 1.
19736     bool FValIsFalse = true;
19737     if (FVal && FVal->getZExtValue() != 0) {
19738       if (FVal->getZExtValue() != 1)
19739         return SDValue();
19740       // If FVal is 1, opposite cond is needed.
19741       needOppositeCond = !needOppositeCond;
19742       FValIsFalse = false;
19743     }
19744     // Quit if TVal is not the constant opposite of FVal.
19745     if (FValIsFalse && TVal->getZExtValue() != 1)
19746       return SDValue();
19747     if (!FValIsFalse && TVal->getZExtValue() != 0)
19748       return SDValue();
19749     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19750     if (needOppositeCond)
19751       CC = X86::GetOppositeBranchCondition(CC);
19752     return SetCC.getOperand(3);
19753   }
19754   }
19755
19756   return SDValue();
19757 }
19758
19759 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19760 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19761                                   TargetLowering::DAGCombinerInfo &DCI,
19762                                   const X86Subtarget *Subtarget) {
19763   SDLoc DL(N);
19764
19765   // If the flag operand isn't dead, don't touch this CMOV.
19766   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19767     return SDValue();
19768
19769   SDValue FalseOp = N->getOperand(0);
19770   SDValue TrueOp = N->getOperand(1);
19771   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19772   SDValue Cond = N->getOperand(3);
19773
19774   if (CC == X86::COND_E || CC == X86::COND_NE) {
19775     switch (Cond.getOpcode()) {
19776     default: break;
19777     case X86ISD::BSR:
19778     case X86ISD::BSF:
19779       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19780       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19781         return (CC == X86::COND_E) ? FalseOp : TrueOp;
19782     }
19783   }
19784
19785   SDValue Flags;
19786
19787   Flags = checkBoolTestSetCCCombine(Cond, CC);
19788   if (Flags.getNode() &&
19789       // Extra check as FCMOV only supports a subset of X86 cond.
19790       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19791     SDValue Ops[] = { FalseOp, TrueOp,
19792                       DAG.getConstant(CC, MVT::i8), Flags };
19793     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19794   }
19795
19796   // If this is a select between two integer constants, try to do some
19797   // optimizations.  Note that the operands are ordered the opposite of SELECT
19798   // operands.
19799   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19800     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19801       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19802       // larger than FalseC (the false value).
19803       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19804         CC = X86::GetOppositeBranchCondition(CC);
19805         std::swap(TrueC, FalseC);
19806         std::swap(TrueOp, FalseOp);
19807       }
19808
19809       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
19810       // This is efficient for any integer data type (including i8/i16) and
19811       // shift amount.
19812       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19813         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19814                            DAG.getConstant(CC, MVT::i8), Cond);
19815
19816         // Zero extend the condition if needed.
19817         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19818
19819         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19820         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19821                            DAG.getConstant(ShAmt, MVT::i8));
19822         if (N->getNumValues() == 2)  // Dead flag value?
19823           return DCI.CombineTo(N, Cond, SDValue());
19824         return Cond;
19825       }
19826
19827       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
19828       // for any integer data type, including i8/i16.
19829       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19830         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19831                            DAG.getConstant(CC, MVT::i8), Cond);
19832
19833         // Zero extend the condition if needed.
19834         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19835                            FalseC->getValueType(0), Cond);
19836         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19837                            SDValue(FalseC, 0));
19838
19839         if (N->getNumValues() == 2)  // Dead flag value?
19840           return DCI.CombineTo(N, Cond, SDValue());
19841         return Cond;
19842       }
19843
19844       // Optimize cases that will turn into an LEA instruction.  This requires
19845       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19846       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19847         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19848         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19849
19850         bool isFastMultiplier = false;
19851         if (Diff < 10) {
19852           switch ((unsigned char)Diff) {
19853           default: break;
19854           case 1:  // result = add base, cond
19855           case 2:  // result = lea base(    , cond*2)
19856           case 3:  // result = lea base(cond, cond*2)
19857           case 4:  // result = lea base(    , cond*4)
19858           case 5:  // result = lea base(cond, cond*4)
19859           case 8:  // result = lea base(    , cond*8)
19860           case 9:  // result = lea base(cond, cond*8)
19861             isFastMultiplier = true;
19862             break;
19863           }
19864         }
19865
19866         if (isFastMultiplier) {
19867           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19868           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19869                              DAG.getConstant(CC, MVT::i8), Cond);
19870           // Zero extend the condition if needed.
19871           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19872                              Cond);
19873           // Scale the condition by the difference.
19874           if (Diff != 1)
19875             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19876                                DAG.getConstant(Diff, Cond.getValueType()));
19877
19878           // Add the base if non-zero.
19879           if (FalseC->getAPIntValue() != 0)
19880             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19881                                SDValue(FalseC, 0));
19882           if (N->getNumValues() == 2)  // Dead flag value?
19883             return DCI.CombineTo(N, Cond, SDValue());
19884           return Cond;
19885         }
19886       }
19887     }
19888   }
19889
19890   // Handle these cases:
19891   //   (select (x != c), e, c) -> select (x != c), e, x),
19892   //   (select (x == c), c, e) -> select (x == c), x, e)
19893   // where the c is an integer constant, and the "select" is the combination
19894   // of CMOV and CMP.
19895   //
19896   // The rationale for this change is that the conditional-move from a constant
19897   // needs two instructions, however, conditional-move from a register needs
19898   // only one instruction.
19899   //
19900   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19901   //  some instruction-combining opportunities. This opt needs to be
19902   //  postponed as late as possible.
19903   //
19904   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19905     // the DCI.xxxx conditions are provided to postpone the optimization as
19906     // late as possible.
19907
19908     ConstantSDNode *CmpAgainst = nullptr;
19909     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19910         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19911         !isa<ConstantSDNode>(Cond.getOperand(0))) {
19912
19913       if (CC == X86::COND_NE &&
19914           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19915         CC = X86::GetOppositeBranchCondition(CC);
19916         std::swap(TrueOp, FalseOp);
19917       }
19918
19919       if (CC == X86::COND_E &&
19920           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19921         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19922                           DAG.getConstant(CC, MVT::i8), Cond };
19923         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19924       }
19925     }
19926   }
19927
19928   return SDValue();
19929 }
19930
19931 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19932                                                 const X86Subtarget *Subtarget) {
19933   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19934   switch (IntNo) {
19935   default: return SDValue();
19936   // SSE/AVX/AVX2 blend intrinsics.
19937   case Intrinsic::x86_avx2_pblendvb:
19938   case Intrinsic::x86_avx2_pblendw:
19939   case Intrinsic::x86_avx2_pblendd_128:
19940   case Intrinsic::x86_avx2_pblendd_256:
19941     // Don't try to simplify this intrinsic if we don't have AVX2.
19942     if (!Subtarget->hasAVX2())
19943       return SDValue();
19944     // FALL-THROUGH
19945   case Intrinsic::x86_avx_blend_pd_256:
19946   case Intrinsic::x86_avx_blend_ps_256:
19947   case Intrinsic::x86_avx_blendv_pd_256:
19948   case Intrinsic::x86_avx_blendv_ps_256:
19949     // Don't try to simplify this intrinsic if we don't have AVX.
19950     if (!Subtarget->hasAVX())
19951       return SDValue();
19952     // FALL-THROUGH
19953   case Intrinsic::x86_sse41_pblendw:
19954   case Intrinsic::x86_sse41_blendpd:
19955   case Intrinsic::x86_sse41_blendps:
19956   case Intrinsic::x86_sse41_blendvps:
19957   case Intrinsic::x86_sse41_blendvpd:
19958   case Intrinsic::x86_sse41_pblendvb: {
19959     SDValue Op0 = N->getOperand(1);
19960     SDValue Op1 = N->getOperand(2);
19961     SDValue Mask = N->getOperand(3);
19962
19963     // Don't try to simplify this intrinsic if we don't have SSE4.1.
19964     if (!Subtarget->hasSSE41())
19965       return SDValue();
19966
19967     // fold (blend A, A, Mask) -> A
19968     if (Op0 == Op1)
19969       return Op0;
19970     // fold (blend A, B, allZeros) -> A
19971     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19972       return Op0;
19973     // fold (blend A, B, allOnes) -> B
19974     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19975       return Op1;
19976     
19977     // Simplify the case where the mask is a constant i32 value.
19978     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
19979       if (C->isNullValue())
19980         return Op0;
19981       if (C->isAllOnesValue())
19982         return Op1;
19983     }
19984
19985     return SDValue();
19986   }
19987
19988   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
19989   case Intrinsic::x86_sse2_psrai_w:
19990   case Intrinsic::x86_sse2_psrai_d:
19991   case Intrinsic::x86_avx2_psrai_w:
19992   case Intrinsic::x86_avx2_psrai_d:
19993   case Intrinsic::x86_sse2_psra_w:
19994   case Intrinsic::x86_sse2_psra_d:
19995   case Intrinsic::x86_avx2_psra_w:
19996   case Intrinsic::x86_avx2_psra_d: {
19997     SDValue Op0 = N->getOperand(1);
19998     SDValue Op1 = N->getOperand(2);
19999     EVT VT = Op0.getValueType();
20000     assert(VT.isVector() && "Expected a vector type!");
20001
20002     if (isa<BuildVectorSDNode>(Op1))
20003       Op1 = Op1.getOperand(0);
20004
20005     if (!isa<ConstantSDNode>(Op1))
20006       return SDValue();
20007
20008     EVT SVT = VT.getVectorElementType();
20009     unsigned SVTBits = SVT.getSizeInBits();
20010
20011     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20012     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20013     uint64_t ShAmt = C.getZExtValue();
20014
20015     // Don't try to convert this shift into a ISD::SRA if the shift
20016     // count is bigger than or equal to the element size.
20017     if (ShAmt >= SVTBits)
20018       return SDValue();
20019
20020     // Trivial case: if the shift count is zero, then fold this
20021     // into the first operand.
20022     if (ShAmt == 0)
20023       return Op0;
20024
20025     // Replace this packed shift intrinsic with a target independent
20026     // shift dag node.
20027     SDValue Splat = DAG.getConstant(C, VT);
20028     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20029   }
20030   }
20031 }
20032
20033 /// PerformMulCombine - Optimize a single multiply with constant into two
20034 /// in order to implement it with two cheaper instructions, e.g.
20035 /// LEA + SHL, LEA + LEA.
20036 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20037                                  TargetLowering::DAGCombinerInfo &DCI) {
20038   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20039     return SDValue();
20040
20041   EVT VT = N->getValueType(0);
20042   if (VT != MVT::i64)
20043     return SDValue();
20044
20045   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20046   if (!C)
20047     return SDValue();
20048   uint64_t MulAmt = C->getZExtValue();
20049   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20050     return SDValue();
20051
20052   uint64_t MulAmt1 = 0;
20053   uint64_t MulAmt2 = 0;
20054   if ((MulAmt % 9) == 0) {
20055     MulAmt1 = 9;
20056     MulAmt2 = MulAmt / 9;
20057   } else if ((MulAmt % 5) == 0) {
20058     MulAmt1 = 5;
20059     MulAmt2 = MulAmt / 5;
20060   } else if ((MulAmt % 3) == 0) {
20061     MulAmt1 = 3;
20062     MulAmt2 = MulAmt / 3;
20063   }
20064   if (MulAmt2 &&
20065       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20066     SDLoc DL(N);
20067
20068     if (isPowerOf2_64(MulAmt2) &&
20069         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20070       // If second multiplifer is pow2, issue it first. We want the multiply by
20071       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20072       // is an add.
20073       std::swap(MulAmt1, MulAmt2);
20074
20075     SDValue NewMul;
20076     if (isPowerOf2_64(MulAmt1))
20077       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20078                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20079     else
20080       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20081                            DAG.getConstant(MulAmt1, VT));
20082
20083     if (isPowerOf2_64(MulAmt2))
20084       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20085                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20086     else
20087       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20088                            DAG.getConstant(MulAmt2, VT));
20089
20090     // Do not add new nodes to DAG combiner worklist.
20091     DCI.CombineTo(N, NewMul, false);
20092   }
20093   return SDValue();
20094 }
20095
20096 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20097   SDValue N0 = N->getOperand(0);
20098   SDValue N1 = N->getOperand(1);
20099   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20100   EVT VT = N0.getValueType();
20101
20102   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20103   // since the result of setcc_c is all zero's or all ones.
20104   if (VT.isInteger() && !VT.isVector() &&
20105       N1C && N0.getOpcode() == ISD::AND &&
20106       N0.getOperand(1).getOpcode() == ISD::Constant) {
20107     SDValue N00 = N0.getOperand(0);
20108     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20109         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20110           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20111          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20112       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20113       APInt ShAmt = N1C->getAPIntValue();
20114       Mask = Mask.shl(ShAmt);
20115       if (Mask != 0)
20116         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20117                            N00, DAG.getConstant(Mask, VT));
20118     }
20119   }
20120
20121   // Hardware support for vector shifts is sparse which makes us scalarize the
20122   // vector operations in many cases. Also, on sandybridge ADD is faster than
20123   // shl.
20124   // (shl V, 1) -> add V,V
20125   if (isSplatVector(N1.getNode())) {
20126     assert(N0.getValueType().isVector() && "Invalid vector shift type");
20127     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
20128     // We shift all of the values by one. In many cases we do not have
20129     // hardware support for this operation. This is better expressed as an ADD
20130     // of two values.
20131     if (N1C && (1 == N1C->getZExtValue())) {
20132       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20133     }
20134   }
20135
20136   return SDValue();
20137 }
20138
20139 /// \brief Returns a vector of 0s if the node in input is a vector logical
20140 /// shift by a constant amount which is known to be bigger than or equal
20141 /// to the vector element size in bits.
20142 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20143                                       const X86Subtarget *Subtarget) {
20144   EVT VT = N->getValueType(0);
20145
20146   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20147       (!Subtarget->hasInt256() ||
20148        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20149     return SDValue();
20150
20151   SDValue Amt = N->getOperand(1);
20152   SDLoc DL(N);
20153   if (isSplatVector(Amt.getNode())) {
20154     SDValue SclrAmt = Amt->getOperand(0);
20155     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
20156       APInt ShiftAmt = C->getAPIntValue();
20157       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20158
20159       // SSE2/AVX2 logical shifts always return a vector of 0s
20160       // if the shift amount is bigger than or equal to
20161       // the element size. The constant shift amount will be
20162       // encoded as a 8-bit immediate.
20163       if (ShiftAmt.trunc(8).uge(MaxAmount))
20164         return getZeroVector(VT, Subtarget, DAG, DL);
20165     }
20166   }
20167
20168   return SDValue();
20169 }
20170
20171 /// PerformShiftCombine - Combine shifts.
20172 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20173                                    TargetLowering::DAGCombinerInfo &DCI,
20174                                    const X86Subtarget *Subtarget) {
20175   if (N->getOpcode() == ISD::SHL) {
20176     SDValue V = PerformSHLCombine(N, DAG);
20177     if (V.getNode()) return V;
20178   }
20179
20180   if (N->getOpcode() != ISD::SRA) {
20181     // Try to fold this logical shift into a zero vector.
20182     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20183     if (V.getNode()) return V;
20184   }
20185
20186   return SDValue();
20187 }
20188
20189 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20190 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20191 // and friends.  Likewise for OR -> CMPNEQSS.
20192 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20193                             TargetLowering::DAGCombinerInfo &DCI,
20194                             const X86Subtarget *Subtarget) {
20195   unsigned opcode;
20196
20197   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20198   // we're requiring SSE2 for both.
20199   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20200     SDValue N0 = N->getOperand(0);
20201     SDValue N1 = N->getOperand(1);
20202     SDValue CMP0 = N0->getOperand(1);
20203     SDValue CMP1 = N1->getOperand(1);
20204     SDLoc DL(N);
20205
20206     // The SETCCs should both refer to the same CMP.
20207     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20208       return SDValue();
20209
20210     SDValue CMP00 = CMP0->getOperand(0);
20211     SDValue CMP01 = CMP0->getOperand(1);
20212     EVT     VT    = CMP00.getValueType();
20213
20214     if (VT == MVT::f32 || VT == MVT::f64) {
20215       bool ExpectingFlags = false;
20216       // Check for any users that want flags:
20217       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20218            !ExpectingFlags && UI != UE; ++UI)
20219         switch (UI->getOpcode()) {
20220         default:
20221         case ISD::BR_CC:
20222         case ISD::BRCOND:
20223         case ISD::SELECT:
20224           ExpectingFlags = true;
20225           break;
20226         case ISD::CopyToReg:
20227         case ISD::SIGN_EXTEND:
20228         case ISD::ZERO_EXTEND:
20229         case ISD::ANY_EXTEND:
20230           break;
20231         }
20232
20233       if (!ExpectingFlags) {
20234         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20235         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20236
20237         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20238           X86::CondCode tmp = cc0;
20239           cc0 = cc1;
20240           cc1 = tmp;
20241         }
20242
20243         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20244             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20245           // FIXME: need symbolic constants for these magic numbers.
20246           // See X86ATTInstPrinter.cpp:printSSECC().
20247           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20248           if (Subtarget->hasAVX512()) {
20249             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20250                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20251             if (N->getValueType(0) != MVT::i1)
20252               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20253                                  FSetCC);
20254             return FSetCC;
20255           }
20256           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20257                                               CMP00.getValueType(), CMP00, CMP01,
20258                                               DAG.getConstant(x86cc, MVT::i8));
20259
20260           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20261           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20262
20263           if (is64BitFP && !Subtarget->is64Bit()) {
20264             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20265             // 64-bit integer, since that's not a legal type. Since
20266             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20267             // bits, but can do this little dance to extract the lowest 32 bits
20268             // and work with those going forward.
20269             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20270                                            OnesOrZeroesF);
20271             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20272                                            Vector64);
20273             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20274                                         Vector32, DAG.getIntPtrConstant(0));
20275             IntVT = MVT::i32;
20276           }
20277
20278           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20279           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20280                                       DAG.getConstant(1, IntVT));
20281           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20282           return OneBitOfTruth;
20283         }
20284       }
20285     }
20286   }
20287   return SDValue();
20288 }
20289
20290 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20291 /// so it can be folded inside ANDNP.
20292 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20293   EVT VT = N->getValueType(0);
20294
20295   // Match direct AllOnes for 128 and 256-bit vectors
20296   if (ISD::isBuildVectorAllOnes(N))
20297     return true;
20298
20299   // Look through a bit convert.
20300   if (N->getOpcode() == ISD::BITCAST)
20301     N = N->getOperand(0).getNode();
20302
20303   // Sometimes the operand may come from a insert_subvector building a 256-bit
20304   // allones vector
20305   if (VT.is256BitVector() &&
20306       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20307     SDValue V1 = N->getOperand(0);
20308     SDValue V2 = N->getOperand(1);
20309
20310     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20311         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20312         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20313         ISD::isBuildVectorAllOnes(V2.getNode()))
20314       return true;
20315   }
20316
20317   return false;
20318 }
20319
20320 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20321 // register. In most cases we actually compare or select YMM-sized registers
20322 // and mixing the two types creates horrible code. This method optimizes
20323 // some of the transition sequences.
20324 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20325                                  TargetLowering::DAGCombinerInfo &DCI,
20326                                  const X86Subtarget *Subtarget) {
20327   EVT VT = N->getValueType(0);
20328   if (!VT.is256BitVector())
20329     return SDValue();
20330
20331   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20332           N->getOpcode() == ISD::ZERO_EXTEND ||
20333           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20334
20335   SDValue Narrow = N->getOperand(0);
20336   EVT NarrowVT = Narrow->getValueType(0);
20337   if (!NarrowVT.is128BitVector())
20338     return SDValue();
20339
20340   if (Narrow->getOpcode() != ISD::XOR &&
20341       Narrow->getOpcode() != ISD::AND &&
20342       Narrow->getOpcode() != ISD::OR)
20343     return SDValue();
20344
20345   SDValue N0  = Narrow->getOperand(0);
20346   SDValue N1  = Narrow->getOperand(1);
20347   SDLoc DL(Narrow);
20348
20349   // The Left side has to be a trunc.
20350   if (N0.getOpcode() != ISD::TRUNCATE)
20351     return SDValue();
20352
20353   // The type of the truncated inputs.
20354   EVT WideVT = N0->getOperand(0)->getValueType(0);
20355   if (WideVT != VT)
20356     return SDValue();
20357
20358   // The right side has to be a 'trunc' or a constant vector.
20359   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20360   bool RHSConst = (isSplatVector(N1.getNode()) &&
20361                    isa<ConstantSDNode>(N1->getOperand(0)));
20362   if (!RHSTrunc && !RHSConst)
20363     return SDValue();
20364
20365   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20366
20367   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20368     return SDValue();
20369
20370   // Set N0 and N1 to hold the inputs to the new wide operation.
20371   N0 = N0->getOperand(0);
20372   if (RHSConst) {
20373     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20374                      N1->getOperand(0));
20375     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20376     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20377   } else if (RHSTrunc) {
20378     N1 = N1->getOperand(0);
20379   }
20380
20381   // Generate the wide operation.
20382   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20383   unsigned Opcode = N->getOpcode();
20384   switch (Opcode) {
20385   case ISD::ANY_EXTEND:
20386     return Op;
20387   case ISD::ZERO_EXTEND: {
20388     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20389     APInt Mask = APInt::getAllOnesValue(InBits);
20390     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20391     return DAG.getNode(ISD::AND, DL, VT,
20392                        Op, DAG.getConstant(Mask, VT));
20393   }
20394   case ISD::SIGN_EXTEND:
20395     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20396                        Op, DAG.getValueType(NarrowVT));
20397   default:
20398     llvm_unreachable("Unexpected opcode");
20399   }
20400 }
20401
20402 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20403                                  TargetLowering::DAGCombinerInfo &DCI,
20404                                  const X86Subtarget *Subtarget) {
20405   EVT VT = N->getValueType(0);
20406   if (DCI.isBeforeLegalizeOps())
20407     return SDValue();
20408
20409   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20410   if (R.getNode())
20411     return R;
20412
20413   // Create BEXTR instructions
20414   // BEXTR is ((X >> imm) & (2**size-1))
20415   if (VT == MVT::i32 || VT == MVT::i64) {
20416     SDValue N0 = N->getOperand(0);
20417     SDValue N1 = N->getOperand(1);
20418     SDLoc DL(N);
20419
20420     // Check for BEXTR.
20421     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20422         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20423       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20424       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20425       if (MaskNode && ShiftNode) {
20426         uint64_t Mask = MaskNode->getZExtValue();
20427         uint64_t Shift = ShiftNode->getZExtValue();
20428         if (isMask_64(Mask)) {
20429           uint64_t MaskSize = CountPopulation_64(Mask);
20430           if (Shift + MaskSize <= VT.getSizeInBits())
20431             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20432                                DAG.getConstant(Shift | (MaskSize << 8), VT));
20433         }
20434       }
20435     } // BEXTR
20436
20437     return SDValue();
20438   }
20439
20440   // Want to form ANDNP nodes:
20441   // 1) In the hopes of then easily combining them with OR and AND nodes
20442   //    to form PBLEND/PSIGN.
20443   // 2) To match ANDN packed intrinsics
20444   if (VT != MVT::v2i64 && VT != MVT::v4i64)
20445     return SDValue();
20446
20447   SDValue N0 = N->getOperand(0);
20448   SDValue N1 = N->getOperand(1);
20449   SDLoc DL(N);
20450
20451   // Check LHS for vnot
20452   if (N0.getOpcode() == ISD::XOR &&
20453       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20454       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20455     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20456
20457   // Check RHS for vnot
20458   if (N1.getOpcode() == ISD::XOR &&
20459       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20460       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20461     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20462
20463   return SDValue();
20464 }
20465
20466 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20467                                 TargetLowering::DAGCombinerInfo &DCI,
20468                                 const X86Subtarget *Subtarget) {
20469   if (DCI.isBeforeLegalizeOps())
20470     return SDValue();
20471
20472   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20473   if (R.getNode())
20474     return R;
20475
20476   SDValue N0 = N->getOperand(0);
20477   SDValue N1 = N->getOperand(1);
20478   EVT VT = N->getValueType(0);
20479
20480   // look for psign/blend
20481   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20482     if (!Subtarget->hasSSSE3() ||
20483         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20484       return SDValue();
20485
20486     // Canonicalize pandn to RHS
20487     if (N0.getOpcode() == X86ISD::ANDNP)
20488       std::swap(N0, N1);
20489     // or (and (m, y), (pandn m, x))
20490     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20491       SDValue Mask = N1.getOperand(0);
20492       SDValue X    = N1.getOperand(1);
20493       SDValue Y;
20494       if (N0.getOperand(0) == Mask)
20495         Y = N0.getOperand(1);
20496       if (N0.getOperand(1) == Mask)
20497         Y = N0.getOperand(0);
20498
20499       // Check to see if the mask appeared in both the AND and ANDNP and
20500       if (!Y.getNode())
20501         return SDValue();
20502
20503       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20504       // Look through mask bitcast.
20505       if (Mask.getOpcode() == ISD::BITCAST)
20506         Mask = Mask.getOperand(0);
20507       if (X.getOpcode() == ISD::BITCAST)
20508         X = X.getOperand(0);
20509       if (Y.getOpcode() == ISD::BITCAST)
20510         Y = Y.getOperand(0);
20511
20512       EVT MaskVT = Mask.getValueType();
20513
20514       // Validate that the Mask operand is a vector sra node.
20515       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20516       // there is no psrai.b
20517       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20518       unsigned SraAmt = ~0;
20519       if (Mask.getOpcode() == ISD::SRA) {
20520         SDValue Amt = Mask.getOperand(1);
20521         if (isSplatVector(Amt.getNode())) {
20522           SDValue SclrAmt = Amt->getOperand(0);
20523           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
20524             SraAmt = C->getZExtValue();
20525         }
20526       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20527         SDValue SraC = Mask.getOperand(1);
20528         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
20529       }
20530       if ((SraAmt + 1) != EltBits)
20531         return SDValue();
20532
20533       SDLoc DL(N);
20534
20535       // Now we know we at least have a plendvb with the mask val.  See if
20536       // we can form a psignb/w/d.
20537       // psign = x.type == y.type == mask.type && y = sub(0, x);
20538       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20539           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20540           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20541         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20542                "Unsupported VT for PSIGN");
20543         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20544         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20545       }
20546       // PBLENDVB only available on SSE 4.1
20547       if (!Subtarget->hasSSE41())
20548         return SDValue();
20549
20550       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20551
20552       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20553       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20554       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20555       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20556       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20557     }
20558   }
20559
20560   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20561     return SDValue();
20562
20563   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20564   MachineFunction &MF = DAG.getMachineFunction();
20565   bool OptForSize = MF.getFunction()->getAttributes().
20566     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20567
20568   // SHLD/SHRD instructions have lower register pressure, but on some
20569   // platforms they have higher latency than the equivalent
20570   // series of shifts/or that would otherwise be generated.
20571   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20572   // have higher latencies and we are not optimizing for size.
20573   if (!OptForSize && Subtarget->isSHLDSlow())
20574     return SDValue();
20575
20576   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20577     std::swap(N0, N1);
20578   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20579     return SDValue();
20580   if (!N0.hasOneUse() || !N1.hasOneUse())
20581     return SDValue();
20582
20583   SDValue ShAmt0 = N0.getOperand(1);
20584   if (ShAmt0.getValueType() != MVT::i8)
20585     return SDValue();
20586   SDValue ShAmt1 = N1.getOperand(1);
20587   if (ShAmt1.getValueType() != MVT::i8)
20588     return SDValue();
20589   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20590     ShAmt0 = ShAmt0.getOperand(0);
20591   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20592     ShAmt1 = ShAmt1.getOperand(0);
20593
20594   SDLoc DL(N);
20595   unsigned Opc = X86ISD::SHLD;
20596   SDValue Op0 = N0.getOperand(0);
20597   SDValue Op1 = N1.getOperand(0);
20598   if (ShAmt0.getOpcode() == ISD::SUB) {
20599     Opc = X86ISD::SHRD;
20600     std::swap(Op0, Op1);
20601     std::swap(ShAmt0, ShAmt1);
20602   }
20603
20604   unsigned Bits = VT.getSizeInBits();
20605   if (ShAmt1.getOpcode() == ISD::SUB) {
20606     SDValue Sum = ShAmt1.getOperand(0);
20607     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20608       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20609       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20610         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20611       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20612         return DAG.getNode(Opc, DL, VT,
20613                            Op0, Op1,
20614                            DAG.getNode(ISD::TRUNCATE, DL,
20615                                        MVT::i8, ShAmt0));
20616     }
20617   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20618     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20619     if (ShAmt0C &&
20620         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20621       return DAG.getNode(Opc, DL, VT,
20622                          N0.getOperand(0), N1.getOperand(0),
20623                          DAG.getNode(ISD::TRUNCATE, DL,
20624                                        MVT::i8, ShAmt0));
20625   }
20626
20627   return SDValue();
20628 }
20629
20630 // Generate NEG and CMOV for integer abs.
20631 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20632   EVT VT = N->getValueType(0);
20633
20634   // Since X86 does not have CMOV for 8-bit integer, we don't convert
20635   // 8-bit integer abs to NEG and CMOV.
20636   if (VT.isInteger() && VT.getSizeInBits() == 8)
20637     return SDValue();
20638
20639   SDValue N0 = N->getOperand(0);
20640   SDValue N1 = N->getOperand(1);
20641   SDLoc DL(N);
20642
20643   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20644   // and change it to SUB and CMOV.
20645   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20646       N0.getOpcode() == ISD::ADD &&
20647       N0.getOperand(1) == N1 &&
20648       N1.getOpcode() == ISD::SRA &&
20649       N1.getOperand(0) == N0.getOperand(0))
20650     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20651       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20652         // Generate SUB & CMOV.
20653         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20654                                   DAG.getConstant(0, VT), N0.getOperand(0));
20655
20656         SDValue Ops[] = { N0.getOperand(0), Neg,
20657                           DAG.getConstant(X86::COND_GE, MVT::i8),
20658                           SDValue(Neg.getNode(), 1) };
20659         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20660       }
20661   return SDValue();
20662 }
20663
20664 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20665 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20666                                  TargetLowering::DAGCombinerInfo &DCI,
20667                                  const X86Subtarget *Subtarget) {
20668   if (DCI.isBeforeLegalizeOps())
20669     return SDValue();
20670
20671   if (Subtarget->hasCMov()) {
20672     SDValue RV = performIntegerAbsCombine(N, DAG);
20673     if (RV.getNode())
20674       return RV;
20675   }
20676
20677   return SDValue();
20678 }
20679
20680 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20681 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20682                                   TargetLowering::DAGCombinerInfo &DCI,
20683                                   const X86Subtarget *Subtarget) {
20684   LoadSDNode *Ld = cast<LoadSDNode>(N);
20685   EVT RegVT = Ld->getValueType(0);
20686   EVT MemVT = Ld->getMemoryVT();
20687   SDLoc dl(Ld);
20688   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20689   unsigned RegSz = RegVT.getSizeInBits();
20690
20691   // On Sandybridge unaligned 256bit loads are inefficient.
20692   ISD::LoadExtType Ext = Ld->getExtensionType();
20693   unsigned Alignment = Ld->getAlignment();
20694   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20695   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20696       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20697     unsigned NumElems = RegVT.getVectorNumElements();
20698     if (NumElems < 2)
20699       return SDValue();
20700
20701     SDValue Ptr = Ld->getBasePtr();
20702     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20703
20704     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20705                                   NumElems/2);
20706     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20707                                 Ld->getPointerInfo(), Ld->isVolatile(),
20708                                 Ld->isNonTemporal(), Ld->isInvariant(),
20709                                 Alignment);
20710     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20711     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20712                                 Ld->getPointerInfo(), Ld->isVolatile(),
20713                                 Ld->isNonTemporal(), Ld->isInvariant(),
20714                                 std::min(16U, Alignment));
20715     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20716                              Load1.getValue(1),
20717                              Load2.getValue(1));
20718
20719     SDValue NewVec = DAG.getUNDEF(RegVT);
20720     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20721     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20722     return DCI.CombineTo(N, NewVec, TF, true);
20723   }
20724
20725   // If this is a vector EXT Load then attempt to optimize it using a
20726   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20727   // expansion is still better than scalar code.
20728   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20729   // emit a shuffle and a arithmetic shift.
20730   // TODO: It is possible to support ZExt by zeroing the undef values
20731   // during the shuffle phase or after the shuffle.
20732   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20733       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20734     assert(MemVT != RegVT && "Cannot extend to the same type");
20735     assert(MemVT.isVector() && "Must load a vector from memory");
20736
20737     unsigned NumElems = RegVT.getVectorNumElements();
20738     unsigned MemSz = MemVT.getSizeInBits();
20739     assert(RegSz > MemSz && "Register size must be greater than the mem size");
20740
20741     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20742       return SDValue();
20743
20744     // All sizes must be a power of two.
20745     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20746       return SDValue();
20747
20748     // Attempt to load the original value using scalar loads.
20749     // Find the largest scalar type that divides the total loaded size.
20750     MVT SclrLoadTy = MVT::i8;
20751     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20752          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20753       MVT Tp = (MVT::SimpleValueType)tp;
20754       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20755         SclrLoadTy = Tp;
20756       }
20757     }
20758
20759     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20760     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20761         (64 <= MemSz))
20762       SclrLoadTy = MVT::f64;
20763
20764     // Calculate the number of scalar loads that we need to perform
20765     // in order to load our vector from memory.
20766     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20767     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20768       return SDValue();
20769
20770     unsigned loadRegZize = RegSz;
20771     if (Ext == ISD::SEXTLOAD && RegSz == 256)
20772       loadRegZize /= 2;
20773
20774     // Represent our vector as a sequence of elements which are the
20775     // largest scalar that we can load.
20776     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20777       loadRegZize/SclrLoadTy.getSizeInBits());
20778
20779     // Represent the data using the same element type that is stored in
20780     // memory. In practice, we ''widen'' MemVT.
20781     EVT WideVecVT =
20782           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20783                        loadRegZize/MemVT.getScalarType().getSizeInBits());
20784
20785     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20786       "Invalid vector type");
20787
20788     // We can't shuffle using an illegal type.
20789     if (!TLI.isTypeLegal(WideVecVT))
20790       return SDValue();
20791
20792     SmallVector<SDValue, 8> Chains;
20793     SDValue Ptr = Ld->getBasePtr();
20794     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20795                                         TLI.getPointerTy());
20796     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20797
20798     for (unsigned i = 0; i < NumLoads; ++i) {
20799       // Perform a single load.
20800       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20801                                        Ptr, Ld->getPointerInfo(),
20802                                        Ld->isVolatile(), Ld->isNonTemporal(),
20803                                        Ld->isInvariant(), Ld->getAlignment());
20804       Chains.push_back(ScalarLoad.getValue(1));
20805       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20806       // another round of DAGCombining.
20807       if (i == 0)
20808         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20809       else
20810         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20811                           ScalarLoad, DAG.getIntPtrConstant(i));
20812
20813       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20814     }
20815
20816     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20817
20818     // Bitcast the loaded value to a vector of the original element type, in
20819     // the size of the target vector type.
20820     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20821     unsigned SizeRatio = RegSz/MemSz;
20822
20823     if (Ext == ISD::SEXTLOAD) {
20824       // If we have SSE4.1 we can directly emit a VSEXT node.
20825       if (Subtarget->hasSSE41()) {
20826         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20827         return DCI.CombineTo(N, Sext, TF, true);
20828       }
20829
20830       // Otherwise we'll shuffle the small elements in the high bits of the
20831       // larger type and perform an arithmetic shift. If the shift is not legal
20832       // it's better to scalarize.
20833       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20834         return SDValue();
20835
20836       // Redistribute the loaded elements into the different locations.
20837       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20838       for (unsigned i = 0; i != NumElems; ++i)
20839         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20840
20841       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20842                                            DAG.getUNDEF(WideVecVT),
20843                                            &ShuffleVec[0]);
20844
20845       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20846
20847       // Build the arithmetic shift.
20848       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20849                      MemVT.getVectorElementType().getSizeInBits();
20850       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20851                           DAG.getConstant(Amt, RegVT));
20852
20853       return DCI.CombineTo(N, Shuff, TF, true);
20854     }
20855
20856     // Redistribute the loaded elements into the different locations.
20857     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20858     for (unsigned i = 0; i != NumElems; ++i)
20859       ShuffleVec[i*SizeRatio] = i;
20860
20861     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20862                                          DAG.getUNDEF(WideVecVT),
20863                                          &ShuffleVec[0]);
20864
20865     // Bitcast to the requested type.
20866     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20867     // Replace the original load with the new sequence
20868     // and return the new chain.
20869     return DCI.CombineTo(N, Shuff, TF, true);
20870   }
20871
20872   return SDValue();
20873 }
20874
20875 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20876 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20877                                    const X86Subtarget *Subtarget) {
20878   StoreSDNode *St = cast<StoreSDNode>(N);
20879   EVT VT = St->getValue().getValueType();
20880   EVT StVT = St->getMemoryVT();
20881   SDLoc dl(St);
20882   SDValue StoredVal = St->getOperand(1);
20883   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20884
20885   // If we are saving a concatenation of two XMM registers, perform two stores.
20886   // On Sandy Bridge, 256-bit memory operations are executed by two
20887   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20888   // memory  operation.
20889   unsigned Alignment = St->getAlignment();
20890   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20891   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20892       StVT == VT && !IsAligned) {
20893     unsigned NumElems = VT.getVectorNumElements();
20894     if (NumElems < 2)
20895       return SDValue();
20896
20897     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20898     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20899
20900     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20901     SDValue Ptr0 = St->getBasePtr();
20902     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20903
20904     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20905                                 St->getPointerInfo(), St->isVolatile(),
20906                                 St->isNonTemporal(), Alignment);
20907     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20908                                 St->getPointerInfo(), St->isVolatile(),
20909                                 St->isNonTemporal(),
20910                                 std::min(16U, Alignment));
20911     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20912   }
20913
20914   // Optimize trunc store (of multiple scalars) to shuffle and store.
20915   // First, pack all of the elements in one place. Next, store to memory
20916   // in fewer chunks.
20917   if (St->isTruncatingStore() && VT.isVector()) {
20918     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20919     unsigned NumElems = VT.getVectorNumElements();
20920     assert(StVT != VT && "Cannot truncate to the same type");
20921     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20922     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20923
20924     // From, To sizes and ElemCount must be pow of two
20925     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20926     // We are going to use the original vector elt for storing.
20927     // Accumulated smaller vector elements must be a multiple of the store size.
20928     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20929
20930     unsigned SizeRatio  = FromSz / ToSz;
20931
20932     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20933
20934     // Create a type on which we perform the shuffle
20935     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20936             StVT.getScalarType(), NumElems*SizeRatio);
20937
20938     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20939
20940     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20941     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20942     for (unsigned i = 0; i != NumElems; ++i)
20943       ShuffleVec[i] = i * SizeRatio;
20944
20945     // Can't shuffle using an illegal type.
20946     if (!TLI.isTypeLegal(WideVecVT))
20947       return SDValue();
20948
20949     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20950                                          DAG.getUNDEF(WideVecVT),
20951                                          &ShuffleVec[0]);
20952     // At this point all of the data is stored at the bottom of the
20953     // register. We now need to save it to mem.
20954
20955     // Find the largest store unit
20956     MVT StoreType = MVT::i8;
20957     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20958          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20959       MVT Tp = (MVT::SimpleValueType)tp;
20960       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20961         StoreType = Tp;
20962     }
20963
20964     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20965     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20966         (64 <= NumElems * ToSz))
20967       StoreType = MVT::f64;
20968
20969     // Bitcast the original vector into a vector of store-size units
20970     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20971             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20972     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20973     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20974     SmallVector<SDValue, 8> Chains;
20975     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20976                                         TLI.getPointerTy());
20977     SDValue Ptr = St->getBasePtr();
20978
20979     // Perform one or more big stores into memory.
20980     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
20981       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
20982                                    StoreType, ShuffWide,
20983                                    DAG.getIntPtrConstant(i));
20984       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
20985                                 St->getPointerInfo(), St->isVolatile(),
20986                                 St->isNonTemporal(), St->getAlignment());
20987       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20988       Chains.push_back(Ch);
20989     }
20990
20991     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20992   }
20993
20994   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
20995   // the FP state in cases where an emms may be missing.
20996   // A preferable solution to the general problem is to figure out the right
20997   // places to insert EMMS.  This qualifies as a quick hack.
20998
20999   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21000   if (VT.getSizeInBits() != 64)
21001     return SDValue();
21002
21003   const Function *F = DAG.getMachineFunction().getFunction();
21004   bool NoImplicitFloatOps = F->getAttributes().
21005     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21006   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21007                      && Subtarget->hasSSE2();
21008   if ((VT.isVector() ||
21009        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21010       isa<LoadSDNode>(St->getValue()) &&
21011       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21012       St->getChain().hasOneUse() && !St->isVolatile()) {
21013     SDNode* LdVal = St->getValue().getNode();
21014     LoadSDNode *Ld = nullptr;
21015     int TokenFactorIndex = -1;
21016     SmallVector<SDValue, 8> Ops;
21017     SDNode* ChainVal = St->getChain().getNode();
21018     // Must be a store of a load.  We currently handle two cases:  the load
21019     // is a direct child, and it's under an intervening TokenFactor.  It is
21020     // possible to dig deeper under nested TokenFactors.
21021     if (ChainVal == LdVal)
21022       Ld = cast<LoadSDNode>(St->getChain());
21023     else if (St->getValue().hasOneUse() &&
21024              ChainVal->getOpcode() == ISD::TokenFactor) {
21025       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21026         if (ChainVal->getOperand(i).getNode() == LdVal) {
21027           TokenFactorIndex = i;
21028           Ld = cast<LoadSDNode>(St->getValue());
21029         } else
21030           Ops.push_back(ChainVal->getOperand(i));
21031       }
21032     }
21033
21034     if (!Ld || !ISD::isNormalLoad(Ld))
21035       return SDValue();
21036
21037     // If this is not the MMX case, i.e. we are just turning i64 load/store
21038     // into f64 load/store, avoid the transformation if there are multiple
21039     // uses of the loaded value.
21040     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21041       return SDValue();
21042
21043     SDLoc LdDL(Ld);
21044     SDLoc StDL(N);
21045     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21046     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21047     // pair instead.
21048     if (Subtarget->is64Bit() || F64IsLegal) {
21049       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21050       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21051                                   Ld->getPointerInfo(), Ld->isVolatile(),
21052                                   Ld->isNonTemporal(), Ld->isInvariant(),
21053                                   Ld->getAlignment());
21054       SDValue NewChain = NewLd.getValue(1);
21055       if (TokenFactorIndex != -1) {
21056         Ops.push_back(NewChain);
21057         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21058       }
21059       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21060                           St->getPointerInfo(),
21061                           St->isVolatile(), St->isNonTemporal(),
21062                           St->getAlignment());
21063     }
21064
21065     // Otherwise, lower to two pairs of 32-bit loads / stores.
21066     SDValue LoAddr = Ld->getBasePtr();
21067     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21068                                  DAG.getConstant(4, MVT::i32));
21069
21070     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21071                                Ld->getPointerInfo(),
21072                                Ld->isVolatile(), Ld->isNonTemporal(),
21073                                Ld->isInvariant(), Ld->getAlignment());
21074     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21075                                Ld->getPointerInfo().getWithOffset(4),
21076                                Ld->isVolatile(), Ld->isNonTemporal(),
21077                                Ld->isInvariant(),
21078                                MinAlign(Ld->getAlignment(), 4));
21079
21080     SDValue NewChain = LoLd.getValue(1);
21081     if (TokenFactorIndex != -1) {
21082       Ops.push_back(LoLd);
21083       Ops.push_back(HiLd);
21084       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21085     }
21086
21087     LoAddr = St->getBasePtr();
21088     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21089                          DAG.getConstant(4, MVT::i32));
21090
21091     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21092                                 St->getPointerInfo(),
21093                                 St->isVolatile(), St->isNonTemporal(),
21094                                 St->getAlignment());
21095     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21096                                 St->getPointerInfo().getWithOffset(4),
21097                                 St->isVolatile(),
21098                                 St->isNonTemporal(),
21099                                 MinAlign(St->getAlignment(), 4));
21100     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21101   }
21102   return SDValue();
21103 }
21104
21105 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21106 /// and return the operands for the horizontal operation in LHS and RHS.  A
21107 /// horizontal operation performs the binary operation on successive elements
21108 /// of its first operand, then on successive elements of its second operand,
21109 /// returning the resulting values in a vector.  For example, if
21110 ///   A = < float a0, float a1, float a2, float a3 >
21111 /// and
21112 ///   B = < float b0, float b1, float b2, float b3 >
21113 /// then the result of doing a horizontal operation on A and B is
21114 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21115 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21116 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21117 /// set to A, RHS to B, and the routine returns 'true'.
21118 /// Note that the binary operation should have the property that if one of the
21119 /// operands is UNDEF then the result is UNDEF.
21120 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21121   // Look for the following pattern: if
21122   //   A = < float a0, float a1, float a2, float a3 >
21123   //   B = < float b0, float b1, float b2, float b3 >
21124   // and
21125   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21126   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21127   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21128   // which is A horizontal-op B.
21129
21130   // At least one of the operands should be a vector shuffle.
21131   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21132       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21133     return false;
21134
21135   MVT VT = LHS.getSimpleValueType();
21136
21137   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21138          "Unsupported vector type for horizontal add/sub");
21139
21140   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21141   // operate independently on 128-bit lanes.
21142   unsigned NumElts = VT.getVectorNumElements();
21143   unsigned NumLanes = VT.getSizeInBits()/128;
21144   unsigned NumLaneElts = NumElts / NumLanes;
21145   assert((NumLaneElts % 2 == 0) &&
21146          "Vector type should have an even number of elements in each lane");
21147   unsigned HalfLaneElts = NumLaneElts/2;
21148
21149   // View LHS in the form
21150   //   LHS = VECTOR_SHUFFLE A, B, LMask
21151   // If LHS is not a shuffle then pretend it is the shuffle
21152   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21153   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21154   // type VT.
21155   SDValue A, B;
21156   SmallVector<int, 16> LMask(NumElts);
21157   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21158     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21159       A = LHS.getOperand(0);
21160     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21161       B = LHS.getOperand(1);
21162     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21163     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21164   } else {
21165     if (LHS.getOpcode() != ISD::UNDEF)
21166       A = LHS;
21167     for (unsigned i = 0; i != NumElts; ++i)
21168       LMask[i] = i;
21169   }
21170
21171   // Likewise, view RHS in the form
21172   //   RHS = VECTOR_SHUFFLE C, D, RMask
21173   SDValue C, D;
21174   SmallVector<int, 16> RMask(NumElts);
21175   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21176     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21177       C = RHS.getOperand(0);
21178     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21179       D = RHS.getOperand(1);
21180     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21181     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21182   } else {
21183     if (RHS.getOpcode() != ISD::UNDEF)
21184       C = RHS;
21185     for (unsigned i = 0; i != NumElts; ++i)
21186       RMask[i] = i;
21187   }
21188
21189   // Check that the shuffles are both shuffling the same vectors.
21190   if (!(A == C && B == D) && !(A == D && B == C))
21191     return false;
21192
21193   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21194   if (!A.getNode() && !B.getNode())
21195     return false;
21196
21197   // If A and B occur in reverse order in RHS, then "swap" them (which means
21198   // rewriting the mask).
21199   if (A != C)
21200     CommuteVectorShuffleMask(RMask, NumElts);
21201
21202   // At this point LHS and RHS are equivalent to
21203   //   LHS = VECTOR_SHUFFLE A, B, LMask
21204   //   RHS = VECTOR_SHUFFLE A, B, RMask
21205   // Check that the masks correspond to performing a horizontal operation.
21206   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21207     for (unsigned i = 0; i != NumLaneElts; ++i) {
21208       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21209
21210       // Ignore any UNDEF components.
21211       if (LIdx < 0 || RIdx < 0 ||
21212           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21213           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21214         continue;
21215
21216       // Check that successive elements are being operated on.  If not, this is
21217       // not a horizontal operation.
21218       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21219       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21220       if (!(LIdx == Index && RIdx == Index + 1) &&
21221           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21222         return false;
21223     }
21224   }
21225
21226   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21227   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21228   return true;
21229 }
21230
21231 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21232 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21233                                   const X86Subtarget *Subtarget) {
21234   EVT VT = N->getValueType(0);
21235   SDValue LHS = N->getOperand(0);
21236   SDValue RHS = N->getOperand(1);
21237
21238   // Try to synthesize horizontal adds from adds of shuffles.
21239   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21240        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21241       isHorizontalBinOp(LHS, RHS, true))
21242     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21243   return SDValue();
21244 }
21245
21246 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21247 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21248                                   const X86Subtarget *Subtarget) {
21249   EVT VT = N->getValueType(0);
21250   SDValue LHS = N->getOperand(0);
21251   SDValue RHS = N->getOperand(1);
21252
21253   // Try to synthesize horizontal subs from subs of shuffles.
21254   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21255        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21256       isHorizontalBinOp(LHS, RHS, false))
21257     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21258   return SDValue();
21259 }
21260
21261 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21262 /// X86ISD::FXOR nodes.
21263 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21264   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21265   // F[X]OR(0.0, x) -> x
21266   // F[X]OR(x, 0.0) -> x
21267   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21268     if (C->getValueAPF().isPosZero())
21269       return N->getOperand(1);
21270   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21271     if (C->getValueAPF().isPosZero())
21272       return N->getOperand(0);
21273   return SDValue();
21274 }
21275
21276 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21277 /// X86ISD::FMAX nodes.
21278 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21279   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21280
21281   // Only perform optimizations if UnsafeMath is used.
21282   if (!DAG.getTarget().Options.UnsafeFPMath)
21283     return SDValue();
21284
21285   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21286   // into FMINC and FMAXC, which are Commutative operations.
21287   unsigned NewOp = 0;
21288   switch (N->getOpcode()) {
21289     default: llvm_unreachable("unknown opcode");
21290     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21291     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21292   }
21293
21294   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21295                      N->getOperand(0), N->getOperand(1));
21296 }
21297
21298 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21299 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21300   // FAND(0.0, x) -> 0.0
21301   // FAND(x, 0.0) -> 0.0
21302   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21303     if (C->getValueAPF().isPosZero())
21304       return N->getOperand(0);
21305   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21306     if (C->getValueAPF().isPosZero())
21307       return N->getOperand(1);
21308   return SDValue();
21309 }
21310
21311 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21312 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21313   // FANDN(x, 0.0) -> 0.0
21314   // FANDN(0.0, x) -> x
21315   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21316     if (C->getValueAPF().isPosZero())
21317       return N->getOperand(1);
21318   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21319     if (C->getValueAPF().isPosZero())
21320       return N->getOperand(1);
21321   return SDValue();
21322 }
21323
21324 static SDValue PerformBTCombine(SDNode *N,
21325                                 SelectionDAG &DAG,
21326                                 TargetLowering::DAGCombinerInfo &DCI) {
21327   // BT ignores high bits in the bit index operand.
21328   SDValue Op1 = N->getOperand(1);
21329   if (Op1.hasOneUse()) {
21330     unsigned BitWidth = Op1.getValueSizeInBits();
21331     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21332     APInt KnownZero, KnownOne;
21333     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21334                                           !DCI.isBeforeLegalizeOps());
21335     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21336     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21337         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21338       DCI.CommitTargetLoweringOpt(TLO);
21339   }
21340   return SDValue();
21341 }
21342
21343 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21344   SDValue Op = N->getOperand(0);
21345   if (Op.getOpcode() == ISD::BITCAST)
21346     Op = Op.getOperand(0);
21347   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21348   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21349       VT.getVectorElementType().getSizeInBits() ==
21350       OpVT.getVectorElementType().getSizeInBits()) {
21351     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21352   }
21353   return SDValue();
21354 }
21355
21356 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21357                                                const X86Subtarget *Subtarget) {
21358   EVT VT = N->getValueType(0);
21359   if (!VT.isVector())
21360     return SDValue();
21361
21362   SDValue N0 = N->getOperand(0);
21363   SDValue N1 = N->getOperand(1);
21364   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21365   SDLoc dl(N);
21366
21367   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21368   // both SSE and AVX2 since there is no sign-extended shift right
21369   // operation on a vector with 64-bit elements.
21370   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21371   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21372   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21373       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21374     SDValue N00 = N0.getOperand(0);
21375
21376     // EXTLOAD has a better solution on AVX2,
21377     // it may be replaced with X86ISD::VSEXT node.
21378     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21379       if (!ISD::isNormalLoad(N00.getNode()))
21380         return SDValue();
21381
21382     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21383         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21384                                   N00, N1);
21385       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21386     }
21387   }
21388   return SDValue();
21389 }
21390
21391 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21392                                   TargetLowering::DAGCombinerInfo &DCI,
21393                                   const X86Subtarget *Subtarget) {
21394   if (!DCI.isBeforeLegalizeOps())
21395     return SDValue();
21396
21397   if (!Subtarget->hasFp256())
21398     return SDValue();
21399
21400   EVT VT = N->getValueType(0);
21401   if (VT.isVector() && VT.getSizeInBits() == 256) {
21402     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21403     if (R.getNode())
21404       return R;
21405   }
21406
21407   return SDValue();
21408 }
21409
21410 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21411                                  const X86Subtarget* Subtarget) {
21412   SDLoc dl(N);
21413   EVT VT = N->getValueType(0);
21414
21415   // Let legalize expand this if it isn't a legal type yet.
21416   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21417     return SDValue();
21418
21419   EVT ScalarVT = VT.getScalarType();
21420   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21421       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21422     return SDValue();
21423
21424   SDValue A = N->getOperand(0);
21425   SDValue B = N->getOperand(1);
21426   SDValue C = N->getOperand(2);
21427
21428   bool NegA = (A.getOpcode() == ISD::FNEG);
21429   bool NegB = (B.getOpcode() == ISD::FNEG);
21430   bool NegC = (C.getOpcode() == ISD::FNEG);
21431
21432   // Negative multiplication when NegA xor NegB
21433   bool NegMul = (NegA != NegB);
21434   if (NegA)
21435     A = A.getOperand(0);
21436   if (NegB)
21437     B = B.getOperand(0);
21438   if (NegC)
21439     C = C.getOperand(0);
21440
21441   unsigned Opcode;
21442   if (!NegMul)
21443     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21444   else
21445     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21446
21447   return DAG.getNode(Opcode, dl, VT, A, B, C);
21448 }
21449
21450 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21451                                   TargetLowering::DAGCombinerInfo &DCI,
21452                                   const X86Subtarget *Subtarget) {
21453   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21454   //           (and (i32 x86isd::setcc_carry), 1)
21455   // This eliminates the zext. This transformation is necessary because
21456   // ISD::SETCC is always legalized to i8.
21457   SDLoc dl(N);
21458   SDValue N0 = N->getOperand(0);
21459   EVT VT = N->getValueType(0);
21460
21461   if (N0.getOpcode() == ISD::AND &&
21462       N0.hasOneUse() &&
21463       N0.getOperand(0).hasOneUse()) {
21464     SDValue N00 = N0.getOperand(0);
21465     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21466       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21467       if (!C || C->getZExtValue() != 1)
21468         return SDValue();
21469       return DAG.getNode(ISD::AND, dl, VT,
21470                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21471                                      N00.getOperand(0), N00.getOperand(1)),
21472                          DAG.getConstant(1, VT));
21473     }
21474   }
21475
21476   if (N0.getOpcode() == ISD::TRUNCATE &&
21477       N0.hasOneUse() &&
21478       N0.getOperand(0).hasOneUse()) {
21479     SDValue N00 = N0.getOperand(0);
21480     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21481       return DAG.getNode(ISD::AND, dl, VT,
21482                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21483                                      N00.getOperand(0), N00.getOperand(1)),
21484                          DAG.getConstant(1, VT));
21485     }
21486   }
21487   if (VT.is256BitVector()) {
21488     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21489     if (R.getNode())
21490       return R;
21491   }
21492
21493   return SDValue();
21494 }
21495
21496 // Optimize x == -y --> x+y == 0
21497 //          x != -y --> x+y != 0
21498 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21499                                       const X86Subtarget* Subtarget) {
21500   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21501   SDValue LHS = N->getOperand(0);
21502   SDValue RHS = N->getOperand(1);
21503   EVT VT = N->getValueType(0);
21504   SDLoc DL(N);
21505
21506   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21507     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21508       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21509         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21510                                    LHS.getValueType(), RHS, LHS.getOperand(1));
21511         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21512                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21513       }
21514   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21515     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21516       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21517         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21518                                    RHS.getValueType(), LHS, RHS.getOperand(1));
21519         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21520                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21521       }
21522
21523   if (VT.getScalarType() == MVT::i1) {
21524     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21525       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21526     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21527     if (!IsSEXT0 && !IsVZero0)
21528       return SDValue();
21529     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21530       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21531     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21532
21533     if (!IsSEXT1 && !IsVZero1)
21534       return SDValue();
21535
21536     if (IsSEXT0 && IsVZero1) {
21537       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21538       if (CC == ISD::SETEQ)
21539         return DAG.getNOT(DL, LHS.getOperand(0), VT);
21540       return LHS.getOperand(0);
21541     }
21542     if (IsSEXT1 && IsVZero0) {
21543       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21544       if (CC == ISD::SETEQ)
21545         return DAG.getNOT(DL, RHS.getOperand(0), VT);
21546       return RHS.getOperand(0);
21547     }
21548   }
21549
21550   return SDValue();
21551 }
21552
21553 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21554                                       const X86Subtarget *Subtarget) {
21555   SDLoc dl(N);
21556   MVT VT = N->getOperand(1)->getSimpleValueType(0);
21557   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21558          "X86insertps is only defined for v4x32");
21559
21560   SDValue Ld = N->getOperand(1);
21561   if (MayFoldLoad(Ld)) {
21562     // Extract the countS bits from the immediate so we can get the proper
21563     // address when narrowing the vector load to a specific element.
21564     // When the second source op is a memory address, interps doesn't use
21565     // countS and just gets an f32 from that address.
21566     unsigned DestIndex =
21567         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21568     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21569   } else
21570     return SDValue();
21571
21572   // Create this as a scalar to vector to match the instruction pattern.
21573   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21574   // countS bits are ignored when loading from memory on insertps, which
21575   // means we don't need to explicitly set them to 0.
21576   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21577                      LoadScalarToVector, N->getOperand(2));
21578 }
21579
21580 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21581 // as "sbb reg,reg", since it can be extended without zext and produces
21582 // an all-ones bit which is more useful than 0/1 in some cases.
21583 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21584                                MVT VT) {
21585   if (VT == MVT::i8)
21586     return DAG.getNode(ISD::AND, DL, VT,
21587                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21588                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21589                        DAG.getConstant(1, VT));
21590   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21591   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21592                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21593                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21594 }
21595
21596 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21597 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21598                                    TargetLowering::DAGCombinerInfo &DCI,
21599                                    const X86Subtarget *Subtarget) {
21600   SDLoc DL(N);
21601   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21602   SDValue EFLAGS = N->getOperand(1);
21603
21604   if (CC == X86::COND_A) {
21605     // Try to convert COND_A into COND_B in an attempt to facilitate
21606     // materializing "setb reg".
21607     //
21608     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21609     // cannot take an immediate as its first operand.
21610     //
21611     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21612         EFLAGS.getValueType().isInteger() &&
21613         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21614       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21615                                    EFLAGS.getNode()->getVTList(),
21616                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21617       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21618       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21619     }
21620   }
21621
21622   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21623   // a zext and produces an all-ones bit which is more useful than 0/1 in some
21624   // cases.
21625   if (CC == X86::COND_B)
21626     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21627
21628   SDValue Flags;
21629
21630   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21631   if (Flags.getNode()) {
21632     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21633     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21634   }
21635
21636   return SDValue();
21637 }
21638
21639 // Optimize branch condition evaluation.
21640 //
21641 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21642                                     TargetLowering::DAGCombinerInfo &DCI,
21643                                     const X86Subtarget *Subtarget) {
21644   SDLoc DL(N);
21645   SDValue Chain = N->getOperand(0);
21646   SDValue Dest = N->getOperand(1);
21647   SDValue EFLAGS = N->getOperand(3);
21648   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21649
21650   SDValue Flags;
21651
21652   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21653   if (Flags.getNode()) {
21654     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21655     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21656                        Flags);
21657   }
21658
21659   return SDValue();
21660 }
21661
21662 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21663                                         const X86TargetLowering *XTLI) {
21664   SDValue Op0 = N->getOperand(0);
21665   EVT InVT = Op0->getValueType(0);
21666
21667   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21668   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21669     SDLoc dl(N);
21670     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21671     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21672     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21673   }
21674
21675   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21676   // a 32-bit target where SSE doesn't support i64->FP operations.
21677   if (Op0.getOpcode() == ISD::LOAD) {
21678     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21679     EVT VT = Ld->getValueType(0);
21680     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21681         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21682         !XTLI->getSubtarget()->is64Bit() &&
21683         VT == MVT::i64) {
21684       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21685                                           Ld->getChain(), Op0, DAG);
21686       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21687       return FILDChain;
21688     }
21689   }
21690   return SDValue();
21691 }
21692
21693 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21694 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21695                                  X86TargetLowering::DAGCombinerInfo &DCI) {
21696   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21697   // the result is either zero or one (depending on the input carry bit).
21698   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21699   if (X86::isZeroNode(N->getOperand(0)) &&
21700       X86::isZeroNode(N->getOperand(1)) &&
21701       // We don't have a good way to replace an EFLAGS use, so only do this when
21702       // dead right now.
21703       SDValue(N, 1).use_empty()) {
21704     SDLoc DL(N);
21705     EVT VT = N->getValueType(0);
21706     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21707     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21708                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21709                                            DAG.getConstant(X86::COND_B,MVT::i8),
21710                                            N->getOperand(2)),
21711                                DAG.getConstant(1, VT));
21712     return DCI.CombineTo(N, Res1, CarryOut);
21713   }
21714
21715   return SDValue();
21716 }
21717
21718 // fold (add Y, (sete  X, 0)) -> adc  0, Y
21719 //      (add Y, (setne X, 0)) -> sbb -1, Y
21720 //      (sub (sete  X, 0), Y) -> sbb  0, Y
21721 //      (sub (setne X, 0), Y) -> adc -1, Y
21722 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21723   SDLoc DL(N);
21724
21725   // Look through ZExts.
21726   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21727   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21728     return SDValue();
21729
21730   SDValue SetCC = Ext.getOperand(0);
21731   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21732     return SDValue();
21733
21734   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21735   if (CC != X86::COND_E && CC != X86::COND_NE)
21736     return SDValue();
21737
21738   SDValue Cmp = SetCC.getOperand(1);
21739   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21740       !X86::isZeroNode(Cmp.getOperand(1)) ||
21741       !Cmp.getOperand(0).getValueType().isInteger())
21742     return SDValue();
21743
21744   SDValue CmpOp0 = Cmp.getOperand(0);
21745   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21746                                DAG.getConstant(1, CmpOp0.getValueType()));
21747
21748   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21749   if (CC == X86::COND_NE)
21750     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21751                        DL, OtherVal.getValueType(), OtherVal,
21752                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21753   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21754                      DL, OtherVal.getValueType(), OtherVal,
21755                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21756 }
21757
21758 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21759 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21760                                  const X86Subtarget *Subtarget) {
21761   EVT VT = N->getValueType(0);
21762   SDValue Op0 = N->getOperand(0);
21763   SDValue Op1 = N->getOperand(1);
21764
21765   // Try to synthesize horizontal adds from adds of shuffles.
21766   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21767        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21768       isHorizontalBinOp(Op0, Op1, true))
21769     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21770
21771   return OptimizeConditionalInDecrement(N, DAG);
21772 }
21773
21774 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21775                                  const X86Subtarget *Subtarget) {
21776   SDValue Op0 = N->getOperand(0);
21777   SDValue Op1 = N->getOperand(1);
21778
21779   // X86 can't encode an immediate LHS of a sub. See if we can push the
21780   // negation into a preceding instruction.
21781   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21782     // If the RHS of the sub is a XOR with one use and a constant, invert the
21783     // immediate. Then add one to the LHS of the sub so we can turn
21784     // X-Y -> X+~Y+1, saving one register.
21785     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21786         isa<ConstantSDNode>(Op1.getOperand(1))) {
21787       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21788       EVT VT = Op0.getValueType();
21789       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21790                                    Op1.getOperand(0),
21791                                    DAG.getConstant(~XorC, VT));
21792       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21793                          DAG.getConstant(C->getAPIntValue()+1, VT));
21794     }
21795   }
21796
21797   // Try to synthesize horizontal adds from adds of shuffles.
21798   EVT VT = N->getValueType(0);
21799   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21800        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21801       isHorizontalBinOp(Op0, Op1, true))
21802     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21803
21804   return OptimizeConditionalInDecrement(N, DAG);
21805 }
21806
21807 /// performVZEXTCombine - Performs build vector combines
21808 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21809                                         TargetLowering::DAGCombinerInfo &DCI,
21810                                         const X86Subtarget *Subtarget) {
21811   // (vzext (bitcast (vzext (x)) -> (vzext x)
21812   SDValue In = N->getOperand(0);
21813   while (In.getOpcode() == ISD::BITCAST)
21814     In = In.getOperand(0);
21815
21816   if (In.getOpcode() != X86ISD::VZEXT)
21817     return SDValue();
21818
21819   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21820                      In.getOperand(0));
21821 }
21822
21823 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21824                                              DAGCombinerInfo &DCI) const {
21825   SelectionDAG &DAG = DCI.DAG;
21826   switch (N->getOpcode()) {
21827   default: break;
21828   case ISD::EXTRACT_VECTOR_ELT:
21829     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21830   case ISD::VSELECT:
21831   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21832   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21833   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
21834   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
21835   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
21836   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
21837   case ISD::SHL:
21838   case ISD::SRA:
21839   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
21840   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
21841   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
21842   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
21843   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
21844   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
21845   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
21846   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
21847   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
21848   case X86ISD::FXOR:
21849   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
21850   case X86ISD::FMIN:
21851   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
21852   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
21853   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
21854   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
21855   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
21856   case ISD::ANY_EXTEND:
21857   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
21858   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
21859   case ISD::SIGN_EXTEND_INREG:
21860     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21861   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21862   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
21863   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21864   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21865   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
21866   case X86ISD::SHUFP:       // Handle all target specific shuffles
21867   case X86ISD::PALIGNR:
21868   case X86ISD::UNPCKH:
21869   case X86ISD::UNPCKL:
21870   case X86ISD::MOVHLPS:
21871   case X86ISD::MOVLHPS:
21872   case X86ISD::PSHUFD:
21873   case X86ISD::PSHUFHW:
21874   case X86ISD::PSHUFLW:
21875   case X86ISD::MOVSS:
21876   case X86ISD::MOVSD:
21877   case X86ISD::VPERMILP:
21878   case X86ISD::VPERM2X128:
21879   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21880   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
21881   case ISD::INTRINSIC_WO_CHAIN:
21882     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21883   case X86ISD::INSERTPS:
21884     return PerformINSERTPSCombine(N, DAG, Subtarget);
21885   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21886   }
21887
21888   return SDValue();
21889 }
21890
21891 /// isTypeDesirableForOp - Return true if the target has native support for
21892 /// the specified value type and it is 'desirable' to use the type for the
21893 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21894 /// instruction encodings are longer and some i16 instructions are slow.
21895 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21896   if (!isTypeLegal(VT))
21897     return false;
21898   if (VT != MVT::i16)
21899     return true;
21900
21901   switch (Opc) {
21902   default:
21903     return true;
21904   case ISD::LOAD:
21905   case ISD::SIGN_EXTEND:
21906   case ISD::ZERO_EXTEND:
21907   case ISD::ANY_EXTEND:
21908   case ISD::SHL:
21909   case ISD::SRL:
21910   case ISD::SUB:
21911   case ISD::ADD:
21912   case ISD::MUL:
21913   case ISD::AND:
21914   case ISD::OR:
21915   case ISD::XOR:
21916     return false;
21917   }
21918 }
21919
21920 /// IsDesirableToPromoteOp - This method query the target whether it is
21921 /// beneficial for dag combiner to promote the specified node. If true, it
21922 /// should return the desired promotion type by reference.
21923 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21924   EVT VT = Op.getValueType();
21925   if (VT != MVT::i16)
21926     return false;
21927
21928   bool Promote = false;
21929   bool Commute = false;
21930   switch (Op.getOpcode()) {
21931   default: break;
21932   case ISD::LOAD: {
21933     LoadSDNode *LD = cast<LoadSDNode>(Op);
21934     // If the non-extending load has a single use and it's not live out, then it
21935     // might be folded.
21936     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21937                                                      Op.hasOneUse()*/) {
21938       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21939              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21940         // The only case where we'd want to promote LOAD (rather then it being
21941         // promoted as an operand is when it's only use is liveout.
21942         if (UI->getOpcode() != ISD::CopyToReg)
21943           return false;
21944       }
21945     }
21946     Promote = true;
21947     break;
21948   }
21949   case ISD::SIGN_EXTEND:
21950   case ISD::ZERO_EXTEND:
21951   case ISD::ANY_EXTEND:
21952     Promote = true;
21953     break;
21954   case ISD::SHL:
21955   case ISD::SRL: {
21956     SDValue N0 = Op.getOperand(0);
21957     // Look out for (store (shl (load), x)).
21958     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21959       return false;
21960     Promote = true;
21961     break;
21962   }
21963   case ISD::ADD:
21964   case ISD::MUL:
21965   case ISD::AND:
21966   case ISD::OR:
21967   case ISD::XOR:
21968     Commute = true;
21969     // fallthrough
21970   case ISD::SUB: {
21971     SDValue N0 = Op.getOperand(0);
21972     SDValue N1 = Op.getOperand(1);
21973     if (!Commute && MayFoldLoad(N1))
21974       return false;
21975     // Avoid disabling potential load folding opportunities.
21976     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
21977       return false;
21978     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
21979       return false;
21980     Promote = true;
21981   }
21982   }
21983
21984   PVT = MVT::i32;
21985   return Promote;
21986 }
21987
21988 //===----------------------------------------------------------------------===//
21989 //                           X86 Inline Assembly Support
21990 //===----------------------------------------------------------------------===//
21991
21992 namespace {
21993   // Helper to match a string separated by whitespace.
21994   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
21995     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
21996
21997     for (unsigned i = 0, e = args.size(); i != e; ++i) {
21998       StringRef piece(*args[i]);
21999       if (!s.startswith(piece)) // Check if the piece matches.
22000         return false;
22001
22002       s = s.substr(piece.size());
22003       StringRef::size_type pos = s.find_first_not_of(" \t");
22004       if (pos == 0) // We matched a prefix.
22005         return false;
22006
22007       s = s.substr(pos);
22008     }
22009
22010     return s.empty();
22011   }
22012   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22013 }
22014
22015 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22016
22017   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22018     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22019         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22020         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22021
22022       if (AsmPieces.size() == 3)
22023         return true;
22024       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22025         return true;
22026     }
22027   }
22028   return false;
22029 }
22030
22031 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22032   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22033
22034   std::string AsmStr = IA->getAsmString();
22035
22036   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22037   if (!Ty || Ty->getBitWidth() % 16 != 0)
22038     return false;
22039
22040   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22041   SmallVector<StringRef, 4> AsmPieces;
22042   SplitString(AsmStr, AsmPieces, ";\n");
22043
22044   switch (AsmPieces.size()) {
22045   default: return false;
22046   case 1:
22047     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22048     // we will turn this bswap into something that will be lowered to logical
22049     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22050     // lower so don't worry about this.
22051     // bswap $0
22052     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22053         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22054         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22055         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22056         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22057         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22058       // No need to check constraints, nothing other than the equivalent of
22059       // "=r,0" would be valid here.
22060       return IntrinsicLowering::LowerToByteSwap(CI);
22061     }
22062
22063     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22064     if (CI->getType()->isIntegerTy(16) &&
22065         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22066         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22067          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22068       AsmPieces.clear();
22069       const std::string &ConstraintsStr = IA->getConstraintString();
22070       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22071       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22072       if (clobbersFlagRegisters(AsmPieces))
22073         return IntrinsicLowering::LowerToByteSwap(CI);
22074     }
22075     break;
22076   case 3:
22077     if (CI->getType()->isIntegerTy(32) &&
22078         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22079         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22080         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22081         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22082       AsmPieces.clear();
22083       const std::string &ConstraintsStr = IA->getConstraintString();
22084       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22085       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22086       if (clobbersFlagRegisters(AsmPieces))
22087         return IntrinsicLowering::LowerToByteSwap(CI);
22088     }
22089
22090     if (CI->getType()->isIntegerTy(64)) {
22091       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22092       if (Constraints.size() >= 2 &&
22093           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22094           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22095         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22096         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22097             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22098             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22099           return IntrinsicLowering::LowerToByteSwap(CI);
22100       }
22101     }
22102     break;
22103   }
22104   return false;
22105 }
22106
22107 /// getConstraintType - Given a constraint letter, return the type of
22108 /// constraint it is for this target.
22109 X86TargetLowering::ConstraintType
22110 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22111   if (Constraint.size() == 1) {
22112     switch (Constraint[0]) {
22113     case 'R':
22114     case 'q':
22115     case 'Q':
22116     case 'f':
22117     case 't':
22118     case 'u':
22119     case 'y':
22120     case 'x':
22121     case 'Y':
22122     case 'l':
22123       return C_RegisterClass;
22124     case 'a':
22125     case 'b':
22126     case 'c':
22127     case 'd':
22128     case 'S':
22129     case 'D':
22130     case 'A':
22131       return C_Register;
22132     case 'I':
22133     case 'J':
22134     case 'K':
22135     case 'L':
22136     case 'M':
22137     case 'N':
22138     case 'G':
22139     case 'C':
22140     case 'e':
22141     case 'Z':
22142       return C_Other;
22143     default:
22144       break;
22145     }
22146   }
22147   return TargetLowering::getConstraintType(Constraint);
22148 }
22149
22150 /// Examine constraint type and operand type and determine a weight value.
22151 /// This object must already have been set up with the operand type
22152 /// and the current alternative constraint selected.
22153 TargetLowering::ConstraintWeight
22154   X86TargetLowering::getSingleConstraintMatchWeight(
22155     AsmOperandInfo &info, const char *constraint) const {
22156   ConstraintWeight weight = CW_Invalid;
22157   Value *CallOperandVal = info.CallOperandVal;
22158     // If we don't have a value, we can't do a match,
22159     // but allow it at the lowest weight.
22160   if (!CallOperandVal)
22161     return CW_Default;
22162   Type *type = CallOperandVal->getType();
22163   // Look at the constraint type.
22164   switch (*constraint) {
22165   default:
22166     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22167   case 'R':
22168   case 'q':
22169   case 'Q':
22170   case 'a':
22171   case 'b':
22172   case 'c':
22173   case 'd':
22174   case 'S':
22175   case 'D':
22176   case 'A':
22177     if (CallOperandVal->getType()->isIntegerTy())
22178       weight = CW_SpecificReg;
22179     break;
22180   case 'f':
22181   case 't':
22182   case 'u':
22183     if (type->isFloatingPointTy())
22184       weight = CW_SpecificReg;
22185     break;
22186   case 'y':
22187     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22188       weight = CW_SpecificReg;
22189     break;
22190   case 'x':
22191   case 'Y':
22192     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22193         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22194       weight = CW_Register;
22195     break;
22196   case 'I':
22197     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22198       if (C->getZExtValue() <= 31)
22199         weight = CW_Constant;
22200     }
22201     break;
22202   case 'J':
22203     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22204       if (C->getZExtValue() <= 63)
22205         weight = CW_Constant;
22206     }
22207     break;
22208   case 'K':
22209     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22210       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22211         weight = CW_Constant;
22212     }
22213     break;
22214   case 'L':
22215     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22216       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22217         weight = CW_Constant;
22218     }
22219     break;
22220   case 'M':
22221     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22222       if (C->getZExtValue() <= 3)
22223         weight = CW_Constant;
22224     }
22225     break;
22226   case 'N':
22227     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22228       if (C->getZExtValue() <= 0xff)
22229         weight = CW_Constant;
22230     }
22231     break;
22232   case 'G':
22233   case 'C':
22234     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22235       weight = CW_Constant;
22236     }
22237     break;
22238   case 'e':
22239     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22240       if ((C->getSExtValue() >= -0x80000000LL) &&
22241           (C->getSExtValue() <= 0x7fffffffLL))
22242         weight = CW_Constant;
22243     }
22244     break;
22245   case 'Z':
22246     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22247       if (C->getZExtValue() <= 0xffffffff)
22248         weight = CW_Constant;
22249     }
22250     break;
22251   }
22252   return weight;
22253 }
22254
22255 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22256 /// with another that has more specific requirements based on the type of the
22257 /// corresponding operand.
22258 const char *X86TargetLowering::
22259 LowerXConstraint(EVT ConstraintVT) const {
22260   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22261   // 'f' like normal targets.
22262   if (ConstraintVT.isFloatingPoint()) {
22263     if (Subtarget->hasSSE2())
22264       return "Y";
22265     if (Subtarget->hasSSE1())
22266       return "x";
22267   }
22268
22269   return TargetLowering::LowerXConstraint(ConstraintVT);
22270 }
22271
22272 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22273 /// vector.  If it is invalid, don't add anything to Ops.
22274 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22275                                                      std::string &Constraint,
22276                                                      std::vector<SDValue>&Ops,
22277                                                      SelectionDAG &DAG) const {
22278   SDValue Result;
22279
22280   // Only support length 1 constraints for now.
22281   if (Constraint.length() > 1) return;
22282
22283   char ConstraintLetter = Constraint[0];
22284   switch (ConstraintLetter) {
22285   default: break;
22286   case 'I':
22287     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22288       if (C->getZExtValue() <= 31) {
22289         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22290         break;
22291       }
22292     }
22293     return;
22294   case 'J':
22295     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22296       if (C->getZExtValue() <= 63) {
22297         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22298         break;
22299       }
22300     }
22301     return;
22302   case 'K':
22303     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22304       if (isInt<8>(C->getSExtValue())) {
22305         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22306         break;
22307       }
22308     }
22309     return;
22310   case 'N':
22311     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22312       if (C->getZExtValue() <= 255) {
22313         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22314         break;
22315       }
22316     }
22317     return;
22318   case 'e': {
22319     // 32-bit signed value
22320     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22321       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22322                                            C->getSExtValue())) {
22323         // Widen to 64 bits here to get it sign extended.
22324         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22325         break;
22326       }
22327     // FIXME gcc accepts some relocatable values here too, but only in certain
22328     // memory models; it's complicated.
22329     }
22330     return;
22331   }
22332   case 'Z': {
22333     // 32-bit unsigned value
22334     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22335       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22336                                            C->getZExtValue())) {
22337         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22338         break;
22339       }
22340     }
22341     // FIXME gcc accepts some relocatable values here too, but only in certain
22342     // memory models; it's complicated.
22343     return;
22344   }
22345   case 'i': {
22346     // Literal immediates are always ok.
22347     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22348       // Widen to 64 bits here to get it sign extended.
22349       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22350       break;
22351     }
22352
22353     // In any sort of PIC mode addresses need to be computed at runtime by
22354     // adding in a register or some sort of table lookup.  These can't
22355     // be used as immediates.
22356     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22357       return;
22358
22359     // If we are in non-pic codegen mode, we allow the address of a global (with
22360     // an optional displacement) to be used with 'i'.
22361     GlobalAddressSDNode *GA = nullptr;
22362     int64_t Offset = 0;
22363
22364     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22365     while (1) {
22366       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22367         Offset += GA->getOffset();
22368         break;
22369       } else if (Op.getOpcode() == ISD::ADD) {
22370         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22371           Offset += C->getZExtValue();
22372           Op = Op.getOperand(0);
22373           continue;
22374         }
22375       } else if (Op.getOpcode() == ISD::SUB) {
22376         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22377           Offset += -C->getZExtValue();
22378           Op = Op.getOperand(0);
22379           continue;
22380         }
22381       }
22382
22383       // Otherwise, this isn't something we can handle, reject it.
22384       return;
22385     }
22386
22387     const GlobalValue *GV = GA->getGlobal();
22388     // If we require an extra load to get this address, as in PIC mode, we
22389     // can't accept it.
22390     if (isGlobalStubReference(
22391             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22392       return;
22393
22394     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22395                                         GA->getValueType(0), Offset);
22396     break;
22397   }
22398   }
22399
22400   if (Result.getNode()) {
22401     Ops.push_back(Result);
22402     return;
22403   }
22404   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22405 }
22406
22407 std::pair<unsigned, const TargetRegisterClass*>
22408 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22409                                                 MVT VT) const {
22410   // First, see if this is a constraint that directly corresponds to an LLVM
22411   // register class.
22412   if (Constraint.size() == 1) {
22413     // GCC Constraint Letters
22414     switch (Constraint[0]) {
22415     default: break;
22416       // TODO: Slight differences here in allocation order and leaving
22417       // RIP in the class. Do they matter any more here than they do
22418       // in the normal allocation?
22419     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22420       if (Subtarget->is64Bit()) {
22421         if (VT == MVT::i32 || VT == MVT::f32)
22422           return std::make_pair(0U, &X86::GR32RegClass);
22423         if (VT == MVT::i16)
22424           return std::make_pair(0U, &X86::GR16RegClass);
22425         if (VT == MVT::i8 || VT == MVT::i1)
22426           return std::make_pair(0U, &X86::GR8RegClass);
22427         if (VT == MVT::i64 || VT == MVT::f64)
22428           return std::make_pair(0U, &X86::GR64RegClass);
22429         break;
22430       }
22431       // 32-bit fallthrough
22432     case 'Q':   // Q_REGS
22433       if (VT == MVT::i32 || VT == MVT::f32)
22434         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22435       if (VT == MVT::i16)
22436         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22437       if (VT == MVT::i8 || VT == MVT::i1)
22438         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22439       if (VT == MVT::i64)
22440         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22441       break;
22442     case 'r':   // GENERAL_REGS
22443     case 'l':   // INDEX_REGS
22444       if (VT == MVT::i8 || VT == MVT::i1)
22445         return std::make_pair(0U, &X86::GR8RegClass);
22446       if (VT == MVT::i16)
22447         return std::make_pair(0U, &X86::GR16RegClass);
22448       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22449         return std::make_pair(0U, &X86::GR32RegClass);
22450       return std::make_pair(0U, &X86::GR64RegClass);
22451     case 'R':   // LEGACY_REGS
22452       if (VT == MVT::i8 || VT == MVT::i1)
22453         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22454       if (VT == MVT::i16)
22455         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22456       if (VT == MVT::i32 || !Subtarget->is64Bit())
22457         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22458       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22459     case 'f':  // FP Stack registers.
22460       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22461       // value to the correct fpstack register class.
22462       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22463         return std::make_pair(0U, &X86::RFP32RegClass);
22464       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22465         return std::make_pair(0U, &X86::RFP64RegClass);
22466       return std::make_pair(0U, &X86::RFP80RegClass);
22467     case 'y':   // MMX_REGS if MMX allowed.
22468       if (!Subtarget->hasMMX()) break;
22469       return std::make_pair(0U, &X86::VR64RegClass);
22470     case 'Y':   // SSE_REGS if SSE2 allowed
22471       if (!Subtarget->hasSSE2()) break;
22472       // FALL THROUGH.
22473     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22474       if (!Subtarget->hasSSE1()) break;
22475
22476       switch (VT.SimpleTy) {
22477       default: break;
22478       // Scalar SSE types.
22479       case MVT::f32:
22480       case MVT::i32:
22481         return std::make_pair(0U, &X86::FR32RegClass);
22482       case MVT::f64:
22483       case MVT::i64:
22484         return std::make_pair(0U, &X86::FR64RegClass);
22485       // Vector types.
22486       case MVT::v16i8:
22487       case MVT::v8i16:
22488       case MVT::v4i32:
22489       case MVT::v2i64:
22490       case MVT::v4f32:
22491       case MVT::v2f64:
22492         return std::make_pair(0U, &X86::VR128RegClass);
22493       // AVX types.
22494       case MVT::v32i8:
22495       case MVT::v16i16:
22496       case MVT::v8i32:
22497       case MVT::v4i64:
22498       case MVT::v8f32:
22499       case MVT::v4f64:
22500         return std::make_pair(0U, &X86::VR256RegClass);
22501       case MVT::v8f64:
22502       case MVT::v16f32:
22503       case MVT::v16i32:
22504       case MVT::v8i64:
22505         return std::make_pair(0U, &X86::VR512RegClass);
22506       }
22507       break;
22508     }
22509   }
22510
22511   // Use the default implementation in TargetLowering to convert the register
22512   // constraint into a member of a register class.
22513   std::pair<unsigned, const TargetRegisterClass*> Res;
22514   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22515
22516   // Not found as a standard register?
22517   if (!Res.second) {
22518     // Map st(0) -> st(7) -> ST0
22519     if (Constraint.size() == 7 && Constraint[0] == '{' &&
22520         tolower(Constraint[1]) == 's' &&
22521         tolower(Constraint[2]) == 't' &&
22522         Constraint[3] == '(' &&
22523         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22524         Constraint[5] == ')' &&
22525         Constraint[6] == '}') {
22526
22527       Res.first = X86::ST0+Constraint[4]-'0';
22528       Res.second = &X86::RFP80RegClass;
22529       return Res;
22530     }
22531
22532     // GCC allows "st(0)" to be called just plain "st".
22533     if (StringRef("{st}").equals_lower(Constraint)) {
22534       Res.first = X86::ST0;
22535       Res.second = &X86::RFP80RegClass;
22536       return Res;
22537     }
22538
22539     // flags -> EFLAGS
22540     if (StringRef("{flags}").equals_lower(Constraint)) {
22541       Res.first = X86::EFLAGS;
22542       Res.second = &X86::CCRRegClass;
22543       return Res;
22544     }
22545
22546     // 'A' means EAX + EDX.
22547     if (Constraint == "A") {
22548       Res.first = X86::EAX;
22549       Res.second = &X86::GR32_ADRegClass;
22550       return Res;
22551     }
22552     return Res;
22553   }
22554
22555   // Otherwise, check to see if this is a register class of the wrong value
22556   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22557   // turn into {ax},{dx}.
22558   if (Res.second->hasType(VT))
22559     return Res;   // Correct type already, nothing to do.
22560
22561   // All of the single-register GCC register classes map their values onto
22562   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
22563   // really want an 8-bit or 32-bit register, map to the appropriate register
22564   // class and return the appropriate register.
22565   if (Res.second == &X86::GR16RegClass) {
22566     if (VT == MVT::i8 || VT == MVT::i1) {
22567       unsigned DestReg = 0;
22568       switch (Res.first) {
22569       default: break;
22570       case X86::AX: DestReg = X86::AL; break;
22571       case X86::DX: DestReg = X86::DL; break;
22572       case X86::CX: DestReg = X86::CL; break;
22573       case X86::BX: DestReg = X86::BL; break;
22574       }
22575       if (DestReg) {
22576         Res.first = DestReg;
22577         Res.second = &X86::GR8RegClass;
22578       }
22579     } else if (VT == MVT::i32 || VT == MVT::f32) {
22580       unsigned DestReg = 0;
22581       switch (Res.first) {
22582       default: break;
22583       case X86::AX: DestReg = X86::EAX; break;
22584       case X86::DX: DestReg = X86::EDX; break;
22585       case X86::CX: DestReg = X86::ECX; break;
22586       case X86::BX: DestReg = X86::EBX; break;
22587       case X86::SI: DestReg = X86::ESI; break;
22588       case X86::DI: DestReg = X86::EDI; break;
22589       case X86::BP: DestReg = X86::EBP; break;
22590       case X86::SP: DestReg = X86::ESP; break;
22591       }
22592       if (DestReg) {
22593         Res.first = DestReg;
22594         Res.second = &X86::GR32RegClass;
22595       }
22596     } else if (VT == MVT::i64 || VT == MVT::f64) {
22597       unsigned DestReg = 0;
22598       switch (Res.first) {
22599       default: break;
22600       case X86::AX: DestReg = X86::RAX; break;
22601       case X86::DX: DestReg = X86::RDX; break;
22602       case X86::CX: DestReg = X86::RCX; break;
22603       case X86::BX: DestReg = X86::RBX; break;
22604       case X86::SI: DestReg = X86::RSI; break;
22605       case X86::DI: DestReg = X86::RDI; break;
22606       case X86::BP: DestReg = X86::RBP; break;
22607       case X86::SP: DestReg = X86::RSP; break;
22608       }
22609       if (DestReg) {
22610         Res.first = DestReg;
22611         Res.second = &X86::GR64RegClass;
22612       }
22613     }
22614   } else if (Res.second == &X86::FR32RegClass ||
22615              Res.second == &X86::FR64RegClass ||
22616              Res.second == &X86::VR128RegClass ||
22617              Res.second == &X86::VR256RegClass ||
22618              Res.second == &X86::FR32XRegClass ||
22619              Res.second == &X86::FR64XRegClass ||
22620              Res.second == &X86::VR128XRegClass ||
22621              Res.second == &X86::VR256XRegClass ||
22622              Res.second == &X86::VR512RegClass) {
22623     // Handle references to XMM physical registers that got mapped into the
22624     // wrong class.  This can happen with constraints like {xmm0} where the
22625     // target independent register mapper will just pick the first match it can
22626     // find, ignoring the required type.
22627
22628     if (VT == MVT::f32 || VT == MVT::i32)
22629       Res.second = &X86::FR32RegClass;
22630     else if (VT == MVT::f64 || VT == MVT::i64)
22631       Res.second = &X86::FR64RegClass;
22632     else if (X86::VR128RegClass.hasType(VT))
22633       Res.second = &X86::VR128RegClass;
22634     else if (X86::VR256RegClass.hasType(VT))
22635       Res.second = &X86::VR256RegClass;
22636     else if (X86::VR512RegClass.hasType(VT))
22637       Res.second = &X86::VR512RegClass;
22638   }
22639
22640   return Res;
22641 }
22642
22643 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22644                                             Type *Ty) const {
22645   // Scaling factors are not free at all.
22646   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22647   // will take 2 allocations in the out of order engine instead of 1
22648   // for plain addressing mode, i.e. inst (reg1).
22649   // E.g.,
22650   // vaddps (%rsi,%drx), %ymm0, %ymm1
22651   // Requires two allocations (one for the load, one for the computation)
22652   // whereas:
22653   // vaddps (%rsi), %ymm0, %ymm1
22654   // Requires just 1 allocation, i.e., freeing allocations for other operations
22655   // and having less micro operations to execute.
22656   //
22657   // For some X86 architectures, this is even worse because for instance for
22658   // stores, the complex addressing mode forces the instruction to use the
22659   // "load" ports instead of the dedicated "store" port.
22660   // E.g., on Haswell:
22661   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22662   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
22663   if (isLegalAddressingMode(AM, Ty))
22664     // Scale represents reg2 * scale, thus account for 1
22665     // as soon as we use a second register.
22666     return AM.Scale != 0;
22667   return -1;
22668 }
22669
22670 bool X86TargetLowering::isTargetFTOL() const {
22671   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
22672 }