24cc828aca100147848d8ab288052d7a3a61fd7a
[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/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 #define DEBUG_TYPE "x86-isel"
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64                                 SelectionDAG &DAG, SDLoc dl,
65                                 unsigned vectorWidth) {
66   assert((vectorWidth == 128 || vectorWidth == 256) &&
67          "Unsupported vector width");
68   EVT VT = Vec.getValueType();
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/vectorWidth;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
79   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80
81   // This is the index of the first element of the vectorWidth-bit chunk
82   // we want.
83   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84                                * ElemsPerChunk);
85
86   // If the input is a buildvector just emit a smaller one.
87   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
90                                     ElemsPerChunk));
91
92   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
94                                VecIdx);
95
96   return Result;
97
98 }
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106                                    SelectionDAG &DAG, SDLoc dl) {
107   assert((Vec.getValueType().is256BitVector() ||
108           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 }
111
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114                                    SelectionDAG &DAG, SDLoc dl) {
115   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 }
118
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120                                unsigned IdxVal, SelectionDAG &DAG,
121                                SDLoc dl, unsigned vectorWidth) {
122   assert((vectorWidth == 128 || vectorWidth == 256) &&
123          "Unsupported vector width");
124   // Inserting UNDEF is Result
125   if (Vec.getOpcode() == ISD::UNDEF)
126     return Result;
127   EVT VT = Vec.getValueType();
128   EVT ElVT = VT.getVectorElementType();
129   EVT ResultVT = Result.getValueType();
130
131   // Insert the relevant vectorWidth bits.
132   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
133
134   // This is the index of the first element of the vectorWidth-bit chunk
135   // we want.
136   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137                                * ElemsPerChunk);
138
139   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141                      VecIdx);
142 }
143 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference.  Idx is an index in the 128 bits
147 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150                                   unsigned IdxVal, SelectionDAG &DAG,
151                                   SDLoc dl) {
152   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 }
155
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 }
162
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168                                    unsigned NumElems, SelectionDAG &DAG,
169                                    SDLoc dl) {
170   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 }
173
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
182   if (TT.isOSBinFormatMachO()) {
183     if (TT.getArch() == Triple::x86_64)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (TT.isOSLinux())
189     return new X86LinuxTargetObjectFile();
190   if (TT.isOSBinFormatELF())
191     return new TargetLoweringObjectFileELF();
192   if (TT.isKnownWindowsMSVCEnvironment())
193     return new X86WindowsTargetObjectFile();
194   if (TT.isOSBinFormatCOFF())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird, it always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit since we have so many registers use the ILP scheduler, for
234   // 32-bit code use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2
247   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248     addBypassSlowDiv(32, 8);
249     if (Subtarget->is64Bit())
250       addBypassSlowDiv(64, 16);
251   }
252
253   if (Subtarget->isTargetKnownWindowsMSVC()) {
254     // Setup Windows compiler runtime calls.
255     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257     setLibcallName(RTLIB::SREM_I64, "_allrem");
258     setLibcallName(RTLIB::UREM_I64, "_aullrem");
259     setLibcallName(RTLIB::MUL_I64, "_allmul");
260     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
265
266     // The _ftol2 runtime function has an unusual calling conv, which
267     // is modeled by a special pseudo-instruction.
268     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
269     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
272   }
273
274   if (Subtarget->isTargetDarwin()) {
275     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276     setUseUnderscoreSetJmp(false);
277     setUseUnderscoreLongJmp(false);
278   } else if (Subtarget->isTargetWindowsGNU()) {
279     // MS runtime is weird: it exports _setjmp, but longjmp!
280     setUseUnderscoreSetJmp(true);
281     setUseUnderscoreLongJmp(false);
282   } else {
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(true);
285   }
286
287   // Set up the register classes.
288   addRegisterClass(MVT::i8, &X86::GR8RegClass);
289   addRegisterClass(MVT::i16, &X86::GR16RegClass);
290   addRegisterClass(MVT::i32, &X86::GR32RegClass);
291   if (Subtarget->is64Bit())
292     addRegisterClass(MVT::i64, &X86::GR64RegClass);
293
294   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
295
296   // We don't accept any truncstore of integer registers.
297   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
303
304   // SETOEQ and SETUNE require checking two conditions.
305   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
311
312   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
313   // operation.
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
317
318   if (Subtarget->is64Bit()) {
319     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
321   } else if (!TM.Options.UseSoftFloat) {
322     // We have an algorithm for SSE2->double, and we turn this into a
323     // 64-bit FILD followed by conditional FADD for other targets.
324     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
325     // We have an algorithm for SSE2, and we turn this into a 64-bit
326     // FILD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
328   }
329
330   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
331   // this operation.
332   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
334
335   if (!TM.Options.UseSoftFloat) {
336     // SSE has no i16 to fp conversion, only i32
337     if (X86ScalarSSEf32) {
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
339       // f32 and f64 cases are Legal, f80 case is not
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
341     } else {
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     }
345   } else {
346     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
348   }
349
350   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
351   // are Legal, f80 is custom lowered.
352   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
353   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
354
355   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
356   // this operation.
357   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
359
360   if (X86ScalarSSEf32) {
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
362     // f32 and f64 cases are Legal, f80 case is not
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
364   } else {
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   }
368
369   // Handle FP_TO_UINT by promoting the destination to a larger signed
370   // conversion.
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
374
375   if (Subtarget->is64Bit()) {
376     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
378   } else if (!TM.Options.UseSoftFloat) {
379     // Since AVX is a superset of SSE3, only check for SSE here.
380     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381       // Expand FP_TO_UINT into a select.
382       // FIXME: We would like to use a Custom expander here eventually to do
383       // the optimal thing for SSE vs. the default expansion in the legalizer.
384       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
385     else
386       // With SSE3 we can use fisttpll to convert to a signed i64; without
387       // SSE, we're stuck with a fistpll.
388       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
389   }
390
391   if (isTargetFTOL()) {
392     // Use the _ftol2 runtime function, which has a pseudo-instruction
393     // to handle its weird calling convention.
394     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
395   }
396
397   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398   if (!X86ScalarSSEf64) {
399     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
400     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
401     if (Subtarget->is64Bit()) {
402       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
403       // Without SSE, i64->f64 goes through memory.
404       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
405     }
406   }
407
408   // Scalar integer divide and remainder are lowered to use operations that
409   // produce two results, to match the available instructions. This exposes
410   // the two-result form to trivial CSE, which is able to combine x/y and x%y
411   // into a single instruction.
412   //
413   // Scalar integer multiply-high is also lowered to use two-result
414   // operations, to match the available instructions. However, plain multiply
415   // (low) operations are left as Legal, as there are single-result
416   // instructions for this in x86. Using the two-result multiply instructions
417   // when both high and low results are needed must be arranged by dagcombine.
418   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
419     MVT VT = IntVTs[i];
420     setOperationAction(ISD::MULHS, VT, Expand);
421     setOperationAction(ISD::MULHU, VT, Expand);
422     setOperationAction(ISD::SDIV, VT, Expand);
423     setOperationAction(ISD::UDIV, VT, Expand);
424     setOperationAction(ISD::SREM, VT, Expand);
425     setOperationAction(ISD::UREM, VT, Expand);
426
427     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428     setOperationAction(ISD::ADDC, VT, Custom);
429     setOperationAction(ISD::ADDE, VT, Custom);
430     setOperationAction(ISD::SUBC, VT, Custom);
431     setOperationAction(ISD::SUBE, VT, Custom);
432   }
433
434   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
435   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
436   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
443   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
444   if (Subtarget->is64Bit())
445     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
449   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
453   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
454
455   // Promote the i8 variants and force them on up to i32 which has a shorter
456   // encoding.
457   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
459   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
460   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
461   if (Subtarget->hasBMI()) {
462     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
464     if (Subtarget->is64Bit())
465       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
466   } else {
467     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
468     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
469     if (Subtarget->is64Bit())
470       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
471   }
472
473   if (Subtarget->hasLZCNT()) {
474     // When promoting the i8 variants, force them to i32 for a shorter
475     // encoding.
476     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
479     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
480     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
482     if (Subtarget->is64Bit())
483       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
484   } else {
485     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
486     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
491     if (Subtarget->is64Bit()) {
492       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
493       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
494     }
495   }
496
497   if (Subtarget->hasPOPCNT()) {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
499   } else {
500     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
501     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
505   }
506
507   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
508
509   if (!Subtarget->hasMOVBE())
510     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
511
512   // These should be promoted to a larger select which is supported.
513   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
514   // X86 wants to expand cmov itself.
515   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
516   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
517   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
522   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
527   if (Subtarget->is64Bit()) {
528     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
529     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
530   }
531   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
532   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534   // support continuation, user-level threading, and etc.. As a result, no
535   // other SjLj exception interfaces are implemented and please don't build
536   // your own exception handling based on them.
537   // LLVM/Clang supports zero-cost DWARF exception handling.
538   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
540
541   // Darwin ABI issue.
542   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
543   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
544   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
545   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
546   if (Subtarget->is64Bit())
547     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
549   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
550   if (Subtarget->is64Bit()) {
551     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
552     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
553     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
554     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
555     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
556   }
557   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
559   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
560   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
561   if (Subtarget->is64Bit()) {
562     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
563     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
564     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
565   }
566
567   if (Subtarget->hasSSE1())
568     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
569
570   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
571
572   // Expand certain atomics
573   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
574     MVT VT = IntVTs[i];
575     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
578   }
579
580   if (!Subtarget->is64Bit()) {
581     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
593   }
594
595   if (Subtarget->hasCmpxchg16b()) {
596     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
597   }
598
599   // FIXME - use subtarget debug flags
600   if (!Subtarget->isTargetDarwin() &&
601       !Subtarget->isTargetELF() &&
602       !Subtarget->isTargetCygMing()) {
603     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
604   }
605
606   if (Subtarget->is64Bit()) {
607     setExceptionPointerRegister(X86::RAX);
608     setExceptionSelectorRegister(X86::RDX);
609   } else {
610     setExceptionPointerRegister(X86::EAX);
611     setExceptionSelectorRegister(X86::EDX);
612   }
613   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
615
616   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
618
619   setOperationAction(ISD::TRAP, MVT::Other, Legal);
620   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
621
622   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
624   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
625   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626     // TargetInfo::X86_64ABIBuiltinVaList
627     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
628     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
629   } else {
630     // TargetInfo::CharPtrBuiltinVaList
631     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
632     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
633   }
634
635   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
636   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
637
638   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639                      MVT::i64 : MVT::i32, Custom);
640
641   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
642     // f32 and f64 use SSE.
643     // Set up the FP register classes.
644     addRegisterClass(MVT::f32, &X86::FR32RegClass);
645     addRegisterClass(MVT::f64, &X86::FR64RegClass);
646
647     // Use ANDPD to simulate FABS.
648     setOperationAction(ISD::FABS , MVT::f64, Custom);
649     setOperationAction(ISD::FABS , MVT::f32, Custom);
650
651     // Use XORP to simulate FNEG.
652     setOperationAction(ISD::FNEG , MVT::f64, Custom);
653     setOperationAction(ISD::FNEG , MVT::f32, Custom);
654
655     // Use ANDPD and ORPD to simulate FCOPYSIGN.
656     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
657     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
658
659     // Lower this to FGETSIGNx86 plus an AND.
660     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
661     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
662
663     // We don't support sin/cos/fmod
664     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
665     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
666     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
667     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
670
671     // Expand FP immediates into loads from the stack, except for the special
672     // cases we handle.
673     addLegalFPImmediate(APFloat(+0.0)); // xorpd
674     addLegalFPImmediate(APFloat(+0.0f)); // xorps
675   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
676     // Use SSE for f32, x87 for f64.
677     // Set up the FP register classes.
678     addRegisterClass(MVT::f32, &X86::FR32RegClass);
679     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
680
681     // Use ANDPS to simulate FABS.
682     setOperationAction(ISD::FABS , MVT::f32, Custom);
683
684     // Use XORP to simulate FNEG.
685     setOperationAction(ISD::FNEG , MVT::f32, Custom);
686
687     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
688
689     // Use ANDPS and ORPS to simulate FCOPYSIGN.
690     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
691     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
692
693     // We don't support sin/cos/fmod
694     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
695     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
696     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
697
698     // Special cases we handle for FP constants.
699     addLegalFPImmediate(APFloat(+0.0f)); // xorps
700     addLegalFPImmediate(APFloat(+0.0)); // FLD0
701     addLegalFPImmediate(APFloat(+1.0)); // FLD1
702     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
703     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
704
705     if (!TM.Options.UnsafeFPMath) {
706       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
707       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
708       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
709     }
710   } else if (!TM.Options.UseSoftFloat) {
711     // f32 and f64 in x87.
712     // Set up the FP register classes.
713     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
714     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
715
716     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
717     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
718     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
720
721     if (!TM.Options.UnsafeFPMath) {
722       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
723       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
724       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
725       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
726       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
727       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
728     }
729     addLegalFPImmediate(APFloat(+0.0)); // FLD0
730     addLegalFPImmediate(APFloat(+1.0)); // FLD1
731     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
732     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
733     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
734     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
735     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
736     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
737   }
738
739   // We don't support FMA.
740   setOperationAction(ISD::FMA, MVT::f64, Expand);
741   setOperationAction(ISD::FMA, MVT::f32, Expand);
742
743   // Long double always uses X87.
744   if (!TM.Options.UseSoftFloat) {
745     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
746     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
747     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
748     {
749       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
750       addLegalFPImmediate(TmpFlt);  // FLD0
751       TmpFlt.changeSign();
752       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
753
754       bool ignored;
755       APFloat TmpFlt2(+1.0);
756       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
757                       &ignored);
758       addLegalFPImmediate(TmpFlt2);  // FLD1
759       TmpFlt2.changeSign();
760       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
761     }
762
763     if (!TM.Options.UnsafeFPMath) {
764       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
765       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
766       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
767     }
768
769     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
770     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
771     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
772     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
773     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
774     setOperationAction(ISD::FMA, MVT::f80, Expand);
775   }
776
777   // Always use a library call for pow.
778   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
779   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
781
782   setOperationAction(ISD::FLOG, MVT::f80, Expand);
783   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
785   setOperationAction(ISD::FEXP, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
787
788   // First set operation action for all vector types to either promote
789   // (for widening) or expand (for scalarization). Then we will selectively
790   // turn on ones that can be effectively codegen'd.
791   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
792            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
793     MVT VT = (MVT::SimpleValueType)i;
794     setOperationAction(ISD::ADD , VT, Expand);
795     setOperationAction(ISD::SUB , VT, Expand);
796     setOperationAction(ISD::FADD, VT, Expand);
797     setOperationAction(ISD::FNEG, VT, Expand);
798     setOperationAction(ISD::FSUB, VT, Expand);
799     setOperationAction(ISD::MUL , VT, Expand);
800     setOperationAction(ISD::FMUL, VT, Expand);
801     setOperationAction(ISD::SDIV, VT, Expand);
802     setOperationAction(ISD::UDIV, VT, Expand);
803     setOperationAction(ISD::FDIV, VT, Expand);
804     setOperationAction(ISD::SREM, VT, Expand);
805     setOperationAction(ISD::UREM, VT, Expand);
806     setOperationAction(ISD::LOAD, VT, Expand);
807     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
808     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
809     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
810     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
811     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
812     setOperationAction(ISD::FABS, VT, Expand);
813     setOperationAction(ISD::FSIN, VT, Expand);
814     setOperationAction(ISD::FSINCOS, VT, Expand);
815     setOperationAction(ISD::FCOS, VT, Expand);
816     setOperationAction(ISD::FSINCOS, VT, Expand);
817     setOperationAction(ISD::FREM, VT, Expand);
818     setOperationAction(ISD::FMA,  VT, Expand);
819     setOperationAction(ISD::FPOWI, VT, Expand);
820     setOperationAction(ISD::FSQRT, VT, Expand);
821     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
822     setOperationAction(ISD::FFLOOR, VT, Expand);
823     setOperationAction(ISD::FCEIL, VT, Expand);
824     setOperationAction(ISD::FTRUNC, VT, Expand);
825     setOperationAction(ISD::FRINT, VT, Expand);
826     setOperationAction(ISD::FNEARBYINT, VT, Expand);
827     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
828     setOperationAction(ISD::MULHS, VT, Expand);
829     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
830     setOperationAction(ISD::MULHU, VT, Expand);
831     setOperationAction(ISD::SDIVREM, VT, Expand);
832     setOperationAction(ISD::UDIVREM, VT, Expand);
833     setOperationAction(ISD::FPOW, VT, Expand);
834     setOperationAction(ISD::CTPOP, VT, Expand);
835     setOperationAction(ISD::CTTZ, VT, Expand);
836     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
837     setOperationAction(ISD::CTLZ, VT, Expand);
838     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
839     setOperationAction(ISD::SHL, VT, Expand);
840     setOperationAction(ISD::SRA, VT, Expand);
841     setOperationAction(ISD::SRL, VT, Expand);
842     setOperationAction(ISD::ROTL, VT, Expand);
843     setOperationAction(ISD::ROTR, VT, Expand);
844     setOperationAction(ISD::BSWAP, VT, Expand);
845     setOperationAction(ISD::SETCC, VT, Expand);
846     setOperationAction(ISD::FLOG, VT, Expand);
847     setOperationAction(ISD::FLOG2, VT, Expand);
848     setOperationAction(ISD::FLOG10, VT, Expand);
849     setOperationAction(ISD::FEXP, VT, Expand);
850     setOperationAction(ISD::FEXP2, VT, Expand);
851     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
852     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
853     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
854     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
856     setOperationAction(ISD::TRUNCATE, VT, Expand);
857     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
858     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
859     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
860     setOperationAction(ISD::VSELECT, 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     // Custom lower several nodes.
1434     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1435              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1436       MVT VT = (MVT::SimpleValueType)i;
1437
1438       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1439       // Extract subvector is special because the value type
1440       // (result) is 256/128-bit but the source is 512-bit wide.
1441       if (VT.is128BitVector() || VT.is256BitVector())
1442         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1443
1444       if (VT.getVectorElementType() == MVT::i1)
1445         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1446
1447       // Do not attempt to custom lower other non-512-bit vectors
1448       if (!VT.is512BitVector())
1449         continue;
1450
1451       if ( EltSize >= 32) {
1452         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1453         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1454         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1455         setOperationAction(ISD::VSELECT,             VT, Legal);
1456         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1457         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1458         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1459       }
1460     }
1461     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1462       MVT VT = (MVT::SimpleValueType)i;
1463
1464       // Do not attempt to promote non-256-bit vectors
1465       if (!VT.is512BitVector())
1466         continue;
1467
1468       setOperationAction(ISD::SELECT, VT, Promote);
1469       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1470     }
1471   }// has  AVX-512
1472
1473   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1474   // of this type with custom code.
1475   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1476            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1477     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1478                        Custom);
1479   }
1480
1481   // We want to custom lower some of our intrinsics.
1482   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1483   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1484   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1485   if (!Subtarget->is64Bit())
1486     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1487
1488   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1489   // handle type legalization for these operations here.
1490   //
1491   // FIXME: We really should do custom legalization for addition and
1492   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1493   // than generic legalization for 64-bit multiplication-with-overflow, though.
1494   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1495     // Add/Sub/Mul with overflow operations are custom lowered.
1496     MVT VT = IntVTs[i];
1497     setOperationAction(ISD::SADDO, VT, Custom);
1498     setOperationAction(ISD::UADDO, VT, Custom);
1499     setOperationAction(ISD::SSUBO, VT, Custom);
1500     setOperationAction(ISD::USUBO, VT, Custom);
1501     setOperationAction(ISD::SMULO, VT, Custom);
1502     setOperationAction(ISD::UMULO, VT, Custom);
1503   }
1504
1505   // There are no 8-bit 3-address imul/mul instructions
1506   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1507   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1508
1509   if (!Subtarget->is64Bit()) {
1510     // These libcalls are not available in 32-bit.
1511     setLibcallName(RTLIB::SHL_I128, nullptr);
1512     setLibcallName(RTLIB::SRL_I128, nullptr);
1513     setLibcallName(RTLIB::SRA_I128, nullptr);
1514   }
1515
1516   // Combine sin / cos into one node or libcall if possible.
1517   if (Subtarget->hasSinCos()) {
1518     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1519     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1520     if (Subtarget->isTargetDarwin()) {
1521       // For MacOSX, we don't want to the normal expansion of a libcall to
1522       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1523       // traffic.
1524       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1525       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1526     }
1527   }
1528
1529   if (Subtarget->isTargetWin64()) {
1530     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1531     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1532     setOperationAction(ISD::SREM, MVT::i128, Custom);
1533     setOperationAction(ISD::UREM, MVT::i128, Custom);
1534     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1535     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1536   }
1537
1538   // We have target-specific dag combine patterns for the following nodes:
1539   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1540   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1541   setTargetDAGCombine(ISD::VSELECT);
1542   setTargetDAGCombine(ISD::SELECT);
1543   setTargetDAGCombine(ISD::SHL);
1544   setTargetDAGCombine(ISD::SRA);
1545   setTargetDAGCombine(ISD::SRL);
1546   setTargetDAGCombine(ISD::OR);
1547   setTargetDAGCombine(ISD::AND);
1548   setTargetDAGCombine(ISD::ADD);
1549   setTargetDAGCombine(ISD::FADD);
1550   setTargetDAGCombine(ISD::FSUB);
1551   setTargetDAGCombine(ISD::FMA);
1552   setTargetDAGCombine(ISD::SUB);
1553   setTargetDAGCombine(ISD::LOAD);
1554   setTargetDAGCombine(ISD::STORE);
1555   setTargetDAGCombine(ISD::ZERO_EXTEND);
1556   setTargetDAGCombine(ISD::ANY_EXTEND);
1557   setTargetDAGCombine(ISD::SIGN_EXTEND);
1558   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1559   setTargetDAGCombine(ISD::TRUNCATE);
1560   setTargetDAGCombine(ISD::SINT_TO_FP);
1561   setTargetDAGCombine(ISD::SETCC);
1562   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1563   if (Subtarget->is64Bit())
1564     setTargetDAGCombine(ISD::MUL);
1565   setTargetDAGCombine(ISD::XOR);
1566
1567   computeRegisterProperties();
1568
1569   // On Darwin, -Os means optimize for size without hurting performance,
1570   // do not reduce the limit.
1571   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1572   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1573   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1574   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1575   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1576   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1577   setPrefLoopAlignment(4); // 2^4 bytes.
1578
1579   // Predictable cmov don't hurt on atom because it's in-order.
1580   PredictableSelectIsExpensive = !Subtarget->isAtom();
1581
1582   setPrefFunctionAlignment(4); // 2^4 bytes.
1583 }
1584
1585 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1586   if (!VT.isVector())
1587     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1588
1589   if (Subtarget->hasAVX512())
1590     switch(VT.getVectorNumElements()) {
1591     case  8: return MVT::v8i1;
1592     case 16: return MVT::v16i1;
1593   }
1594
1595   return VT.changeVectorElementTypeToInteger();
1596 }
1597
1598 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1599 /// the desired ByVal argument alignment.
1600 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1601   if (MaxAlign == 16)
1602     return;
1603   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1604     if (VTy->getBitWidth() == 128)
1605       MaxAlign = 16;
1606   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1607     unsigned EltAlign = 0;
1608     getMaxByValAlign(ATy->getElementType(), EltAlign);
1609     if (EltAlign > MaxAlign)
1610       MaxAlign = EltAlign;
1611   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1612     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1613       unsigned EltAlign = 0;
1614       getMaxByValAlign(STy->getElementType(i), EltAlign);
1615       if (EltAlign > MaxAlign)
1616         MaxAlign = EltAlign;
1617       if (MaxAlign == 16)
1618         break;
1619     }
1620   }
1621 }
1622
1623 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1624 /// function arguments in the caller parameter area. For X86, aggregates
1625 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1626 /// are at 4-byte boundaries.
1627 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1628   if (Subtarget->is64Bit()) {
1629     // Max of 8 and alignment of type.
1630     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1631     if (TyAlign > 8)
1632       return TyAlign;
1633     return 8;
1634   }
1635
1636   unsigned Align = 4;
1637   if (Subtarget->hasSSE1())
1638     getMaxByValAlign(Ty, Align);
1639   return Align;
1640 }
1641
1642 /// getOptimalMemOpType - Returns the target specific optimal type for load
1643 /// and store operations as a result of memset, memcpy, and memmove
1644 /// lowering. If DstAlign is zero that means it's safe to destination
1645 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1646 /// means there isn't a need to check it against alignment requirement,
1647 /// probably because the source does not need to be loaded. If 'IsMemset' is
1648 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1649 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1650 /// source is constant so it does not need to be loaded.
1651 /// It returns EVT::Other if the type should be determined using generic
1652 /// target-independent logic.
1653 EVT
1654 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1655                                        unsigned DstAlign, unsigned SrcAlign,
1656                                        bool IsMemset, bool ZeroMemset,
1657                                        bool MemcpyStrSrc,
1658                                        MachineFunction &MF) const {
1659   const Function *F = MF.getFunction();
1660   if ((!IsMemset || ZeroMemset) &&
1661       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1662                                        Attribute::NoImplicitFloat)) {
1663     if (Size >= 16 &&
1664         (Subtarget->isUnalignedMemAccessFast() ||
1665          ((DstAlign == 0 || DstAlign >= 16) &&
1666           (SrcAlign == 0 || SrcAlign >= 16)))) {
1667       if (Size >= 32) {
1668         if (Subtarget->hasInt256())
1669           return MVT::v8i32;
1670         if (Subtarget->hasFp256())
1671           return MVT::v8f32;
1672       }
1673       if (Subtarget->hasSSE2())
1674         return MVT::v4i32;
1675       if (Subtarget->hasSSE1())
1676         return MVT::v4f32;
1677     } else if (!MemcpyStrSrc && Size >= 8 &&
1678                !Subtarget->is64Bit() &&
1679                Subtarget->hasSSE2()) {
1680       // Do not use f64 to lower memcpy if source is string constant. It's
1681       // better to use i32 to avoid the loads.
1682       return MVT::f64;
1683     }
1684   }
1685   if (Subtarget->is64Bit() && Size >= 8)
1686     return MVT::i64;
1687   return MVT::i32;
1688 }
1689
1690 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1691   if (VT == MVT::f32)
1692     return X86ScalarSSEf32;
1693   else if (VT == MVT::f64)
1694     return X86ScalarSSEf64;
1695   return true;
1696 }
1697
1698 bool
1699 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1700                                                  unsigned,
1701                                                  bool *Fast) const {
1702   if (Fast)
1703     *Fast = Subtarget->isUnalignedMemAccessFast();
1704   return true;
1705 }
1706
1707 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1708 /// current function.  The returned value is a member of the
1709 /// MachineJumpTableInfo::JTEntryKind enum.
1710 unsigned X86TargetLowering::getJumpTableEncoding() const {
1711   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1712   // symbol.
1713   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1714       Subtarget->isPICStyleGOT())
1715     return MachineJumpTableInfo::EK_Custom32;
1716
1717   // Otherwise, use the normal jump table encoding heuristics.
1718   return TargetLowering::getJumpTableEncoding();
1719 }
1720
1721 const MCExpr *
1722 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1723                                              const MachineBasicBlock *MBB,
1724                                              unsigned uid,MCContext &Ctx) const{
1725   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1726          Subtarget->isPICStyleGOT());
1727   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1728   // entries.
1729   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1730                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1731 }
1732
1733 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1734 /// jumptable.
1735 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1736                                                     SelectionDAG &DAG) const {
1737   if (!Subtarget->is64Bit())
1738     // This doesn't have SDLoc associated with it, but is not really the
1739     // same as a Register.
1740     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1741   return Table;
1742 }
1743
1744 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1745 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1746 /// MCExpr.
1747 const MCExpr *X86TargetLowering::
1748 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1749                              MCContext &Ctx) const {
1750   // X86-64 uses RIP relative addressing based on the jump table label.
1751   if (Subtarget->isPICStyleRIPRel())
1752     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1753
1754   // Otherwise, the reference is relative to the PIC base.
1755   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1756 }
1757
1758 // FIXME: Why this routine is here? Move to RegInfo!
1759 std::pair<const TargetRegisterClass*, uint8_t>
1760 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1761   const TargetRegisterClass *RRC = nullptr;
1762   uint8_t Cost = 1;
1763   switch (VT.SimpleTy) {
1764   default:
1765     return TargetLowering::findRepresentativeClass(VT);
1766   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1767     RRC = Subtarget->is64Bit() ?
1768       (const TargetRegisterClass*)&X86::GR64RegClass :
1769       (const TargetRegisterClass*)&X86::GR32RegClass;
1770     break;
1771   case MVT::x86mmx:
1772     RRC = &X86::VR64RegClass;
1773     break;
1774   case MVT::f32: case MVT::f64:
1775   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1776   case MVT::v4f32: case MVT::v2f64:
1777   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1778   case MVT::v4f64:
1779     RRC = &X86::VR128RegClass;
1780     break;
1781   }
1782   return std::make_pair(RRC, Cost);
1783 }
1784
1785 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1786                                                unsigned &Offset) const {
1787   if (!Subtarget->isTargetLinux())
1788     return false;
1789
1790   if (Subtarget->is64Bit()) {
1791     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1792     Offset = 0x28;
1793     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1794       AddressSpace = 256;
1795     else
1796       AddressSpace = 257;
1797   } else {
1798     // %gs:0x14 on i386
1799     Offset = 0x14;
1800     AddressSpace = 256;
1801   }
1802   return true;
1803 }
1804
1805 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1806                                             unsigned DestAS) const {
1807   assert(SrcAS != DestAS && "Expected different address spaces!");
1808
1809   return SrcAS < 256 && DestAS < 256;
1810 }
1811
1812 //===----------------------------------------------------------------------===//
1813 //               Return Value Calling Convention Implementation
1814 //===----------------------------------------------------------------------===//
1815
1816 #include "X86GenCallingConv.inc"
1817
1818 bool
1819 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1820                                   MachineFunction &MF, bool isVarArg,
1821                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1822                         LLVMContext &Context) const {
1823   SmallVector<CCValAssign, 16> RVLocs;
1824   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1825                  RVLocs, Context);
1826   return CCInfo.CheckReturn(Outs, RetCC_X86);
1827 }
1828
1829 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1830   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1831   return ScratchRegs;
1832 }
1833
1834 SDValue
1835 X86TargetLowering::LowerReturn(SDValue Chain,
1836                                CallingConv::ID CallConv, bool isVarArg,
1837                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1838                                const SmallVectorImpl<SDValue> &OutVals,
1839                                SDLoc dl, SelectionDAG &DAG) const {
1840   MachineFunction &MF = DAG.getMachineFunction();
1841   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1842
1843   SmallVector<CCValAssign, 16> RVLocs;
1844   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1845                  RVLocs, *DAG.getContext());
1846   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1847
1848   SDValue Flag;
1849   SmallVector<SDValue, 6> RetOps;
1850   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1851   // Operand #1 = Bytes To Pop
1852   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1853                    MVT::i16));
1854
1855   // Copy the result values into the output registers.
1856   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1857     CCValAssign &VA = RVLocs[i];
1858     assert(VA.isRegLoc() && "Can only return in registers!");
1859     SDValue ValToCopy = OutVals[i];
1860     EVT ValVT = ValToCopy.getValueType();
1861
1862     // Promote values to the appropriate types
1863     if (VA.getLocInfo() == CCValAssign::SExt)
1864       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1865     else if (VA.getLocInfo() == CCValAssign::ZExt)
1866       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1867     else if (VA.getLocInfo() == CCValAssign::AExt)
1868       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1869     else if (VA.getLocInfo() == CCValAssign::BCvt)
1870       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1871
1872     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1873            "Unexpected FP-extend for return value.");  
1874
1875     // If this is x86-64, and we disabled SSE, we can't return FP values,
1876     // or SSE or MMX vectors.
1877     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1878          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1879           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1880       report_fatal_error("SSE register return with SSE disabled");
1881     }
1882     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1883     // llvm-gcc has never done it right and no one has noticed, so this
1884     // should be OK for now.
1885     if (ValVT == MVT::f64 &&
1886         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1887       report_fatal_error("SSE2 register return with SSE2 disabled");
1888
1889     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1890     // the RET instruction and handled by the FP Stackifier.
1891     if (VA.getLocReg() == X86::ST0 ||
1892         VA.getLocReg() == X86::ST1) {
1893       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1894       // change the value to the FP stack register class.
1895       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1896         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1897       RetOps.push_back(ValToCopy);
1898       // Don't emit a copytoreg.
1899       continue;
1900     }
1901
1902     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1903     // which is returned in RAX / RDX.
1904     if (Subtarget->is64Bit()) {
1905       if (ValVT == MVT::x86mmx) {
1906         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1907           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1908           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1909                                   ValToCopy);
1910           // If we don't have SSE2 available, convert to v4f32 so the generated
1911           // register is legal.
1912           if (!Subtarget->hasSSE2())
1913             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1914         }
1915       }
1916     }
1917
1918     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1919     Flag = Chain.getValue(1);
1920     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1921   }
1922
1923   // The x86-64 ABIs require that for returning structs by value we copy
1924   // the sret argument into %rax/%eax (depending on ABI) for the return.
1925   // Win32 requires us to put the sret argument to %eax as well.
1926   // We saved the argument into a virtual register in the entry block,
1927   // so now we copy the value out and into %rax/%eax.
1928   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1929       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1930     MachineFunction &MF = DAG.getMachineFunction();
1931     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1932     unsigned Reg = FuncInfo->getSRetReturnReg();
1933     assert(Reg &&
1934            "SRetReturnReg should have been set in LowerFormalArguments().");
1935     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1936
1937     unsigned RetValReg
1938         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1939           X86::RAX : X86::EAX;
1940     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1941     Flag = Chain.getValue(1);
1942
1943     // RAX/EAX now acts like a return value.
1944     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1945   }
1946
1947   RetOps[0] = Chain;  // Update chain.
1948
1949   // Add the flag if we have it.
1950   if (Flag.getNode())
1951     RetOps.push_back(Flag);
1952
1953   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1954 }
1955
1956 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1957   if (N->getNumValues() != 1)
1958     return false;
1959   if (!N->hasNUsesOfValue(1, 0))
1960     return false;
1961
1962   SDValue TCChain = Chain;
1963   SDNode *Copy = *N->use_begin();
1964   if (Copy->getOpcode() == ISD::CopyToReg) {
1965     // If the copy has a glue operand, we conservatively assume it isn't safe to
1966     // perform a tail call.
1967     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1968       return false;
1969     TCChain = Copy->getOperand(0);
1970   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1971     return false;
1972
1973   bool HasRet = false;
1974   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1975        UI != UE; ++UI) {
1976     if (UI->getOpcode() != X86ISD::RET_FLAG)
1977       return false;
1978     HasRet = true;
1979   }
1980
1981   if (!HasRet)
1982     return false;
1983
1984   Chain = TCChain;
1985   return true;
1986 }
1987
1988 MVT
1989 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1990                                             ISD::NodeType ExtendKind) const {
1991   MVT ReturnMVT;
1992   // TODO: Is this also valid on 32-bit?
1993   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1994     ReturnMVT = MVT::i8;
1995   else
1996     ReturnMVT = MVT::i32;
1997
1998   MVT MinVT = getRegisterType(ReturnMVT);
1999   return VT.bitsLT(MinVT) ? MinVT : VT;
2000 }
2001
2002 /// LowerCallResult - Lower the result values of a call into the
2003 /// appropriate copies out of appropriate physical registers.
2004 ///
2005 SDValue
2006 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2007                                    CallingConv::ID CallConv, bool isVarArg,
2008                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2009                                    SDLoc dl, SelectionDAG &DAG,
2010                                    SmallVectorImpl<SDValue> &InVals) const {
2011
2012   // Assign locations to each value returned by this call.
2013   SmallVector<CCValAssign, 16> RVLocs;
2014   bool Is64Bit = Subtarget->is64Bit();
2015   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2016                  getTargetMachine(), RVLocs, *DAG.getContext());
2017   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2018
2019   // Copy all of the result registers out of their specified physreg.
2020   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2021     CCValAssign &VA = RVLocs[i];
2022     EVT CopyVT = VA.getValVT();
2023
2024     // If this is x86-64, and we disabled SSE, we can't return FP values
2025     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2026         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2027       report_fatal_error("SSE register return with SSE disabled");
2028     }
2029
2030     SDValue Val;
2031
2032     // If this is a call to a function that returns an fp value on the floating
2033     // point stack, we must guarantee the value is popped from the stack, so
2034     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2035     // if the return value is not used. We use the FpPOP_RETVAL instruction
2036     // instead.
2037     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2038       // If we prefer to use the value in xmm registers, copy it out as f80 and
2039       // use a truncate to move it from fp stack reg to xmm reg.
2040       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2041       SDValue Ops[] = { Chain, InFlag };
2042       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2043                                          MVT::Other, MVT::Glue, Ops), 1);
2044       Val = Chain.getValue(0);
2045
2046       // Round the f80 to the right size, which also moves it to the appropriate
2047       // xmm register.
2048       if (CopyVT != VA.getValVT())
2049         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2050                           // This truncation won't change the value.
2051                           DAG.getIntPtrConstant(1));
2052     } else {
2053       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2054                                  CopyVT, InFlag).getValue(1);
2055       Val = Chain.getValue(0);
2056     }
2057     InFlag = Chain.getValue(2);
2058     InVals.push_back(Val);
2059   }
2060
2061   return Chain;
2062 }
2063
2064 //===----------------------------------------------------------------------===//
2065 //                C & StdCall & Fast Calling Convention implementation
2066 //===----------------------------------------------------------------------===//
2067 //  StdCall calling convention seems to be standard for many Windows' API
2068 //  routines and around. It differs from C calling convention just a little:
2069 //  callee should clean up the stack, not caller. Symbols should be also
2070 //  decorated in some fancy way :) It doesn't support any vector arguments.
2071 //  For info on fast calling convention see Fast Calling Convention (tail call)
2072 //  implementation LowerX86_32FastCCCallTo.
2073
2074 /// CallIsStructReturn - Determines whether a call uses struct return
2075 /// semantics.
2076 enum StructReturnType {
2077   NotStructReturn,
2078   RegStructReturn,
2079   StackStructReturn
2080 };
2081 static StructReturnType
2082 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2083   if (Outs.empty())
2084     return NotStructReturn;
2085
2086   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2087   if (!Flags.isSRet())
2088     return NotStructReturn;
2089   if (Flags.isInReg())
2090     return RegStructReturn;
2091   return StackStructReturn;
2092 }
2093
2094 /// ArgsAreStructReturn - Determines whether a function uses struct
2095 /// return semantics.
2096 static StructReturnType
2097 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2098   if (Ins.empty())
2099     return NotStructReturn;
2100
2101   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2102   if (!Flags.isSRet())
2103     return NotStructReturn;
2104   if (Flags.isInReg())
2105     return RegStructReturn;
2106   return StackStructReturn;
2107 }
2108
2109 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2110 /// by "Src" to address "Dst" with size and alignment information specified by
2111 /// the specific parameter attribute. The copy will be passed as a byval
2112 /// function parameter.
2113 static SDValue
2114 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2115                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2116                           SDLoc dl) {
2117   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2118
2119   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2120                        /*isVolatile*/false, /*AlwaysInline=*/true,
2121                        MachinePointerInfo(), MachinePointerInfo());
2122 }
2123
2124 /// IsTailCallConvention - Return true if the calling convention is one that
2125 /// supports tail call optimization.
2126 static bool IsTailCallConvention(CallingConv::ID CC) {
2127   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2128           CC == CallingConv::HiPE);
2129 }
2130
2131 /// \brief Return true if the calling convention is a C calling convention.
2132 static bool IsCCallConvention(CallingConv::ID CC) {
2133   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2134           CC == CallingConv::X86_64_SysV);
2135 }
2136
2137 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2138   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2139     return false;
2140
2141   CallSite CS(CI);
2142   CallingConv::ID CalleeCC = CS.getCallingConv();
2143   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2144     return false;
2145
2146   return true;
2147 }
2148
2149 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2150 /// a tailcall target by changing its ABI.
2151 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2152                                    bool GuaranteedTailCallOpt) {
2153   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2154 }
2155
2156 SDValue
2157 X86TargetLowering::LowerMemArgument(SDValue Chain,
2158                                     CallingConv::ID CallConv,
2159                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2160                                     SDLoc dl, SelectionDAG &DAG,
2161                                     const CCValAssign &VA,
2162                                     MachineFrameInfo *MFI,
2163                                     unsigned i) const {
2164   // Create the nodes corresponding to a load from this parameter slot.
2165   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2166   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2167                               getTargetMachine().Options.GuaranteedTailCallOpt);
2168   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2169   EVT ValVT;
2170
2171   // If value is passed by pointer we have address passed instead of the value
2172   // itself.
2173   if (VA.getLocInfo() == CCValAssign::Indirect)
2174     ValVT = VA.getLocVT();
2175   else
2176     ValVT = VA.getValVT();
2177
2178   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2179   // changed with more analysis.
2180   // In case of tail call optimization mark all arguments mutable. Since they
2181   // could be overwritten by lowering of arguments in case of a tail call.
2182   if (Flags.isByVal()) {
2183     unsigned Bytes = Flags.getByValSize();
2184     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2185     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2186     return DAG.getFrameIndex(FI, getPointerTy());
2187   } else {
2188     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2189                                     VA.getLocMemOffset(), isImmutable);
2190     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2191     return DAG.getLoad(ValVT, dl, Chain, FIN,
2192                        MachinePointerInfo::getFixedStack(FI),
2193                        false, false, false, 0);
2194   }
2195 }
2196
2197 SDValue
2198 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2199                                         CallingConv::ID CallConv,
2200                                         bool isVarArg,
2201                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2202                                         SDLoc dl,
2203                                         SelectionDAG &DAG,
2204                                         SmallVectorImpl<SDValue> &InVals)
2205                                           const {
2206   MachineFunction &MF = DAG.getMachineFunction();
2207   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2208
2209   const Function* Fn = MF.getFunction();
2210   if (Fn->hasExternalLinkage() &&
2211       Subtarget->isTargetCygMing() &&
2212       Fn->getName() == "main")
2213     FuncInfo->setForceFramePointer(true);
2214
2215   MachineFrameInfo *MFI = MF.getFrameInfo();
2216   bool Is64Bit = Subtarget->is64Bit();
2217   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2218
2219   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2220          "Var args not supported with calling convention fastcc, ghc or hipe");
2221
2222   // Assign locations to all of the incoming arguments.
2223   SmallVector<CCValAssign, 16> ArgLocs;
2224   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2225                  ArgLocs, *DAG.getContext());
2226
2227   // Allocate shadow area for Win64
2228   if (IsWin64)
2229     CCInfo.AllocateStack(32, 8);
2230
2231   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2232
2233   unsigned LastVal = ~0U;
2234   SDValue ArgValue;
2235   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2236     CCValAssign &VA = ArgLocs[i];
2237     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2238     // places.
2239     assert(VA.getValNo() != LastVal &&
2240            "Don't support value assigned to multiple locs yet");
2241     (void)LastVal;
2242     LastVal = VA.getValNo();
2243
2244     if (VA.isRegLoc()) {
2245       EVT RegVT = VA.getLocVT();
2246       const TargetRegisterClass *RC;
2247       if (RegVT == MVT::i32)
2248         RC = &X86::GR32RegClass;
2249       else if (Is64Bit && RegVT == MVT::i64)
2250         RC = &X86::GR64RegClass;
2251       else if (RegVT == MVT::f32)
2252         RC = &X86::FR32RegClass;
2253       else if (RegVT == MVT::f64)
2254         RC = &X86::FR64RegClass;
2255       else if (RegVT.is512BitVector())
2256         RC = &X86::VR512RegClass;
2257       else if (RegVT.is256BitVector())
2258         RC = &X86::VR256RegClass;
2259       else if (RegVT.is128BitVector())
2260         RC = &X86::VR128RegClass;
2261       else if (RegVT == MVT::x86mmx)
2262         RC = &X86::VR64RegClass;
2263       else if (RegVT == MVT::i1)
2264         RC = &X86::VK1RegClass;
2265       else if (RegVT == MVT::v8i1)
2266         RC = &X86::VK8RegClass;
2267       else if (RegVT == MVT::v16i1)
2268         RC = &X86::VK16RegClass;
2269       else
2270         llvm_unreachable("Unknown argument type!");
2271
2272       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2273       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2274
2275       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2276       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2277       // right size.
2278       if (VA.getLocInfo() == CCValAssign::SExt)
2279         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2280                                DAG.getValueType(VA.getValVT()));
2281       else if (VA.getLocInfo() == CCValAssign::ZExt)
2282         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2283                                DAG.getValueType(VA.getValVT()));
2284       else if (VA.getLocInfo() == CCValAssign::BCvt)
2285         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2286
2287       if (VA.isExtInLoc()) {
2288         // Handle MMX values passed in XMM regs.
2289         if (RegVT.isVector())
2290           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2291         else
2292           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2293       }
2294     } else {
2295       assert(VA.isMemLoc());
2296       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2297     }
2298
2299     // If value is passed via pointer - do a load.
2300     if (VA.getLocInfo() == CCValAssign::Indirect)
2301       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2302                              MachinePointerInfo(), false, false, false, 0);
2303
2304     InVals.push_back(ArgValue);
2305   }
2306
2307   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2308     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2309       // The x86-64 ABIs require that for returning structs by value we copy
2310       // the sret argument into %rax/%eax (depending on ABI) for the return.
2311       // Win32 requires us to put the sret argument to %eax as well.
2312       // Save the argument into a virtual register so that we can access it
2313       // from the return points.
2314       if (Ins[i].Flags.isSRet()) {
2315         unsigned Reg = FuncInfo->getSRetReturnReg();
2316         if (!Reg) {
2317           MVT PtrTy = getPointerTy();
2318           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2319           FuncInfo->setSRetReturnReg(Reg);
2320         }
2321         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2322         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2323         break;
2324       }
2325     }
2326   }
2327
2328   unsigned StackSize = CCInfo.getNextStackOffset();
2329   // Align stack specially for tail calls.
2330   if (FuncIsMadeTailCallSafe(CallConv,
2331                              MF.getTarget().Options.GuaranteedTailCallOpt))
2332     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2333
2334   // If the function takes variable number of arguments, make a frame index for
2335   // the start of the first vararg value... for expansion of llvm.va_start.
2336   if (isVarArg) {
2337     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2338                     CallConv != CallingConv::X86_ThisCall)) {
2339       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2340     }
2341     if (Is64Bit) {
2342       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2343
2344       // FIXME: We should really autogenerate these arrays
2345       static const MCPhysReg GPR64ArgRegsWin64[] = {
2346         X86::RCX, X86::RDX, X86::R8,  X86::R9
2347       };
2348       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2349         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2350       };
2351       static const MCPhysReg XMMArgRegs64Bit[] = {
2352         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2353         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2354       };
2355       const MCPhysReg *GPR64ArgRegs;
2356       unsigned NumXMMRegs = 0;
2357
2358       if (IsWin64) {
2359         // The XMM registers which might contain var arg parameters are shadowed
2360         // in their paired GPR.  So we only need to save the GPR to their home
2361         // slots.
2362         TotalNumIntRegs = 4;
2363         GPR64ArgRegs = GPR64ArgRegsWin64;
2364       } else {
2365         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2366         GPR64ArgRegs = GPR64ArgRegs64Bit;
2367
2368         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2369                                                 TotalNumXMMRegs);
2370       }
2371       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2372                                                        TotalNumIntRegs);
2373
2374       bool NoImplicitFloatOps = Fn->getAttributes().
2375         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2376       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2377              "SSE register cannot be used when SSE is disabled!");
2378       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2379                NoImplicitFloatOps) &&
2380              "SSE register cannot be used when SSE is disabled!");
2381       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2382           !Subtarget->hasSSE1())
2383         // Kernel mode asks for SSE to be disabled, so don't push them
2384         // on the stack.
2385         TotalNumXMMRegs = 0;
2386
2387       if (IsWin64) {
2388         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2389         // Get to the caller-allocated home save location.  Add 8 to account
2390         // for the return address.
2391         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2392         FuncInfo->setRegSaveFrameIndex(
2393           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2394         // Fixup to set vararg frame on shadow area (4 x i64).
2395         if (NumIntRegs < 4)
2396           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2397       } else {
2398         // For X86-64, if there are vararg parameters that are passed via
2399         // registers, then we must store them to their spots on the stack so
2400         // they may be loaded by deferencing the result of va_next.
2401         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2402         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2403         FuncInfo->setRegSaveFrameIndex(
2404           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2405                                false));
2406       }
2407
2408       // Store the integer parameter registers.
2409       SmallVector<SDValue, 8> MemOps;
2410       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2411                                         getPointerTy());
2412       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2413       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2414         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2415                                   DAG.getIntPtrConstant(Offset));
2416         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2417                                      &X86::GR64RegClass);
2418         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2419         SDValue Store =
2420           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2421                        MachinePointerInfo::getFixedStack(
2422                          FuncInfo->getRegSaveFrameIndex(), Offset),
2423                        false, false, 0);
2424         MemOps.push_back(Store);
2425         Offset += 8;
2426       }
2427
2428       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2429         // Now store the XMM (fp + vector) parameter registers.
2430         SmallVector<SDValue, 11> SaveXMMOps;
2431         SaveXMMOps.push_back(Chain);
2432
2433         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2434         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2435         SaveXMMOps.push_back(ALVal);
2436
2437         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2438                                FuncInfo->getRegSaveFrameIndex()));
2439         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2440                                FuncInfo->getVarArgsFPOffset()));
2441
2442         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2443           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2444                                        &X86::VR128RegClass);
2445           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2446           SaveXMMOps.push_back(Val);
2447         }
2448         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2449                                      MVT::Other, SaveXMMOps));
2450       }
2451
2452       if (!MemOps.empty())
2453         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2454     }
2455   }
2456
2457   // Some CCs need callee pop.
2458   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2459                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2460     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2461   } else {
2462     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2463     // If this is an sret function, the return should pop the hidden pointer.
2464     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2465         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2466         argsAreStructReturn(Ins) == StackStructReturn)
2467       FuncInfo->setBytesToPopOnReturn(4);
2468   }
2469
2470   if (!Is64Bit) {
2471     // RegSaveFrameIndex is X86-64 only.
2472     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2473     if (CallConv == CallingConv::X86_FastCall ||
2474         CallConv == CallingConv::X86_ThisCall)
2475       // fastcc functions can't have varargs.
2476       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2477   }
2478
2479   FuncInfo->setArgumentStackSize(StackSize);
2480
2481   return Chain;
2482 }
2483
2484 SDValue
2485 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2486                                     SDValue StackPtr, SDValue Arg,
2487                                     SDLoc dl, SelectionDAG &DAG,
2488                                     const CCValAssign &VA,
2489                                     ISD::ArgFlagsTy Flags) const {
2490   unsigned LocMemOffset = VA.getLocMemOffset();
2491   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2492   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2493   if (Flags.isByVal())
2494     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2495
2496   return DAG.getStore(Chain, dl, Arg, PtrOff,
2497                       MachinePointerInfo::getStack(LocMemOffset),
2498                       false, false, 0);
2499 }
2500
2501 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2502 /// optimization is performed and it is required.
2503 SDValue
2504 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2505                                            SDValue &OutRetAddr, SDValue Chain,
2506                                            bool IsTailCall, bool Is64Bit,
2507                                            int FPDiff, SDLoc dl) const {
2508   // Adjust the Return address stack slot.
2509   EVT VT = getPointerTy();
2510   OutRetAddr = getReturnAddressFrameIndex(DAG);
2511
2512   // Load the "old" Return address.
2513   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2514                            false, false, false, 0);
2515   return SDValue(OutRetAddr.getNode(), 1);
2516 }
2517
2518 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2519 /// optimization is performed and it is required (FPDiff!=0).
2520 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2521                                         SDValue Chain, SDValue RetAddrFrIdx,
2522                                         EVT PtrVT, unsigned SlotSize,
2523                                         int FPDiff, SDLoc dl) {
2524   // Store the return address to the appropriate stack slot.
2525   if (!FPDiff) return Chain;
2526   // Calculate the new stack slot for the return address.
2527   int NewReturnAddrFI =
2528     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2529                                          false);
2530   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2531   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2532                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2533                        false, false, 0);
2534   return Chain;
2535 }
2536
2537 SDValue
2538 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2539                              SmallVectorImpl<SDValue> &InVals) const {
2540   SelectionDAG &DAG                     = CLI.DAG;
2541   SDLoc &dl                             = CLI.DL;
2542   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2543   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2544   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2545   SDValue Chain                         = CLI.Chain;
2546   SDValue Callee                        = CLI.Callee;
2547   CallingConv::ID CallConv              = CLI.CallConv;
2548   bool &isTailCall                      = CLI.IsTailCall;
2549   bool isVarArg                         = CLI.IsVarArg;
2550
2551   MachineFunction &MF = DAG.getMachineFunction();
2552   bool Is64Bit        = Subtarget->is64Bit();
2553   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2554   StructReturnType SR = callIsStructReturn(Outs);
2555   bool IsSibcall      = false;
2556
2557   if (MF.getTarget().Options.DisableTailCalls)
2558     isTailCall = false;
2559
2560   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2561   if (IsMustTail) {
2562     // Force this to be a tail call.  The verifier rules are enough to ensure
2563     // that we can lower this successfully without moving the return address
2564     // around.
2565     isTailCall = true;
2566   } else if (isTailCall) {
2567     // Check if it's really possible to do a tail call.
2568     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2569                     isVarArg, SR != NotStructReturn,
2570                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2571                     Outs, OutVals, Ins, DAG);
2572
2573     // Sibcalls are automatically detected tailcalls which do not require
2574     // ABI changes.
2575     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2576       IsSibcall = true;
2577
2578     if (isTailCall)
2579       ++NumTailCalls;
2580   }
2581
2582   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2583          "Var args not supported with calling convention fastcc, ghc or hipe");
2584
2585   // Analyze operands of the call, assigning locations to each operand.
2586   SmallVector<CCValAssign, 16> ArgLocs;
2587   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2588                  ArgLocs, *DAG.getContext());
2589
2590   // Allocate shadow area for Win64
2591   if (IsWin64)
2592     CCInfo.AllocateStack(32, 8);
2593
2594   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2595
2596   // Get a count of how many bytes are to be pushed on the stack.
2597   unsigned NumBytes = CCInfo.getNextStackOffset();
2598   if (IsSibcall)
2599     // This is a sibcall. The memory operands are available in caller's
2600     // own caller's stack.
2601     NumBytes = 0;
2602   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2603            IsTailCallConvention(CallConv))
2604     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2605
2606   int FPDiff = 0;
2607   if (isTailCall && !IsSibcall && !IsMustTail) {
2608     // Lower arguments at fp - stackoffset + fpdiff.
2609     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2610     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2611
2612     FPDiff = NumBytesCallerPushed - NumBytes;
2613
2614     // Set the delta of movement of the returnaddr stackslot.
2615     // But only set if delta is greater than previous delta.
2616     if (FPDiff < X86Info->getTCReturnAddrDelta())
2617       X86Info->setTCReturnAddrDelta(FPDiff);
2618   }
2619
2620   unsigned NumBytesToPush = NumBytes;
2621   unsigned NumBytesToPop = NumBytes;
2622
2623   // If we have an inalloca argument, all stack space has already been allocated
2624   // for us and be right at the top of the stack.  We don't support multiple
2625   // arguments passed in memory when using inalloca.
2626   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2627     NumBytesToPush = 0;
2628     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2629            "an inalloca argument must be the only memory argument");
2630   }
2631
2632   if (!IsSibcall)
2633     Chain = DAG.getCALLSEQ_START(
2634         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2635
2636   SDValue RetAddrFrIdx;
2637   // Load return address for tail calls.
2638   if (isTailCall && FPDiff)
2639     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2640                                     Is64Bit, FPDiff, dl);
2641
2642   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2643   SmallVector<SDValue, 8> MemOpChains;
2644   SDValue StackPtr;
2645
2646   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2647   // of tail call optimization arguments are handle later.
2648   const X86RegisterInfo *RegInfo =
2649     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2650   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2651     // Skip inalloca arguments, they have already been written.
2652     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2653     if (Flags.isInAlloca())
2654       continue;
2655
2656     CCValAssign &VA = ArgLocs[i];
2657     EVT RegVT = VA.getLocVT();
2658     SDValue Arg = OutVals[i];
2659     bool isByVal = Flags.isByVal();
2660
2661     // Promote the value if needed.
2662     switch (VA.getLocInfo()) {
2663     default: llvm_unreachable("Unknown loc info!");
2664     case CCValAssign::Full: break;
2665     case CCValAssign::SExt:
2666       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2667       break;
2668     case CCValAssign::ZExt:
2669       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2670       break;
2671     case CCValAssign::AExt:
2672       if (RegVT.is128BitVector()) {
2673         // Special case: passing MMX values in XMM registers.
2674         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2675         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2676         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2677       } else
2678         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2679       break;
2680     case CCValAssign::BCvt:
2681       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2682       break;
2683     case CCValAssign::Indirect: {
2684       // Store the argument.
2685       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2686       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2687       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2688                            MachinePointerInfo::getFixedStack(FI),
2689                            false, false, 0);
2690       Arg = SpillSlot;
2691       break;
2692     }
2693     }
2694
2695     if (VA.isRegLoc()) {
2696       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2697       if (isVarArg && IsWin64) {
2698         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2699         // shadow reg if callee is a varargs function.
2700         unsigned ShadowReg = 0;
2701         switch (VA.getLocReg()) {
2702         case X86::XMM0: ShadowReg = X86::RCX; break;
2703         case X86::XMM1: ShadowReg = X86::RDX; break;
2704         case X86::XMM2: ShadowReg = X86::R8; break;
2705         case X86::XMM3: ShadowReg = X86::R9; break;
2706         }
2707         if (ShadowReg)
2708           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2709       }
2710     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2711       assert(VA.isMemLoc());
2712       if (!StackPtr.getNode())
2713         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2714                                       getPointerTy());
2715       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2716                                              dl, DAG, VA, Flags));
2717     }
2718   }
2719
2720   if (!MemOpChains.empty())
2721     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2722
2723   if (Subtarget->isPICStyleGOT()) {
2724     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2725     // GOT pointer.
2726     if (!isTailCall) {
2727       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2728                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2729     } else {
2730       // If we are tail calling and generating PIC/GOT style code load the
2731       // address of the callee into ECX. The value in ecx is used as target of
2732       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2733       // for tail calls on PIC/GOT architectures. Normally we would just put the
2734       // address of GOT into ebx and then call target@PLT. But for tail calls
2735       // ebx would be restored (since ebx is callee saved) before jumping to the
2736       // target@PLT.
2737
2738       // Note: The actual moving to ECX is done further down.
2739       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2740       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2741           !G->getGlobal()->hasProtectedVisibility())
2742         Callee = LowerGlobalAddress(Callee, DAG);
2743       else if (isa<ExternalSymbolSDNode>(Callee))
2744         Callee = LowerExternalSymbol(Callee, DAG);
2745     }
2746   }
2747
2748   if (Is64Bit && isVarArg && !IsWin64) {
2749     // From AMD64 ABI document:
2750     // For calls that may call functions that use varargs or stdargs
2751     // (prototype-less calls or calls to functions containing ellipsis (...) in
2752     // the declaration) %al is used as hidden argument to specify the number
2753     // of SSE registers used. The contents of %al do not need to match exactly
2754     // the number of registers, but must be an ubound on the number of SSE
2755     // registers used and is in the range 0 - 8 inclusive.
2756
2757     // Count the number of XMM registers allocated.
2758     static const MCPhysReg XMMArgRegs[] = {
2759       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2760       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2761     };
2762     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2763     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2764            && "SSE registers cannot be used when SSE is disabled");
2765
2766     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2767                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2768   }
2769
2770   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2771   // don't need this because the eligibility check rejects calls that require
2772   // shuffling arguments passed in memory.
2773   if (!IsSibcall && isTailCall) {
2774     // Force all the incoming stack arguments to be loaded from the stack
2775     // before any new outgoing arguments are stored to the stack, because the
2776     // outgoing stack slots may alias the incoming argument stack slots, and
2777     // the alias isn't otherwise explicit. This is slightly more conservative
2778     // than necessary, because it means that each store effectively depends
2779     // on every argument instead of just those arguments it would clobber.
2780     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2781
2782     SmallVector<SDValue, 8> MemOpChains2;
2783     SDValue FIN;
2784     int FI = 0;
2785     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2786       CCValAssign &VA = ArgLocs[i];
2787       if (VA.isRegLoc())
2788         continue;
2789       assert(VA.isMemLoc());
2790       SDValue Arg = OutVals[i];
2791       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2792       // Skip inalloca arguments.  They don't require any work.
2793       if (Flags.isInAlloca())
2794         continue;
2795       // Create frame index.
2796       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2797       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2798       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2799       FIN = DAG.getFrameIndex(FI, getPointerTy());
2800
2801       if (Flags.isByVal()) {
2802         // Copy relative to framepointer.
2803         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2804         if (!StackPtr.getNode())
2805           StackPtr = DAG.getCopyFromReg(Chain, dl,
2806                                         RegInfo->getStackRegister(),
2807                                         getPointerTy());
2808         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2809
2810         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2811                                                          ArgChain,
2812                                                          Flags, DAG, dl));
2813       } else {
2814         // Store relative to framepointer.
2815         MemOpChains2.push_back(
2816           DAG.getStore(ArgChain, dl, Arg, FIN,
2817                        MachinePointerInfo::getFixedStack(FI),
2818                        false, false, 0));
2819       }
2820     }
2821
2822     if (!MemOpChains2.empty())
2823       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2824
2825     // Store the return address to the appropriate stack slot.
2826     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2827                                      getPointerTy(), RegInfo->getSlotSize(),
2828                                      FPDiff, dl);
2829   }
2830
2831   // Build a sequence of copy-to-reg nodes chained together with token chain
2832   // and flag operands which copy the outgoing args into registers.
2833   SDValue InFlag;
2834   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2835     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2836                              RegsToPass[i].second, InFlag);
2837     InFlag = Chain.getValue(1);
2838   }
2839
2840   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2841     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2842     // In the 64-bit large code model, we have to make all calls
2843     // through a register, since the call instruction's 32-bit
2844     // pc-relative offset may not be large enough to hold the whole
2845     // address.
2846   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2847     // If the callee is a GlobalAddress node (quite common, every direct call
2848     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2849     // it.
2850
2851     // We should use extra load for direct calls to dllimported functions in
2852     // non-JIT mode.
2853     const GlobalValue *GV = G->getGlobal();
2854     if (!GV->hasDLLImportStorageClass()) {
2855       unsigned char OpFlags = 0;
2856       bool ExtraLoad = false;
2857       unsigned WrapperKind = ISD::DELETED_NODE;
2858
2859       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2860       // external symbols most go through the PLT in PIC mode.  If the symbol
2861       // has hidden or protected visibility, or if it is static or local, then
2862       // we don't need to use the PLT - we can directly call it.
2863       if (Subtarget->isTargetELF() &&
2864           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2865           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2866         OpFlags = X86II::MO_PLT;
2867       } else if (Subtarget->isPICStyleStubAny() &&
2868                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2869                  (!Subtarget->getTargetTriple().isMacOSX() ||
2870                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2871         // PC-relative references to external symbols should go through $stub,
2872         // unless we're building with the leopard linker or later, which
2873         // automatically synthesizes these stubs.
2874         OpFlags = X86II::MO_DARWIN_STUB;
2875       } else if (Subtarget->isPICStyleRIPRel() &&
2876                  isa<Function>(GV) &&
2877                  cast<Function>(GV)->getAttributes().
2878                    hasAttribute(AttributeSet::FunctionIndex,
2879                                 Attribute::NonLazyBind)) {
2880         // If the function is marked as non-lazy, generate an indirect call
2881         // which loads from the GOT directly. This avoids runtime overhead
2882         // at the cost of eager binding (and one extra byte of encoding).
2883         OpFlags = X86II::MO_GOTPCREL;
2884         WrapperKind = X86ISD::WrapperRIP;
2885         ExtraLoad = true;
2886       }
2887
2888       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2889                                           G->getOffset(), OpFlags);
2890
2891       // Add a wrapper if needed.
2892       if (WrapperKind != ISD::DELETED_NODE)
2893         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2894       // Add extra indirection if needed.
2895       if (ExtraLoad)
2896         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2897                              MachinePointerInfo::getGOT(),
2898                              false, false, false, 0);
2899     }
2900   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2901     unsigned char OpFlags = 0;
2902
2903     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2904     // external symbols should go through the PLT.
2905     if (Subtarget->isTargetELF() &&
2906         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2907       OpFlags = X86II::MO_PLT;
2908     } else if (Subtarget->isPICStyleStubAny() &&
2909                (!Subtarget->getTargetTriple().isMacOSX() ||
2910                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2911       // PC-relative references to external symbols should go through $stub,
2912       // unless we're building with the leopard linker or later, which
2913       // automatically synthesizes these stubs.
2914       OpFlags = X86II::MO_DARWIN_STUB;
2915     }
2916
2917     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2918                                          OpFlags);
2919   }
2920
2921   // Returns a chain & a flag for retval copy to use.
2922   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2923   SmallVector<SDValue, 8> Ops;
2924
2925   if (!IsSibcall && isTailCall) {
2926     Chain = DAG.getCALLSEQ_END(Chain,
2927                                DAG.getIntPtrConstant(NumBytesToPop, true),
2928                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2929     InFlag = Chain.getValue(1);
2930   }
2931
2932   Ops.push_back(Chain);
2933   Ops.push_back(Callee);
2934
2935   if (isTailCall)
2936     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2937
2938   // Add argument registers to the end of the list so that they are known live
2939   // into the call.
2940   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2941     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2942                                   RegsToPass[i].second.getValueType()));
2943
2944   // Add a register mask operand representing the call-preserved registers.
2945   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2946   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2947   assert(Mask && "Missing call preserved mask for calling convention");
2948   Ops.push_back(DAG.getRegisterMask(Mask));
2949
2950   if (InFlag.getNode())
2951     Ops.push_back(InFlag);
2952
2953   if (isTailCall) {
2954     // We used to do:
2955     //// If this is the first return lowered for this function, add the regs
2956     //// to the liveout set for the function.
2957     // This isn't right, although it's probably harmless on x86; liveouts
2958     // should be computed from returns not tail calls.  Consider a void
2959     // function making a tail call to a function returning int.
2960     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2961   }
2962
2963   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2964   InFlag = Chain.getValue(1);
2965
2966   // Create the CALLSEQ_END node.
2967   unsigned NumBytesForCalleeToPop;
2968   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2969                        getTargetMachine().Options.GuaranteedTailCallOpt))
2970     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2971   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2972            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2973            SR == StackStructReturn)
2974     // If this is a call to a struct-return function, the callee
2975     // pops the hidden struct pointer, so we have to push it back.
2976     // This is common for Darwin/X86, Linux & Mingw32 targets.
2977     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2978     NumBytesForCalleeToPop = 4;
2979   else
2980     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2981
2982   // Returns a flag for retval copy to use.
2983   if (!IsSibcall) {
2984     Chain = DAG.getCALLSEQ_END(Chain,
2985                                DAG.getIntPtrConstant(NumBytesToPop, true),
2986                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2987                                                      true),
2988                                InFlag, dl);
2989     InFlag = Chain.getValue(1);
2990   }
2991
2992   // Handle result values, copying them out of physregs into vregs that we
2993   // return.
2994   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2995                          Ins, dl, DAG, InVals);
2996 }
2997
2998 //===----------------------------------------------------------------------===//
2999 //                Fast Calling Convention (tail call) implementation
3000 //===----------------------------------------------------------------------===//
3001
3002 //  Like std call, callee cleans arguments, convention except that ECX is
3003 //  reserved for storing the tail called function address. Only 2 registers are
3004 //  free for argument passing (inreg). Tail call optimization is performed
3005 //  provided:
3006 //                * tailcallopt is enabled
3007 //                * caller/callee are fastcc
3008 //  On X86_64 architecture with GOT-style position independent code only local
3009 //  (within module) calls are supported at the moment.
3010 //  To keep the stack aligned according to platform abi the function
3011 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3012 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3013 //  If a tail called function callee has more arguments than the caller the
3014 //  caller needs to make sure that there is room to move the RETADDR to. This is
3015 //  achieved by reserving an area the size of the argument delta right after the
3016 //  original REtADDR, but before the saved framepointer or the spilled registers
3017 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3018 //  stack layout:
3019 //    arg1
3020 //    arg2
3021 //    RETADDR
3022 //    [ new RETADDR
3023 //      move area ]
3024 //    (possible EBP)
3025 //    ESI
3026 //    EDI
3027 //    local1 ..
3028
3029 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3030 /// for a 16 byte align requirement.
3031 unsigned
3032 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3033                                                SelectionDAG& DAG) const {
3034   MachineFunction &MF = DAG.getMachineFunction();
3035   const TargetMachine &TM = MF.getTarget();
3036   const X86RegisterInfo *RegInfo =
3037     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3038   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3039   unsigned StackAlignment = TFI.getStackAlignment();
3040   uint64_t AlignMask = StackAlignment - 1;
3041   int64_t Offset = StackSize;
3042   unsigned SlotSize = RegInfo->getSlotSize();
3043   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3044     // Number smaller than 12 so just add the difference.
3045     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3046   } else {
3047     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3048     Offset = ((~AlignMask) & Offset) + StackAlignment +
3049       (StackAlignment-SlotSize);
3050   }
3051   return Offset;
3052 }
3053
3054 /// MatchingStackOffset - Return true if the given stack call argument is
3055 /// already available in the same position (relatively) of the caller's
3056 /// incoming argument stack.
3057 static
3058 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3059                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3060                          const X86InstrInfo *TII) {
3061   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3062   int FI = INT_MAX;
3063   if (Arg.getOpcode() == ISD::CopyFromReg) {
3064     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3065     if (!TargetRegisterInfo::isVirtualRegister(VR))
3066       return false;
3067     MachineInstr *Def = MRI->getVRegDef(VR);
3068     if (!Def)
3069       return false;
3070     if (!Flags.isByVal()) {
3071       if (!TII->isLoadFromStackSlot(Def, FI))
3072         return false;
3073     } else {
3074       unsigned Opcode = Def->getOpcode();
3075       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3076           Def->getOperand(1).isFI()) {
3077         FI = Def->getOperand(1).getIndex();
3078         Bytes = Flags.getByValSize();
3079       } else
3080         return false;
3081     }
3082   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3083     if (Flags.isByVal())
3084       // ByVal argument is passed in as a pointer but it's now being
3085       // dereferenced. e.g.
3086       // define @foo(%struct.X* %A) {
3087       //   tail call @bar(%struct.X* byval %A)
3088       // }
3089       return false;
3090     SDValue Ptr = Ld->getBasePtr();
3091     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3092     if (!FINode)
3093       return false;
3094     FI = FINode->getIndex();
3095   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3096     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3097     FI = FINode->getIndex();
3098     Bytes = Flags.getByValSize();
3099   } else
3100     return false;
3101
3102   assert(FI != INT_MAX);
3103   if (!MFI->isFixedObjectIndex(FI))
3104     return false;
3105   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3106 }
3107
3108 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3109 /// for tail call optimization. Targets which want to do tail call
3110 /// optimization should implement this function.
3111 bool
3112 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3113                                                      CallingConv::ID CalleeCC,
3114                                                      bool isVarArg,
3115                                                      bool isCalleeStructRet,
3116                                                      bool isCallerStructRet,
3117                                                      Type *RetTy,
3118                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3119                                     const SmallVectorImpl<SDValue> &OutVals,
3120                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3121                                                      SelectionDAG &DAG) const {
3122   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3123     return false;
3124
3125   // If -tailcallopt is specified, make fastcc functions tail-callable.
3126   const MachineFunction &MF = DAG.getMachineFunction();
3127   const Function *CallerF = MF.getFunction();
3128
3129   // If the function return type is x86_fp80 and the callee return type is not,
3130   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3131   // perform a tailcall optimization here.
3132   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3133     return false;
3134
3135   CallingConv::ID CallerCC = CallerF->getCallingConv();
3136   bool CCMatch = CallerCC == CalleeCC;
3137   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3138   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3139
3140   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3141     if (IsTailCallConvention(CalleeCC) && CCMatch)
3142       return true;
3143     return false;
3144   }
3145
3146   // Look for obvious safe cases to perform tail call optimization that do not
3147   // require ABI changes. This is what gcc calls sibcall.
3148
3149   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3150   // emit a special epilogue.
3151   const X86RegisterInfo *RegInfo =
3152     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3153   if (RegInfo->needsStackRealignment(MF))
3154     return false;
3155
3156   // Also avoid sibcall optimization if either caller or callee uses struct
3157   // return semantics.
3158   if (isCalleeStructRet || isCallerStructRet)
3159     return false;
3160
3161   // An stdcall/thiscall caller is expected to clean up its arguments; the
3162   // callee isn't going to do that.
3163   // FIXME: this is more restrictive than needed. We could produce a tailcall
3164   // when the stack adjustment matches. For example, with a thiscall that takes
3165   // only one argument.
3166   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3167                    CallerCC == CallingConv::X86_ThisCall))
3168     return false;
3169
3170   // Do not sibcall optimize vararg calls unless all arguments are passed via
3171   // registers.
3172   if (isVarArg && !Outs.empty()) {
3173
3174     // Optimizing for varargs on Win64 is unlikely to be safe without
3175     // additional testing.
3176     if (IsCalleeWin64 || IsCallerWin64)
3177       return false;
3178
3179     SmallVector<CCValAssign, 16> ArgLocs;
3180     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3181                    getTargetMachine(), ArgLocs, *DAG.getContext());
3182
3183     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3184     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3185       if (!ArgLocs[i].isRegLoc())
3186         return false;
3187   }
3188
3189   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3190   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3191   // this into a sibcall.
3192   bool Unused = false;
3193   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3194     if (!Ins[i].Used) {
3195       Unused = true;
3196       break;
3197     }
3198   }
3199   if (Unused) {
3200     SmallVector<CCValAssign, 16> RVLocs;
3201     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3202                    getTargetMachine(), RVLocs, *DAG.getContext());
3203     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3204     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3205       CCValAssign &VA = RVLocs[i];
3206       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3207         return false;
3208     }
3209   }
3210
3211   // If the calling conventions do not match, then we'd better make sure the
3212   // results are returned in the same way as what the caller expects.
3213   if (!CCMatch) {
3214     SmallVector<CCValAssign, 16> RVLocs1;
3215     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3216                     getTargetMachine(), RVLocs1, *DAG.getContext());
3217     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3218
3219     SmallVector<CCValAssign, 16> RVLocs2;
3220     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3221                     getTargetMachine(), RVLocs2, *DAG.getContext());
3222     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3223
3224     if (RVLocs1.size() != RVLocs2.size())
3225       return false;
3226     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3227       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3228         return false;
3229       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3230         return false;
3231       if (RVLocs1[i].isRegLoc()) {
3232         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3233           return false;
3234       } else {
3235         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3236           return false;
3237       }
3238     }
3239   }
3240
3241   // If the callee takes no arguments then go on to check the results of the
3242   // call.
3243   if (!Outs.empty()) {
3244     // Check if stack adjustment is needed. For now, do not do this if any
3245     // argument is passed on the stack.
3246     SmallVector<CCValAssign, 16> ArgLocs;
3247     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3248                    getTargetMachine(), ArgLocs, *DAG.getContext());
3249
3250     // Allocate shadow area for Win64
3251     if (IsCalleeWin64)
3252       CCInfo.AllocateStack(32, 8);
3253
3254     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3255     if (CCInfo.getNextStackOffset()) {
3256       MachineFunction &MF = DAG.getMachineFunction();
3257       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3258         return false;
3259
3260       // Check if the arguments are already laid out in the right way as
3261       // the caller's fixed stack objects.
3262       MachineFrameInfo *MFI = MF.getFrameInfo();
3263       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3264       const X86InstrInfo *TII =
3265         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3266       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3267         CCValAssign &VA = ArgLocs[i];
3268         SDValue Arg = OutVals[i];
3269         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3270         if (VA.getLocInfo() == CCValAssign::Indirect)
3271           return false;
3272         if (!VA.isRegLoc()) {
3273           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3274                                    MFI, MRI, TII))
3275             return false;
3276         }
3277       }
3278     }
3279
3280     // If the tailcall address may be in a register, then make sure it's
3281     // possible to register allocate for it. In 32-bit, the call address can
3282     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3283     // callee-saved registers are restored. These happen to be the same
3284     // registers used to pass 'inreg' arguments so watch out for those.
3285     if (!Subtarget->is64Bit() &&
3286         ((!isa<GlobalAddressSDNode>(Callee) &&
3287           !isa<ExternalSymbolSDNode>(Callee)) ||
3288          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3289       unsigned NumInRegs = 0;
3290       // In PIC we need an extra register to formulate the address computation
3291       // for the callee.
3292       unsigned MaxInRegs =
3293           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3294
3295       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3296         CCValAssign &VA = ArgLocs[i];
3297         if (!VA.isRegLoc())
3298           continue;
3299         unsigned Reg = VA.getLocReg();
3300         switch (Reg) {
3301         default: break;
3302         case X86::EAX: case X86::EDX: case X86::ECX:
3303           if (++NumInRegs == MaxInRegs)
3304             return false;
3305           break;
3306         }
3307       }
3308     }
3309   }
3310
3311   return true;
3312 }
3313
3314 FastISel *
3315 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3316                                   const TargetLibraryInfo *libInfo) const {
3317   return X86::createFastISel(funcInfo, libInfo);
3318 }
3319
3320 //===----------------------------------------------------------------------===//
3321 //                           Other Lowering Hooks
3322 //===----------------------------------------------------------------------===//
3323
3324 static bool MayFoldLoad(SDValue Op) {
3325   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3326 }
3327
3328 static bool MayFoldIntoStore(SDValue Op) {
3329   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3330 }
3331
3332 static bool isTargetShuffle(unsigned Opcode) {
3333   switch(Opcode) {
3334   default: return false;
3335   case X86ISD::PSHUFD:
3336   case X86ISD::PSHUFHW:
3337   case X86ISD::PSHUFLW:
3338   case X86ISD::SHUFP:
3339   case X86ISD::PALIGNR:
3340   case X86ISD::MOVLHPS:
3341   case X86ISD::MOVLHPD:
3342   case X86ISD::MOVHLPS:
3343   case X86ISD::MOVLPS:
3344   case X86ISD::MOVLPD:
3345   case X86ISD::MOVSHDUP:
3346   case X86ISD::MOVSLDUP:
3347   case X86ISD::MOVDDUP:
3348   case X86ISD::MOVSS:
3349   case X86ISD::MOVSD:
3350   case X86ISD::UNPCKL:
3351   case X86ISD::UNPCKH:
3352   case X86ISD::VPERMILP:
3353   case X86ISD::VPERM2X128:
3354   case X86ISD::VPERMI:
3355     return true;
3356   }
3357 }
3358
3359 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3360                                     SDValue V1, SelectionDAG &DAG) {
3361   switch(Opc) {
3362   default: llvm_unreachable("Unknown x86 shuffle node");
3363   case X86ISD::MOVSHDUP:
3364   case X86ISD::MOVSLDUP:
3365   case X86ISD::MOVDDUP:
3366     return DAG.getNode(Opc, dl, VT, V1);
3367   }
3368 }
3369
3370 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3371                                     SDValue V1, unsigned TargetMask,
3372                                     SelectionDAG &DAG) {
3373   switch(Opc) {
3374   default: llvm_unreachable("Unknown x86 shuffle node");
3375   case X86ISD::PSHUFD:
3376   case X86ISD::PSHUFHW:
3377   case X86ISD::PSHUFLW:
3378   case X86ISD::VPERMILP:
3379   case X86ISD::VPERMI:
3380     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3381   }
3382 }
3383
3384 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3385                                     SDValue V1, SDValue V2, unsigned TargetMask,
3386                                     SelectionDAG &DAG) {
3387   switch(Opc) {
3388   default: llvm_unreachable("Unknown x86 shuffle node");
3389   case X86ISD::PALIGNR:
3390   case X86ISD::SHUFP:
3391   case X86ISD::VPERM2X128:
3392     return DAG.getNode(Opc, dl, VT, V1, V2,
3393                        DAG.getConstant(TargetMask, MVT::i8));
3394   }
3395 }
3396
3397 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3398                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3399   switch(Opc) {
3400   default: llvm_unreachable("Unknown x86 shuffle node");
3401   case X86ISD::MOVLHPS:
3402   case X86ISD::MOVLHPD:
3403   case X86ISD::MOVHLPS:
3404   case X86ISD::MOVLPS:
3405   case X86ISD::MOVLPD:
3406   case X86ISD::MOVSS:
3407   case X86ISD::MOVSD:
3408   case X86ISD::UNPCKL:
3409   case X86ISD::UNPCKH:
3410     return DAG.getNode(Opc, dl, VT, V1, V2);
3411   }
3412 }
3413
3414 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3415   MachineFunction &MF = DAG.getMachineFunction();
3416   const X86RegisterInfo *RegInfo =
3417     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3418   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3419   int ReturnAddrIndex = FuncInfo->getRAIndex();
3420
3421   if (ReturnAddrIndex == 0) {
3422     // Set up a frame object for the return address.
3423     unsigned SlotSize = RegInfo->getSlotSize();
3424     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3425                                                            -(int64_t)SlotSize,
3426                                                            false);
3427     FuncInfo->setRAIndex(ReturnAddrIndex);
3428   }
3429
3430   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3431 }
3432
3433 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3434                                        bool hasSymbolicDisplacement) {
3435   // Offset should fit into 32 bit immediate field.
3436   if (!isInt<32>(Offset))
3437     return false;
3438
3439   // If we don't have a symbolic displacement - we don't have any extra
3440   // restrictions.
3441   if (!hasSymbolicDisplacement)
3442     return true;
3443
3444   // FIXME: Some tweaks might be needed for medium code model.
3445   if (M != CodeModel::Small && M != CodeModel::Kernel)
3446     return false;
3447
3448   // For small code model we assume that latest object is 16MB before end of 31
3449   // bits boundary. We may also accept pretty large negative constants knowing
3450   // that all objects are in the positive half of address space.
3451   if (M == CodeModel::Small && Offset < 16*1024*1024)
3452     return true;
3453
3454   // For kernel code model we know that all object resist in the negative half
3455   // of 32bits address space. We may not accept negative offsets, since they may
3456   // be just off and we may accept pretty large positive ones.
3457   if (M == CodeModel::Kernel && Offset > 0)
3458     return true;
3459
3460   return false;
3461 }
3462
3463 /// isCalleePop - Determines whether the callee is required to pop its
3464 /// own arguments. Callee pop is necessary to support tail calls.
3465 bool X86::isCalleePop(CallingConv::ID CallingConv,
3466                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3467   if (IsVarArg)
3468     return false;
3469
3470   switch (CallingConv) {
3471   default:
3472     return false;
3473   case CallingConv::X86_StdCall:
3474     return !is64Bit;
3475   case CallingConv::X86_FastCall:
3476     return !is64Bit;
3477   case CallingConv::X86_ThisCall:
3478     return !is64Bit;
3479   case CallingConv::Fast:
3480     return TailCallOpt;
3481   case CallingConv::GHC:
3482     return TailCallOpt;
3483   case CallingConv::HiPE:
3484     return TailCallOpt;
3485   }
3486 }
3487
3488 /// \brief Return true if the condition is an unsigned comparison operation.
3489 static bool isX86CCUnsigned(unsigned X86CC) {
3490   switch (X86CC) {
3491   default: llvm_unreachable("Invalid integer condition!");
3492   case X86::COND_E:     return true;
3493   case X86::COND_G:     return false;
3494   case X86::COND_GE:    return false;
3495   case X86::COND_L:     return false;
3496   case X86::COND_LE:    return false;
3497   case X86::COND_NE:    return true;
3498   case X86::COND_B:     return true;
3499   case X86::COND_A:     return true;
3500   case X86::COND_BE:    return true;
3501   case X86::COND_AE:    return true;
3502   }
3503   llvm_unreachable("covered switch fell through?!");
3504 }
3505
3506 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3507 /// specific condition code, returning the condition code and the LHS/RHS of the
3508 /// comparison to make.
3509 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3510                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3511   if (!isFP) {
3512     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3513       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3514         // X > -1   -> X == 0, jump !sign.
3515         RHS = DAG.getConstant(0, RHS.getValueType());
3516         return X86::COND_NS;
3517       }
3518       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3519         // X < 0   -> X == 0, jump on sign.
3520         return X86::COND_S;
3521       }
3522       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3523         // X < 1   -> X <= 0
3524         RHS = DAG.getConstant(0, RHS.getValueType());
3525         return X86::COND_LE;
3526       }
3527     }
3528
3529     switch (SetCCOpcode) {
3530     default: llvm_unreachable("Invalid integer condition!");
3531     case ISD::SETEQ:  return X86::COND_E;
3532     case ISD::SETGT:  return X86::COND_G;
3533     case ISD::SETGE:  return X86::COND_GE;
3534     case ISD::SETLT:  return X86::COND_L;
3535     case ISD::SETLE:  return X86::COND_LE;
3536     case ISD::SETNE:  return X86::COND_NE;
3537     case ISD::SETULT: return X86::COND_B;
3538     case ISD::SETUGT: return X86::COND_A;
3539     case ISD::SETULE: return X86::COND_BE;
3540     case ISD::SETUGE: return X86::COND_AE;
3541     }
3542   }
3543
3544   // First determine if it is required or is profitable to flip the operands.
3545
3546   // If LHS is a foldable load, but RHS is not, flip the condition.
3547   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3548       !ISD::isNON_EXTLoad(RHS.getNode())) {
3549     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3550     std::swap(LHS, RHS);
3551   }
3552
3553   switch (SetCCOpcode) {
3554   default: break;
3555   case ISD::SETOLT:
3556   case ISD::SETOLE:
3557   case ISD::SETUGT:
3558   case ISD::SETUGE:
3559     std::swap(LHS, RHS);
3560     break;
3561   }
3562
3563   // On a floating point condition, the flags are set as follows:
3564   // ZF  PF  CF   op
3565   //  0 | 0 | 0 | X > Y
3566   //  0 | 0 | 1 | X < Y
3567   //  1 | 0 | 0 | X == Y
3568   //  1 | 1 | 1 | unordered
3569   switch (SetCCOpcode) {
3570   default: llvm_unreachable("Condcode should be pre-legalized away");
3571   case ISD::SETUEQ:
3572   case ISD::SETEQ:   return X86::COND_E;
3573   case ISD::SETOLT:              // flipped
3574   case ISD::SETOGT:
3575   case ISD::SETGT:   return X86::COND_A;
3576   case ISD::SETOLE:              // flipped
3577   case ISD::SETOGE:
3578   case ISD::SETGE:   return X86::COND_AE;
3579   case ISD::SETUGT:              // flipped
3580   case ISD::SETULT:
3581   case ISD::SETLT:   return X86::COND_B;
3582   case ISD::SETUGE:              // flipped
3583   case ISD::SETULE:
3584   case ISD::SETLE:   return X86::COND_BE;
3585   case ISD::SETONE:
3586   case ISD::SETNE:   return X86::COND_NE;
3587   case ISD::SETUO:   return X86::COND_P;
3588   case ISD::SETO:    return X86::COND_NP;
3589   case ISD::SETOEQ:
3590   case ISD::SETUNE:  return X86::COND_INVALID;
3591   }
3592 }
3593
3594 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3595 /// code. Current x86 isa includes the following FP cmov instructions:
3596 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3597 static bool hasFPCMov(unsigned X86CC) {
3598   switch (X86CC) {
3599   default:
3600     return false;
3601   case X86::COND_B:
3602   case X86::COND_BE:
3603   case X86::COND_E:
3604   case X86::COND_P:
3605   case X86::COND_A:
3606   case X86::COND_AE:
3607   case X86::COND_NE:
3608   case X86::COND_NP:
3609     return true;
3610   }
3611 }
3612
3613 /// isFPImmLegal - Returns true if the target can instruction select the
3614 /// specified FP immediate natively. If false, the legalizer will
3615 /// materialize the FP immediate as a load from a constant pool.
3616 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3617   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3618     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3619       return true;
3620   }
3621   return false;
3622 }
3623
3624 /// \brief Returns true if it is beneficial to convert a load of a constant
3625 /// to just the constant itself.
3626 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3627                                                           Type *Ty) const {
3628   assert(Ty->isIntegerTy());
3629
3630   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3631   if (BitSize == 0 || BitSize > 64)
3632     return false;
3633   return true;
3634 }
3635
3636 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3637 /// the specified range (L, H].
3638 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3639   return (Val < 0) || (Val >= Low && Val < Hi);
3640 }
3641
3642 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3643 /// specified value.
3644 static bool isUndefOrEqual(int Val, int CmpVal) {
3645   return (Val < 0 || Val == CmpVal);
3646 }
3647
3648 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3649 /// from position Pos and ending in Pos+Size, falls within the specified
3650 /// sequential range (L, L+Pos]. or is undef.
3651 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3652                                        unsigned Pos, unsigned Size, int Low) {
3653   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3654     if (!isUndefOrEqual(Mask[i], Low))
3655       return false;
3656   return true;
3657 }
3658
3659 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3660 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3661 /// the second operand.
3662 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3663   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3664     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3665   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3666     return (Mask[0] < 2 && Mask[1] < 2);
3667   return false;
3668 }
3669
3670 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3671 /// is suitable for input to PSHUFHW.
3672 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3673   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3674     return false;
3675
3676   // Lower quadword copied in order or undef.
3677   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3678     return false;
3679
3680   // Upper quadword shuffled.
3681   for (unsigned i = 4; i != 8; ++i)
3682     if (!isUndefOrInRange(Mask[i], 4, 8))
3683       return false;
3684
3685   if (VT == MVT::v16i16) {
3686     // Lower quadword copied in order or undef.
3687     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3688       return false;
3689
3690     // Upper quadword shuffled.
3691     for (unsigned i = 12; i != 16; ++i)
3692       if (!isUndefOrInRange(Mask[i], 12, 16))
3693         return false;
3694   }
3695
3696   return true;
3697 }
3698
3699 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3700 /// is suitable for input to PSHUFLW.
3701 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3702   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3703     return false;
3704
3705   // Upper quadword copied in order.
3706   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3707     return false;
3708
3709   // Lower quadword shuffled.
3710   for (unsigned i = 0; i != 4; ++i)
3711     if (!isUndefOrInRange(Mask[i], 0, 4))
3712       return false;
3713
3714   if (VT == MVT::v16i16) {
3715     // Upper quadword copied in order.
3716     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3717       return false;
3718
3719     // Lower quadword shuffled.
3720     for (unsigned i = 8; i != 12; ++i)
3721       if (!isUndefOrInRange(Mask[i], 8, 12))
3722         return false;
3723   }
3724
3725   return true;
3726 }
3727
3728 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3729 /// is suitable for input to PALIGNR.
3730 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3731                           const X86Subtarget *Subtarget) {
3732   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3733       (VT.is256BitVector() && !Subtarget->hasInt256()))
3734     return false;
3735
3736   unsigned NumElts = VT.getVectorNumElements();
3737   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3738   unsigned NumLaneElts = NumElts/NumLanes;
3739
3740   // Do not handle 64-bit element shuffles with palignr.
3741   if (NumLaneElts == 2)
3742     return false;
3743
3744   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3745     unsigned i;
3746     for (i = 0; i != NumLaneElts; ++i) {
3747       if (Mask[i+l] >= 0)
3748         break;
3749     }
3750
3751     // Lane is all undef, go to next lane
3752     if (i == NumLaneElts)
3753       continue;
3754
3755     int Start = Mask[i+l];
3756
3757     // Make sure its in this lane in one of the sources
3758     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3759         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3760       return false;
3761
3762     // If not lane 0, then we must match lane 0
3763     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3764       return false;
3765
3766     // Correct second source to be contiguous with first source
3767     if (Start >= (int)NumElts)
3768       Start -= NumElts - NumLaneElts;
3769
3770     // Make sure we're shifting in the right direction.
3771     if (Start <= (int)(i+l))
3772       return false;
3773
3774     Start -= i;
3775
3776     // Check the rest of the elements to see if they are consecutive.
3777     for (++i; i != NumLaneElts; ++i) {
3778       int Idx = Mask[i+l];
3779
3780       // Make sure its in this lane
3781       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3782           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3783         return false;
3784
3785       // If not lane 0, then we must match lane 0
3786       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3787         return false;
3788
3789       if (Idx >= (int)NumElts)
3790         Idx -= NumElts - NumLaneElts;
3791
3792       if (!isUndefOrEqual(Idx, Start+i))
3793         return false;
3794
3795     }
3796   }
3797
3798   return true;
3799 }
3800
3801 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3802 /// the two vector operands have swapped position.
3803 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3804                                      unsigned NumElems) {
3805   for (unsigned i = 0; i != NumElems; ++i) {
3806     int idx = Mask[i];
3807     if (idx < 0)
3808       continue;
3809     else if (idx < (int)NumElems)
3810       Mask[i] = idx + NumElems;
3811     else
3812       Mask[i] = idx - NumElems;
3813   }
3814 }
3815
3816 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3817 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3818 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3819 /// reverse of what x86 shuffles want.
3820 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3821
3822   unsigned NumElems = VT.getVectorNumElements();
3823   unsigned NumLanes = VT.getSizeInBits()/128;
3824   unsigned NumLaneElems = NumElems/NumLanes;
3825
3826   if (NumLaneElems != 2 && NumLaneElems != 4)
3827     return false;
3828
3829   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3830   bool symetricMaskRequired =
3831     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3832
3833   // VSHUFPSY divides the resulting vector into 4 chunks.
3834   // The sources are also splitted into 4 chunks, and each destination
3835   // chunk must come from a different source chunk.
3836   //
3837   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3838   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3839   //
3840   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3841   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3842   //
3843   // VSHUFPDY divides the resulting vector into 4 chunks.
3844   // The sources are also splitted into 4 chunks, and each destination
3845   // chunk must come from a different source chunk.
3846   //
3847   //  SRC1 =>      X3       X2       X1       X0
3848   //  SRC2 =>      Y3       Y2       Y1       Y0
3849   //
3850   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3851   //
3852   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3853   unsigned HalfLaneElems = NumLaneElems/2;
3854   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3855     for (unsigned i = 0; i != NumLaneElems; ++i) {
3856       int Idx = Mask[i+l];
3857       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3858       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3859         return false;
3860       // For VSHUFPSY, the mask of the second half must be the same as the
3861       // first but with the appropriate offsets. This works in the same way as
3862       // VPERMILPS works with masks.
3863       if (!symetricMaskRequired || Idx < 0)
3864         continue;
3865       if (MaskVal[i] < 0) {
3866         MaskVal[i] = Idx - l;
3867         continue;
3868       }
3869       if ((signed)(Idx - l) != MaskVal[i])
3870         return false;
3871     }
3872   }
3873
3874   return true;
3875 }
3876
3877 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3878 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3879 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3880   if (!VT.is128BitVector())
3881     return false;
3882
3883   unsigned NumElems = VT.getVectorNumElements();
3884
3885   if (NumElems != 4)
3886     return false;
3887
3888   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3889   return isUndefOrEqual(Mask[0], 6) &&
3890          isUndefOrEqual(Mask[1], 7) &&
3891          isUndefOrEqual(Mask[2], 2) &&
3892          isUndefOrEqual(Mask[3], 3);
3893 }
3894
3895 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3896 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3897 /// <2, 3, 2, 3>
3898 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3899   if (!VT.is128BitVector())
3900     return false;
3901
3902   unsigned NumElems = VT.getVectorNumElements();
3903
3904   if (NumElems != 4)
3905     return false;
3906
3907   return isUndefOrEqual(Mask[0], 2) &&
3908          isUndefOrEqual(Mask[1], 3) &&
3909          isUndefOrEqual(Mask[2], 2) &&
3910          isUndefOrEqual(Mask[3], 3);
3911 }
3912
3913 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3914 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3915 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3916   if (!VT.is128BitVector())
3917     return false;
3918
3919   unsigned NumElems = VT.getVectorNumElements();
3920
3921   if (NumElems != 2 && NumElems != 4)
3922     return false;
3923
3924   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3925     if (!isUndefOrEqual(Mask[i], i + NumElems))
3926       return false;
3927
3928   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3929     if (!isUndefOrEqual(Mask[i], i))
3930       return false;
3931
3932   return true;
3933 }
3934
3935 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3937 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3938   if (!VT.is128BitVector())
3939     return false;
3940
3941   unsigned NumElems = VT.getVectorNumElements();
3942
3943   if (NumElems != 2 && NumElems != 4)
3944     return false;
3945
3946   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3947     if (!isUndefOrEqual(Mask[i], i))
3948       return false;
3949
3950   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3951     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3952       return false;
3953
3954   return true;
3955 }
3956
3957 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3958 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3959 /// i. e: If all but one element come from the same vector.
3960 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3961   // TODO: Deal with AVX's VINSERTPS
3962   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3963     return false;
3964
3965   unsigned CorrectPosV1 = 0;
3966   unsigned CorrectPosV2 = 0;
3967   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3968     if (Mask[i] == -1) {
3969       ++CorrectPosV1;
3970       ++CorrectPosV2;
3971       continue;
3972     }
3973
3974     if (Mask[i] == i)
3975       ++CorrectPosV1;
3976     else if (Mask[i] == i + 4)
3977       ++CorrectPosV2;
3978   }
3979
3980   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3981     // We have 3 elements (undefs count as elements from any vector) from one
3982     // vector, and one from another.
3983     return true;
3984
3985   return false;
3986 }
3987
3988 //
3989 // Some special combinations that can be optimized.
3990 //
3991 static
3992 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3993                                SelectionDAG &DAG) {
3994   MVT VT = SVOp->getSimpleValueType(0);
3995   SDLoc dl(SVOp);
3996
3997   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3998     return SDValue();
3999
4000   ArrayRef<int> Mask = SVOp->getMask();
4001
4002   // These are the special masks that may be optimized.
4003   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4004   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4005   bool MatchEvenMask = true;
4006   bool MatchOddMask  = true;
4007   for (int i=0; i<8; ++i) {
4008     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4009       MatchEvenMask = false;
4010     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4011       MatchOddMask = false;
4012   }
4013
4014   if (!MatchEvenMask && !MatchOddMask)
4015     return SDValue();
4016
4017   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4018
4019   SDValue Op0 = SVOp->getOperand(0);
4020   SDValue Op1 = SVOp->getOperand(1);
4021
4022   if (MatchEvenMask) {
4023     // Shift the second operand right to 32 bits.
4024     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4025     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4026   } else {
4027     // Shift the first operand left to 32 bits.
4028     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4029     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4030   }
4031   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4032   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4033 }
4034
4035 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4037 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4038                          bool HasInt256, bool V2IsSplat = false) {
4039
4040   assert(VT.getSizeInBits() >= 128 &&
4041          "Unsupported vector type for unpckl");
4042
4043   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4044   unsigned NumLanes;
4045   unsigned NumOf256BitLanes;
4046   unsigned NumElts = VT.getVectorNumElements();
4047   if (VT.is256BitVector()) {
4048     if (NumElts != 4 && NumElts != 8 &&
4049         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4050     return false;
4051     NumLanes = 2;
4052     NumOf256BitLanes = 1;
4053   } else if (VT.is512BitVector()) {
4054     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4055            "Unsupported vector type for unpckh");
4056     NumLanes = 2;
4057     NumOf256BitLanes = 2;
4058   } else {
4059     NumLanes = 1;
4060     NumOf256BitLanes = 1;
4061   }
4062
4063   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4064   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4065
4066   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4067     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4068       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4069         int BitI  = Mask[l256*NumEltsInStride+l+i];
4070         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4071         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4072           return false;
4073         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4074           return false;
4075         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4076           return false;
4077       }
4078     }
4079   }
4080   return true;
4081 }
4082
4083 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4084 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4085 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4086                          bool HasInt256, bool V2IsSplat = false) {
4087   assert(VT.getSizeInBits() >= 128 &&
4088          "Unsupported vector type for unpckh");
4089
4090   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4091   unsigned NumLanes;
4092   unsigned NumOf256BitLanes;
4093   unsigned NumElts = VT.getVectorNumElements();
4094   if (VT.is256BitVector()) {
4095     if (NumElts != 4 && NumElts != 8 &&
4096         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4097     return false;
4098     NumLanes = 2;
4099     NumOf256BitLanes = 1;
4100   } else if (VT.is512BitVector()) {
4101     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4102            "Unsupported vector type for unpckh");
4103     NumLanes = 2;
4104     NumOf256BitLanes = 2;
4105   } else {
4106     NumLanes = 1;
4107     NumOf256BitLanes = 1;
4108   }
4109
4110   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4111   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4112
4113   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4114     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4115       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4116         int BitI  = Mask[l256*NumEltsInStride+l+i];
4117         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4118         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4119           return false;
4120         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4121           return false;
4122         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4123           return false;
4124       }
4125     }
4126   }
4127   return true;
4128 }
4129
4130 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4131 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4132 /// <0, 0, 1, 1>
4133 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4134   unsigned NumElts = VT.getVectorNumElements();
4135   bool Is256BitVec = VT.is256BitVector();
4136
4137   if (VT.is512BitVector())
4138     return false;
4139   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4140          "Unsupported vector type for unpckh");
4141
4142   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4143       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4144     return false;
4145
4146   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4147   // FIXME: Need a better way to get rid of this, there's no latency difference
4148   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4149   // the former later. We should also remove the "_undef" special mask.
4150   if (NumElts == 4 && Is256BitVec)
4151     return false;
4152
4153   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4154   // independently on 128-bit lanes.
4155   unsigned NumLanes = VT.getSizeInBits()/128;
4156   unsigned NumLaneElts = NumElts/NumLanes;
4157
4158   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4159     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4160       int BitI  = Mask[l+i];
4161       int BitI1 = Mask[l+i+1];
4162
4163       if (!isUndefOrEqual(BitI, j))
4164         return false;
4165       if (!isUndefOrEqual(BitI1, j))
4166         return false;
4167     }
4168   }
4169
4170   return true;
4171 }
4172
4173 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4174 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4175 /// <2, 2, 3, 3>
4176 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4177   unsigned NumElts = VT.getVectorNumElements();
4178
4179   if (VT.is512BitVector())
4180     return false;
4181
4182   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4183          "Unsupported vector type for unpckh");
4184
4185   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4186       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4187     return false;
4188
4189   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4190   // independently on 128-bit lanes.
4191   unsigned NumLanes = VT.getSizeInBits()/128;
4192   unsigned NumLaneElts = NumElts/NumLanes;
4193
4194   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4195     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4196       int BitI  = Mask[l+i];
4197       int BitI1 = Mask[l+i+1];
4198       if (!isUndefOrEqual(BitI, j))
4199         return false;
4200       if (!isUndefOrEqual(BitI1, j))
4201         return false;
4202     }
4203   }
4204   return true;
4205 }
4206
4207 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4208 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4209 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4210   if (!VT.is512BitVector())
4211     return false;
4212
4213   unsigned NumElts = VT.getVectorNumElements();
4214   unsigned HalfSize = NumElts/2;
4215   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4216     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4217       *Imm = 1;
4218       return true;
4219     }
4220   }
4221   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4222     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4223       *Imm = 0;
4224       return true;
4225     }
4226   }
4227   return false;
4228 }
4229
4230 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4231 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4232 /// MOVSD, and MOVD, i.e. setting the lowest element.
4233 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4234   if (VT.getVectorElementType().getSizeInBits() < 32)
4235     return false;
4236   if (!VT.is128BitVector())
4237     return false;
4238
4239   unsigned NumElts = VT.getVectorNumElements();
4240
4241   if (!isUndefOrEqual(Mask[0], NumElts))
4242     return false;
4243
4244   for (unsigned i = 1; i != NumElts; ++i)
4245     if (!isUndefOrEqual(Mask[i], i))
4246       return false;
4247
4248   return true;
4249 }
4250
4251 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4252 /// as permutations between 128-bit chunks or halves. As an example: this
4253 /// shuffle bellow:
4254 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4255 /// The first half comes from the second half of V1 and the second half from the
4256 /// the second half of V2.
4257 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4258   if (!HasFp256 || !VT.is256BitVector())
4259     return false;
4260
4261   // The shuffle result is divided into half A and half B. In total the two
4262   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4263   // B must come from C, D, E or F.
4264   unsigned HalfSize = VT.getVectorNumElements()/2;
4265   bool MatchA = false, MatchB = false;
4266
4267   // Check if A comes from one of C, D, E, F.
4268   for (unsigned Half = 0; Half != 4; ++Half) {
4269     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4270       MatchA = true;
4271       break;
4272     }
4273   }
4274
4275   // Check if B comes from one of C, D, E, F.
4276   for (unsigned Half = 0; Half != 4; ++Half) {
4277     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4278       MatchB = true;
4279       break;
4280     }
4281   }
4282
4283   return MatchA && MatchB;
4284 }
4285
4286 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4287 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4288 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4289   MVT VT = SVOp->getSimpleValueType(0);
4290
4291   unsigned HalfSize = VT.getVectorNumElements()/2;
4292
4293   unsigned FstHalf = 0, SndHalf = 0;
4294   for (unsigned i = 0; i < HalfSize; ++i) {
4295     if (SVOp->getMaskElt(i) > 0) {
4296       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4297       break;
4298     }
4299   }
4300   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4301     if (SVOp->getMaskElt(i) > 0) {
4302       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4303       break;
4304     }
4305   }
4306
4307   return (FstHalf | (SndHalf << 4));
4308 }
4309
4310 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4311 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4312   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4313   if (EltSize < 32)
4314     return false;
4315
4316   unsigned NumElts = VT.getVectorNumElements();
4317   Imm8 = 0;
4318   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4319     for (unsigned i = 0; i != NumElts; ++i) {
4320       if (Mask[i] < 0)
4321         continue;
4322       Imm8 |= Mask[i] << (i*2);
4323     }
4324     return true;
4325   }
4326
4327   unsigned LaneSize = 4;
4328   SmallVector<int, 4> MaskVal(LaneSize, -1);
4329
4330   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4331     for (unsigned i = 0; i != LaneSize; ++i) {
4332       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4333         return false;
4334       if (Mask[i+l] < 0)
4335         continue;
4336       if (MaskVal[i] < 0) {
4337         MaskVal[i] = Mask[i+l] - l;
4338         Imm8 |= MaskVal[i] << (i*2);
4339         continue;
4340       }
4341       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4342         return false;
4343     }
4344   }
4345   return true;
4346 }
4347
4348 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4349 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4350 /// Note that VPERMIL mask matching is different depending whether theunderlying
4351 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4352 /// to the same elements of the low, but to the higher half of the source.
4353 /// In VPERMILPD the two lanes could be shuffled independently of each other
4354 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4355 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4356   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4357   if (VT.getSizeInBits() < 256 || EltSize < 32)
4358     return false;
4359   bool symetricMaskRequired = (EltSize == 32);
4360   unsigned NumElts = VT.getVectorNumElements();
4361
4362   unsigned NumLanes = VT.getSizeInBits()/128;
4363   unsigned LaneSize = NumElts/NumLanes;
4364   // 2 or 4 elements in one lane
4365
4366   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4367   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4368     for (unsigned i = 0; i != LaneSize; ++i) {
4369       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4370         return false;
4371       if (symetricMaskRequired) {
4372         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4373           ExpectedMaskVal[i] = Mask[i+l] - l;
4374           continue;
4375         }
4376         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4377           return false;
4378       }
4379     }
4380   }
4381   return true;
4382 }
4383
4384 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4385 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4386 /// element of vector 2 and the other elements to come from vector 1 in order.
4387 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4388                                bool V2IsSplat = false, bool V2IsUndef = false) {
4389   if (!VT.is128BitVector())
4390     return false;
4391
4392   unsigned NumOps = VT.getVectorNumElements();
4393   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4394     return false;
4395
4396   if (!isUndefOrEqual(Mask[0], 0))
4397     return false;
4398
4399   for (unsigned i = 1; i != NumOps; ++i)
4400     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4401           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4402           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4403       return false;
4404
4405   return true;
4406 }
4407
4408 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4409 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4410 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4411 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4412                            const X86Subtarget *Subtarget) {
4413   if (!Subtarget->hasSSE3())
4414     return false;
4415
4416   unsigned NumElems = VT.getVectorNumElements();
4417
4418   if ((VT.is128BitVector() && NumElems != 4) ||
4419       (VT.is256BitVector() && NumElems != 8) ||
4420       (VT.is512BitVector() && NumElems != 16))
4421     return false;
4422
4423   // "i+1" is the value the indexed mask element must have
4424   for (unsigned i = 0; i != NumElems; i += 2)
4425     if (!isUndefOrEqual(Mask[i], i+1) ||
4426         !isUndefOrEqual(Mask[i+1], i+1))
4427       return false;
4428
4429   return true;
4430 }
4431
4432 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4433 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4434 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4435 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4436                            const X86Subtarget *Subtarget) {
4437   if (!Subtarget->hasSSE3())
4438     return false;
4439
4440   unsigned NumElems = VT.getVectorNumElements();
4441
4442   if ((VT.is128BitVector() && NumElems != 4) ||
4443       (VT.is256BitVector() && NumElems != 8) ||
4444       (VT.is512BitVector() && NumElems != 16))
4445     return false;
4446
4447   // "i" is the value the indexed mask element must have
4448   for (unsigned i = 0; i != NumElems; i += 2)
4449     if (!isUndefOrEqual(Mask[i], i) ||
4450         !isUndefOrEqual(Mask[i+1], i))
4451       return false;
4452
4453   return true;
4454 }
4455
4456 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4457 /// specifies a shuffle of elements that is suitable for input to 256-bit
4458 /// version of MOVDDUP.
4459 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4460   if (!HasFp256 || !VT.is256BitVector())
4461     return false;
4462
4463   unsigned NumElts = VT.getVectorNumElements();
4464   if (NumElts != 4)
4465     return false;
4466
4467   for (unsigned i = 0; i != NumElts/2; ++i)
4468     if (!isUndefOrEqual(Mask[i], 0))
4469       return false;
4470   for (unsigned i = NumElts/2; i != NumElts; ++i)
4471     if (!isUndefOrEqual(Mask[i], NumElts/2))
4472       return false;
4473   return true;
4474 }
4475
4476 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4477 /// specifies a shuffle of elements that is suitable for input to 128-bit
4478 /// version of MOVDDUP.
4479 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4480   if (!VT.is128BitVector())
4481     return false;
4482
4483   unsigned e = VT.getVectorNumElements() / 2;
4484   for (unsigned i = 0; i != e; ++i)
4485     if (!isUndefOrEqual(Mask[i], i))
4486       return false;
4487   for (unsigned i = 0; i != e; ++i)
4488     if (!isUndefOrEqual(Mask[e+i], i))
4489       return false;
4490   return true;
4491 }
4492
4493 /// isVEXTRACTIndex - Return true if the specified
4494 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4495 /// suitable for instruction that extract 128 or 256 bit vectors
4496 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4497   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4498   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4499     return false;
4500
4501   // The index should be aligned on a vecWidth-bit boundary.
4502   uint64_t Index =
4503     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4504
4505   MVT VT = N->getSimpleValueType(0);
4506   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4507   bool Result = (Index * ElSize) % vecWidth == 0;
4508
4509   return Result;
4510 }
4511
4512 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4513 /// operand specifies a subvector insert that is suitable for input to
4514 /// insertion of 128 or 256-bit subvectors
4515 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4516   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4517   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4518     return false;
4519   // The index should be aligned on a vecWidth-bit boundary.
4520   uint64_t Index =
4521     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4522
4523   MVT VT = N->getSimpleValueType(0);
4524   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4525   bool Result = (Index * ElSize) % vecWidth == 0;
4526
4527   return Result;
4528 }
4529
4530 bool X86::isVINSERT128Index(SDNode *N) {
4531   return isVINSERTIndex(N, 128);
4532 }
4533
4534 bool X86::isVINSERT256Index(SDNode *N) {
4535   return isVINSERTIndex(N, 256);
4536 }
4537
4538 bool X86::isVEXTRACT128Index(SDNode *N) {
4539   return isVEXTRACTIndex(N, 128);
4540 }
4541
4542 bool X86::isVEXTRACT256Index(SDNode *N) {
4543   return isVEXTRACTIndex(N, 256);
4544 }
4545
4546 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4547 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4548 /// Handles 128-bit and 256-bit.
4549 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4550   MVT VT = N->getSimpleValueType(0);
4551
4552   assert((VT.getSizeInBits() >= 128) &&
4553          "Unsupported vector type for PSHUF/SHUFP");
4554
4555   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4556   // independently on 128-bit lanes.
4557   unsigned NumElts = VT.getVectorNumElements();
4558   unsigned NumLanes = VT.getSizeInBits()/128;
4559   unsigned NumLaneElts = NumElts/NumLanes;
4560
4561   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4562          "Only supports 2, 4 or 8 elements per lane");
4563
4564   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4565   unsigned Mask = 0;
4566   for (unsigned i = 0; i != NumElts; ++i) {
4567     int Elt = N->getMaskElt(i);
4568     if (Elt < 0) continue;
4569     Elt &= NumLaneElts - 1;
4570     unsigned ShAmt = (i << Shift) % 8;
4571     Mask |= Elt << ShAmt;
4572   }
4573
4574   return Mask;
4575 }
4576
4577 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4578 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4579 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4580   MVT VT = N->getSimpleValueType(0);
4581
4582   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4583          "Unsupported vector type for PSHUFHW");
4584
4585   unsigned NumElts = VT.getVectorNumElements();
4586
4587   unsigned Mask = 0;
4588   for (unsigned l = 0; l != NumElts; l += 8) {
4589     // 8 nodes per lane, but we only care about the last 4.
4590     for (unsigned i = 0; i < 4; ++i) {
4591       int Elt = N->getMaskElt(l+i+4);
4592       if (Elt < 0) continue;
4593       Elt &= 0x3; // only 2-bits.
4594       Mask |= Elt << (i * 2);
4595     }
4596   }
4597
4598   return Mask;
4599 }
4600
4601 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4602 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4603 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4604   MVT VT = N->getSimpleValueType(0);
4605
4606   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4607          "Unsupported vector type for PSHUFHW");
4608
4609   unsigned NumElts = VT.getVectorNumElements();
4610
4611   unsigned Mask = 0;
4612   for (unsigned l = 0; l != NumElts; l += 8) {
4613     // 8 nodes per lane, but we only care about the first 4.
4614     for (unsigned i = 0; i < 4; ++i) {
4615       int Elt = N->getMaskElt(l+i);
4616       if (Elt < 0) continue;
4617       Elt &= 0x3; // only 2-bits
4618       Mask |= Elt << (i * 2);
4619     }
4620   }
4621
4622   return Mask;
4623 }
4624
4625 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4626 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4627 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4628   MVT VT = SVOp->getSimpleValueType(0);
4629   unsigned EltSize = VT.is512BitVector() ? 1 :
4630     VT.getVectorElementType().getSizeInBits() >> 3;
4631
4632   unsigned NumElts = VT.getVectorNumElements();
4633   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4634   unsigned NumLaneElts = NumElts/NumLanes;
4635
4636   int Val = 0;
4637   unsigned i;
4638   for (i = 0; i != NumElts; ++i) {
4639     Val = SVOp->getMaskElt(i);
4640     if (Val >= 0)
4641       break;
4642   }
4643   if (Val >= (int)NumElts)
4644     Val -= NumElts - NumLaneElts;
4645
4646   assert(Val - i > 0 && "PALIGNR imm should be positive");
4647   return (Val - i) * EltSize;
4648 }
4649
4650 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4651   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4652   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4653     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4654
4655   uint64_t Index =
4656     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4657
4658   MVT VecVT = N->getOperand(0).getSimpleValueType();
4659   MVT ElVT = VecVT.getVectorElementType();
4660
4661   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4662   return Index / NumElemsPerChunk;
4663 }
4664
4665 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4666   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4667   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4668     llvm_unreachable("Illegal insert subvector for VINSERT");
4669
4670   uint64_t Index =
4671     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4672
4673   MVT VecVT = N->getSimpleValueType(0);
4674   MVT ElVT = VecVT.getVectorElementType();
4675
4676   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4677   return Index / NumElemsPerChunk;
4678 }
4679
4680 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4681 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4682 /// and VINSERTI128 instructions.
4683 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4684   return getExtractVEXTRACTImmediate(N, 128);
4685 }
4686
4687 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4688 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4689 /// and VINSERTI64x4 instructions.
4690 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4691   return getExtractVEXTRACTImmediate(N, 256);
4692 }
4693
4694 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4695 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4696 /// and VINSERTI128 instructions.
4697 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4698   return getInsertVINSERTImmediate(N, 128);
4699 }
4700
4701 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4702 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4703 /// and VINSERTI64x4 instructions.
4704 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4705   return getInsertVINSERTImmediate(N, 256);
4706 }
4707
4708 /// isZero - Returns true if Elt is a constant integer zero
4709 static bool isZero(SDValue V) {
4710   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4711   return C && C->isNullValue();
4712 }
4713
4714 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4715 /// constant +0.0.
4716 bool X86::isZeroNode(SDValue Elt) {
4717   if (isZero(Elt))
4718     return true;
4719   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4720     return CFP->getValueAPF().isPosZero();
4721   return false;
4722 }
4723
4724 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4725 /// their permute mask.
4726 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4727                                     SelectionDAG &DAG) {
4728   MVT VT = SVOp->getSimpleValueType(0);
4729   unsigned NumElems = VT.getVectorNumElements();
4730   SmallVector<int, 8> MaskVec;
4731
4732   for (unsigned i = 0; i != NumElems; ++i) {
4733     int Idx = SVOp->getMaskElt(i);
4734     if (Idx >= 0) {
4735       if (Idx < (int)NumElems)
4736         Idx += NumElems;
4737       else
4738         Idx -= NumElems;
4739     }
4740     MaskVec.push_back(Idx);
4741   }
4742   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4743                               SVOp->getOperand(0), &MaskVec[0]);
4744 }
4745
4746 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4747 /// match movhlps. The lower half elements should come from upper half of
4748 /// V1 (and in order), and the upper half elements should come from the upper
4749 /// half of V2 (and in order).
4750 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4751   if (!VT.is128BitVector())
4752     return false;
4753   if (VT.getVectorNumElements() != 4)
4754     return false;
4755   for (unsigned i = 0, e = 2; i != e; ++i)
4756     if (!isUndefOrEqual(Mask[i], i+2))
4757       return false;
4758   for (unsigned i = 2; i != 4; ++i)
4759     if (!isUndefOrEqual(Mask[i], i+4))
4760       return false;
4761   return true;
4762 }
4763
4764 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4765 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4766 /// required.
4767 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4768   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4769     return false;
4770   N = N->getOperand(0).getNode();
4771   if (!ISD::isNON_EXTLoad(N))
4772     return false;
4773   if (LD)
4774     *LD = cast<LoadSDNode>(N);
4775   return true;
4776 }
4777
4778 // Test whether the given value is a vector value which will be legalized
4779 // into a load.
4780 static bool WillBeConstantPoolLoad(SDNode *N) {
4781   if (N->getOpcode() != ISD::BUILD_VECTOR)
4782     return false;
4783
4784   // Check for any non-constant elements.
4785   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4786     switch (N->getOperand(i).getNode()->getOpcode()) {
4787     case ISD::UNDEF:
4788     case ISD::ConstantFP:
4789     case ISD::Constant:
4790       break;
4791     default:
4792       return false;
4793     }
4794
4795   // Vectors of all-zeros and all-ones are materialized with special
4796   // instructions rather than being loaded.
4797   return !ISD::isBuildVectorAllZeros(N) &&
4798          !ISD::isBuildVectorAllOnes(N);
4799 }
4800
4801 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4802 /// match movlp{s|d}. The lower half elements should come from lower half of
4803 /// V1 (and in order), and the upper half elements should come from the upper
4804 /// half of V2 (and in order). And since V1 will become the source of the
4805 /// MOVLP, it must be either a vector load or a scalar load to vector.
4806 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4807                                ArrayRef<int> Mask, MVT VT) {
4808   if (!VT.is128BitVector())
4809     return false;
4810
4811   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4812     return false;
4813   // Is V2 is a vector load, don't do this transformation. We will try to use
4814   // load folding shufps op.
4815   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4816     return false;
4817
4818   unsigned NumElems = VT.getVectorNumElements();
4819
4820   if (NumElems != 2 && NumElems != 4)
4821     return false;
4822   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4823     if (!isUndefOrEqual(Mask[i], i))
4824       return false;
4825   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4826     if (!isUndefOrEqual(Mask[i], i+NumElems))
4827       return false;
4828   return true;
4829 }
4830
4831 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4832 /// all the same.
4833 static bool isSplatVector(SDNode *N) {
4834   if (N->getOpcode() != ISD::BUILD_VECTOR)
4835     return false;
4836
4837   SDValue SplatValue = N->getOperand(0);
4838   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4839     if (N->getOperand(i) != SplatValue)
4840       return false;
4841   return true;
4842 }
4843
4844 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4845 /// to an zero vector.
4846 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4847 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4848   SDValue V1 = N->getOperand(0);
4849   SDValue V2 = N->getOperand(1);
4850   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4851   for (unsigned i = 0; i != NumElems; ++i) {
4852     int Idx = N->getMaskElt(i);
4853     if (Idx >= (int)NumElems) {
4854       unsigned Opc = V2.getOpcode();
4855       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4856         continue;
4857       if (Opc != ISD::BUILD_VECTOR ||
4858           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4859         return false;
4860     } else if (Idx >= 0) {
4861       unsigned Opc = V1.getOpcode();
4862       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4863         continue;
4864       if (Opc != ISD::BUILD_VECTOR ||
4865           !X86::isZeroNode(V1.getOperand(Idx)))
4866         return false;
4867     }
4868   }
4869   return true;
4870 }
4871
4872 /// getZeroVector - Returns a vector of specified type with all zero elements.
4873 ///
4874 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4875                              SelectionDAG &DAG, SDLoc dl) {
4876   assert(VT.isVector() && "Expected a vector type");
4877
4878   // Always build SSE zero vectors as <4 x i32> bitcasted
4879   // to their dest type. This ensures they get CSE'd.
4880   SDValue Vec;
4881   if (VT.is128BitVector()) {  // SSE
4882     if (Subtarget->hasSSE2()) {  // SSE2
4883       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4884       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4885     } else { // SSE1
4886       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4887       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4888     }
4889   } else if (VT.is256BitVector()) { // AVX
4890     if (Subtarget->hasInt256()) { // AVX2
4891       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4892       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4893       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4894     } else {
4895       // 256-bit logic and arithmetic instructions in AVX are all
4896       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4897       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4898       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4899       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4900     }
4901   } else if (VT.is512BitVector()) { // AVX-512
4902       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4903       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4904                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4905       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4906   } else if (VT.getScalarType() == MVT::i1) {
4907     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4908     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4909     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4910     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4911   } else
4912     llvm_unreachable("Unexpected vector type");
4913
4914   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4915 }
4916
4917 /// getOnesVector - Returns a vector of specified type with all bits set.
4918 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4919 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4920 /// Then bitcast to their original type, ensuring they get CSE'd.
4921 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4922                              SDLoc dl) {
4923   assert(VT.isVector() && "Expected a vector type");
4924
4925   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4926   SDValue Vec;
4927   if (VT.is256BitVector()) {
4928     if (HasInt256) { // AVX2
4929       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4930       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4931     } else { // AVX
4932       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4933       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4934     }
4935   } else if (VT.is128BitVector()) {
4936     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4937   } else
4938     llvm_unreachable("Unexpected vector type");
4939
4940   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4941 }
4942
4943 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4944 /// that point to V2 points to its first element.
4945 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4946   for (unsigned i = 0; i != NumElems; ++i) {
4947     if (Mask[i] > (int)NumElems) {
4948       Mask[i] = NumElems;
4949     }
4950   }
4951 }
4952
4953 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4954 /// operation of specified width.
4955 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4956                        SDValue V2) {
4957   unsigned NumElems = VT.getVectorNumElements();
4958   SmallVector<int, 8> Mask;
4959   Mask.push_back(NumElems);
4960   for (unsigned i = 1; i != NumElems; ++i)
4961     Mask.push_back(i);
4962   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4963 }
4964
4965 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4966 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4967                           SDValue V2) {
4968   unsigned NumElems = VT.getVectorNumElements();
4969   SmallVector<int, 8> Mask;
4970   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4971     Mask.push_back(i);
4972     Mask.push_back(i + NumElems);
4973   }
4974   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4975 }
4976
4977 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4978 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4979                           SDValue V2) {
4980   unsigned NumElems = VT.getVectorNumElements();
4981   SmallVector<int, 8> Mask;
4982   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4983     Mask.push_back(i + Half);
4984     Mask.push_back(i + NumElems + Half);
4985   }
4986   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4987 }
4988
4989 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4990 // a generic shuffle instruction because the target has no such instructions.
4991 // Generate shuffles which repeat i16 and i8 several times until they can be
4992 // represented by v4f32 and then be manipulated by target suported shuffles.
4993 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4994   MVT VT = V.getSimpleValueType();
4995   int NumElems = VT.getVectorNumElements();
4996   SDLoc dl(V);
4997
4998   while (NumElems > 4) {
4999     if (EltNo < NumElems/2) {
5000       V = getUnpackl(DAG, dl, VT, V, V);
5001     } else {
5002       V = getUnpackh(DAG, dl, VT, V, V);
5003       EltNo -= NumElems/2;
5004     }
5005     NumElems >>= 1;
5006   }
5007   return V;
5008 }
5009
5010 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5011 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5012   MVT VT = V.getSimpleValueType();
5013   SDLoc dl(V);
5014
5015   if (VT.is128BitVector()) {
5016     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5017     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5018     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5019                              &SplatMask[0]);
5020   } else if (VT.is256BitVector()) {
5021     // To use VPERMILPS to splat scalars, the second half of indicies must
5022     // refer to the higher part, which is a duplication of the lower one,
5023     // because VPERMILPS can only handle in-lane permutations.
5024     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5025                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5026
5027     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5028     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5029                              &SplatMask[0]);
5030   } else
5031     llvm_unreachable("Vector size not supported");
5032
5033   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5034 }
5035
5036 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5037 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5038   MVT SrcVT = SV->getSimpleValueType(0);
5039   SDValue V1 = SV->getOperand(0);
5040   SDLoc dl(SV);
5041
5042   int EltNo = SV->getSplatIndex();
5043   int NumElems = SrcVT.getVectorNumElements();
5044   bool Is256BitVec = SrcVT.is256BitVector();
5045
5046   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5047          "Unknown how to promote splat for type");
5048
5049   // Extract the 128-bit part containing the splat element and update
5050   // the splat element index when it refers to the higher register.
5051   if (Is256BitVec) {
5052     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5053     if (EltNo >= NumElems/2)
5054       EltNo -= NumElems/2;
5055   }
5056
5057   // All i16 and i8 vector types can't be used directly by a generic shuffle
5058   // instruction because the target has no such instruction. Generate shuffles
5059   // which repeat i16 and i8 several times until they fit in i32, and then can
5060   // be manipulated by target suported shuffles.
5061   MVT EltVT = SrcVT.getVectorElementType();
5062   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5063     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5064
5065   // Recreate the 256-bit vector and place the same 128-bit vector
5066   // into the low and high part. This is necessary because we want
5067   // to use VPERM* to shuffle the vectors
5068   if (Is256BitVec) {
5069     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5070   }
5071
5072   return getLegalSplat(DAG, V1, EltNo);
5073 }
5074
5075 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5076 /// vector of zero or undef vector.  This produces a shuffle where the low
5077 /// element of V2 is swizzled into the zero/undef vector, landing at element
5078 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5079 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5080                                            bool IsZero,
5081                                            const X86Subtarget *Subtarget,
5082                                            SelectionDAG &DAG) {
5083   MVT VT = V2.getSimpleValueType();
5084   SDValue V1 = IsZero
5085     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5086   unsigned NumElems = VT.getVectorNumElements();
5087   SmallVector<int, 16> MaskVec;
5088   for (unsigned i = 0; i != NumElems; ++i)
5089     // If this is the insertion idx, put the low elt of V2 here.
5090     MaskVec.push_back(i == Idx ? NumElems : i);
5091   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5092 }
5093
5094 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5095 /// target specific opcode. Returns true if the Mask could be calculated.
5096 /// Sets IsUnary to true if only uses one source.
5097 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5098                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5099   unsigned NumElems = VT.getVectorNumElements();
5100   SDValue ImmN;
5101
5102   IsUnary = false;
5103   switch(N->getOpcode()) {
5104   case X86ISD::SHUFP:
5105     ImmN = N->getOperand(N->getNumOperands()-1);
5106     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5107     break;
5108   case X86ISD::UNPCKH:
5109     DecodeUNPCKHMask(VT, Mask);
5110     break;
5111   case X86ISD::UNPCKL:
5112     DecodeUNPCKLMask(VT, Mask);
5113     break;
5114   case X86ISD::MOVHLPS:
5115     DecodeMOVHLPSMask(NumElems, Mask);
5116     break;
5117   case X86ISD::MOVLHPS:
5118     DecodeMOVLHPSMask(NumElems, Mask);
5119     break;
5120   case X86ISD::PALIGNR:
5121     ImmN = N->getOperand(N->getNumOperands()-1);
5122     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5123     break;
5124   case X86ISD::PSHUFD:
5125   case X86ISD::VPERMILP:
5126     ImmN = N->getOperand(N->getNumOperands()-1);
5127     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5128     IsUnary = true;
5129     break;
5130   case X86ISD::PSHUFHW:
5131     ImmN = N->getOperand(N->getNumOperands()-1);
5132     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5133     IsUnary = true;
5134     break;
5135   case X86ISD::PSHUFLW:
5136     ImmN = N->getOperand(N->getNumOperands()-1);
5137     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5138     IsUnary = true;
5139     break;
5140   case X86ISD::VPERMI:
5141     ImmN = N->getOperand(N->getNumOperands()-1);
5142     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5143     IsUnary = true;
5144     break;
5145   case X86ISD::MOVSS:
5146   case X86ISD::MOVSD: {
5147     // The index 0 always comes from the first element of the second source,
5148     // this is why MOVSS and MOVSD are used in the first place. The other
5149     // elements come from the other positions of the first source vector
5150     Mask.push_back(NumElems);
5151     for (unsigned i = 1; i != NumElems; ++i) {
5152       Mask.push_back(i);
5153     }
5154     break;
5155   }
5156   case X86ISD::VPERM2X128:
5157     ImmN = N->getOperand(N->getNumOperands()-1);
5158     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5159     if (Mask.empty()) return false;
5160     break;
5161   case X86ISD::MOVDDUP:
5162   case X86ISD::MOVLHPD:
5163   case X86ISD::MOVLPD:
5164   case X86ISD::MOVLPS:
5165   case X86ISD::MOVSHDUP:
5166   case X86ISD::MOVSLDUP:
5167     // Not yet implemented
5168     return false;
5169   default: llvm_unreachable("unknown target shuffle node");
5170   }
5171
5172   return true;
5173 }
5174
5175 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5176 /// element of the result of the vector shuffle.
5177 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5178                                    unsigned Depth) {
5179   if (Depth == 6)
5180     return SDValue();  // Limit search depth.
5181
5182   SDValue V = SDValue(N, 0);
5183   EVT VT = V.getValueType();
5184   unsigned Opcode = V.getOpcode();
5185
5186   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5187   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5188     int Elt = SV->getMaskElt(Index);
5189
5190     if (Elt < 0)
5191       return DAG.getUNDEF(VT.getVectorElementType());
5192
5193     unsigned NumElems = VT.getVectorNumElements();
5194     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5195                                          : SV->getOperand(1);
5196     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5197   }
5198
5199   // Recurse into target specific vector shuffles to find scalars.
5200   if (isTargetShuffle(Opcode)) {
5201     MVT ShufVT = V.getSimpleValueType();
5202     unsigned NumElems = ShufVT.getVectorNumElements();
5203     SmallVector<int, 16> ShuffleMask;
5204     bool IsUnary;
5205
5206     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5207       return SDValue();
5208
5209     int Elt = ShuffleMask[Index];
5210     if (Elt < 0)
5211       return DAG.getUNDEF(ShufVT.getVectorElementType());
5212
5213     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5214                                          : N->getOperand(1);
5215     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5216                                Depth+1);
5217   }
5218
5219   // Actual nodes that may contain scalar elements
5220   if (Opcode == ISD::BITCAST) {
5221     V = V.getOperand(0);
5222     EVT SrcVT = V.getValueType();
5223     unsigned NumElems = VT.getVectorNumElements();
5224
5225     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5226       return SDValue();
5227   }
5228
5229   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5230     return (Index == 0) ? V.getOperand(0)
5231                         : DAG.getUNDEF(VT.getVectorElementType());
5232
5233   if (V.getOpcode() == ISD::BUILD_VECTOR)
5234     return V.getOperand(Index);
5235
5236   return SDValue();
5237 }
5238
5239 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5240 /// shuffle operation which come from a consecutively from a zero. The
5241 /// search can start in two different directions, from left or right.
5242 /// We count undefs as zeros until PreferredNum is reached.
5243 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5244                                          unsigned NumElems, bool ZerosFromLeft,
5245                                          SelectionDAG &DAG,
5246                                          unsigned PreferredNum = -1U) {
5247   unsigned NumZeros = 0;
5248   for (unsigned i = 0; i != NumElems; ++i) {
5249     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5250     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5251     if (!Elt.getNode())
5252       break;
5253
5254     if (X86::isZeroNode(Elt))
5255       ++NumZeros;
5256     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5257       NumZeros = std::min(NumZeros + 1, PreferredNum);
5258     else
5259       break;
5260   }
5261
5262   return NumZeros;
5263 }
5264
5265 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5266 /// correspond consecutively to elements from one of the vector operands,
5267 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5268 static
5269 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5270                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5271                               unsigned NumElems, unsigned &OpNum) {
5272   bool SeenV1 = false;
5273   bool SeenV2 = false;
5274
5275   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5276     int Idx = SVOp->getMaskElt(i);
5277     // Ignore undef indicies
5278     if (Idx < 0)
5279       continue;
5280
5281     if (Idx < (int)NumElems)
5282       SeenV1 = true;
5283     else
5284       SeenV2 = true;
5285
5286     // Only accept consecutive elements from the same vector
5287     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5288       return false;
5289   }
5290
5291   OpNum = SeenV1 ? 0 : 1;
5292   return true;
5293 }
5294
5295 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5296 /// logical left shift of a vector.
5297 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5298                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5299   unsigned NumElems =
5300     SVOp->getSimpleValueType(0).getVectorNumElements();
5301   unsigned NumZeros = getNumOfConsecutiveZeros(
5302       SVOp, NumElems, false /* check zeros from right */, DAG,
5303       SVOp->getMaskElt(0));
5304   unsigned OpSrc;
5305
5306   if (!NumZeros)
5307     return false;
5308
5309   // Considering the elements in the mask that are not consecutive zeros,
5310   // check if they consecutively come from only one of the source vectors.
5311   //
5312   //               V1 = {X, A, B, C}     0
5313   //                         \  \  \    /
5314   //   vector_shuffle V1, V2 <1, 2, 3, X>
5315   //
5316   if (!isShuffleMaskConsecutive(SVOp,
5317             0,                   // Mask Start Index
5318             NumElems-NumZeros,   // Mask End Index(exclusive)
5319             NumZeros,            // Where to start looking in the src vector
5320             NumElems,            // Number of elements in vector
5321             OpSrc))              // Which source operand ?
5322     return false;
5323
5324   isLeft = false;
5325   ShAmt = NumZeros;
5326   ShVal = SVOp->getOperand(OpSrc);
5327   return true;
5328 }
5329
5330 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5331 /// logical left shift of a vector.
5332 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5333                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5334   unsigned NumElems =
5335     SVOp->getSimpleValueType(0).getVectorNumElements();
5336   unsigned NumZeros = getNumOfConsecutiveZeros(
5337       SVOp, NumElems, true /* check zeros from left */, DAG,
5338       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5339   unsigned OpSrc;
5340
5341   if (!NumZeros)
5342     return false;
5343
5344   // Considering the elements in the mask that are not consecutive zeros,
5345   // check if they consecutively come from only one of the source vectors.
5346   //
5347   //                           0    { A, B, X, X } = V2
5348   //                          / \    /  /
5349   //   vector_shuffle V1, V2 <X, X, 4, 5>
5350   //
5351   if (!isShuffleMaskConsecutive(SVOp,
5352             NumZeros,     // Mask Start Index
5353             NumElems,     // Mask End Index(exclusive)
5354             0,            // Where to start looking in the src vector
5355             NumElems,     // Number of elements in vector
5356             OpSrc))       // Which source operand ?
5357     return false;
5358
5359   isLeft = true;
5360   ShAmt = NumZeros;
5361   ShVal = SVOp->getOperand(OpSrc);
5362   return true;
5363 }
5364
5365 /// isVectorShift - Returns true if the shuffle can be implemented as a
5366 /// logical left or right shift of a vector.
5367 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5368                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5369   // Although the logic below support any bitwidth size, there are no
5370   // shift instructions which handle more than 128-bit vectors.
5371   if (!SVOp->getSimpleValueType(0).is128BitVector())
5372     return false;
5373
5374   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5375       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5376     return true;
5377
5378   return false;
5379 }
5380
5381 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5382 ///
5383 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5384                                        unsigned NumNonZero, unsigned NumZero,
5385                                        SelectionDAG &DAG,
5386                                        const X86Subtarget* Subtarget,
5387                                        const TargetLowering &TLI) {
5388   if (NumNonZero > 8)
5389     return SDValue();
5390
5391   SDLoc dl(Op);
5392   SDValue V;
5393   bool First = true;
5394   for (unsigned i = 0; i < 16; ++i) {
5395     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5396     if (ThisIsNonZero && First) {
5397       if (NumZero)
5398         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5399       else
5400         V = DAG.getUNDEF(MVT::v8i16);
5401       First = false;
5402     }
5403
5404     if ((i & 1) != 0) {
5405       SDValue ThisElt, LastElt;
5406       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5407       if (LastIsNonZero) {
5408         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5409                               MVT::i16, Op.getOperand(i-1));
5410       }
5411       if (ThisIsNonZero) {
5412         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5413         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5414                               ThisElt, DAG.getConstant(8, MVT::i8));
5415         if (LastIsNonZero)
5416           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5417       } else
5418         ThisElt = LastElt;
5419
5420       if (ThisElt.getNode())
5421         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5422                         DAG.getIntPtrConstant(i/2));
5423     }
5424   }
5425
5426   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5427 }
5428
5429 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5430 ///
5431 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5432                                      unsigned NumNonZero, unsigned NumZero,
5433                                      SelectionDAG &DAG,
5434                                      const X86Subtarget* Subtarget,
5435                                      const TargetLowering &TLI) {
5436   if (NumNonZero > 4)
5437     return SDValue();
5438
5439   SDLoc dl(Op);
5440   SDValue V;
5441   bool First = true;
5442   for (unsigned i = 0; i < 8; ++i) {
5443     bool isNonZero = (NonZeros & (1 << i)) != 0;
5444     if (isNonZero) {
5445       if (First) {
5446         if (NumZero)
5447           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5448         else
5449           V = DAG.getUNDEF(MVT::v8i16);
5450         First = false;
5451       }
5452       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5453                       MVT::v8i16, V, Op.getOperand(i),
5454                       DAG.getIntPtrConstant(i));
5455     }
5456   }
5457
5458   return V;
5459 }
5460
5461 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5462 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5463                                      unsigned NonZeros, unsigned NumNonZero,
5464                                      unsigned NumZero, SelectionDAG &DAG,
5465                                      const X86Subtarget *Subtarget,
5466                                      const TargetLowering &TLI) {
5467   // We know there's at least one non-zero element
5468   unsigned FirstNonZeroIdx = 0;
5469   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5470   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5471          X86::isZeroNode(FirstNonZero)) {
5472     ++FirstNonZeroIdx;
5473     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5474   }
5475
5476   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5477       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5478     return SDValue();
5479
5480   SDValue V = FirstNonZero.getOperand(0);
5481   MVT VVT = V.getSimpleValueType();
5482   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5483     return SDValue();
5484
5485   unsigned FirstNonZeroDst =
5486       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5487   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5488   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5489   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5490
5491   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5492     SDValue Elem = Op.getOperand(Idx);
5493     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5494       continue;
5495
5496     // TODO: What else can be here? Deal with it.
5497     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5498       return SDValue();
5499
5500     // TODO: Some optimizations are still possible here
5501     // ex: Getting one element from a vector, and the rest from another.
5502     if (Elem.getOperand(0) != V)
5503       return SDValue();
5504
5505     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5506     if (Dst == Idx)
5507       ++CorrectIdx;
5508     else if (IncorrectIdx == -1U) {
5509       IncorrectIdx = Idx;
5510       IncorrectDst = Dst;
5511     } else
5512       // There was already one element with an incorrect index.
5513       // We can't optimize this case to an insertps.
5514       return SDValue();
5515   }
5516
5517   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5518     SDLoc dl(Op);
5519     EVT VT = Op.getSimpleValueType();
5520     unsigned ElementMoveMask = 0;
5521     if (IncorrectIdx == -1U)
5522       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5523     else
5524       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5525
5526     SDValue InsertpsMask =
5527         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5528     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5529   }
5530
5531   return SDValue();
5532 }
5533
5534 /// getVShift - Return a vector logical shift node.
5535 ///
5536 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5537                          unsigned NumBits, SelectionDAG &DAG,
5538                          const TargetLowering &TLI, SDLoc dl) {
5539   assert(VT.is128BitVector() && "Unknown type for VShift");
5540   EVT ShVT = MVT::v2i64;
5541   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5542   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5543   return DAG.getNode(ISD::BITCAST, dl, VT,
5544                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5545                              DAG.getConstant(NumBits,
5546                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5547 }
5548
5549 static SDValue
5550 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5551
5552   // Check if the scalar load can be widened into a vector load. And if
5553   // the address is "base + cst" see if the cst can be "absorbed" into
5554   // the shuffle mask.
5555   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5556     SDValue Ptr = LD->getBasePtr();
5557     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5558       return SDValue();
5559     EVT PVT = LD->getValueType(0);
5560     if (PVT != MVT::i32 && PVT != MVT::f32)
5561       return SDValue();
5562
5563     int FI = -1;
5564     int64_t Offset = 0;
5565     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5566       FI = FINode->getIndex();
5567       Offset = 0;
5568     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5569                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5570       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5571       Offset = Ptr.getConstantOperandVal(1);
5572       Ptr = Ptr.getOperand(0);
5573     } else {
5574       return SDValue();
5575     }
5576
5577     // FIXME: 256-bit vector instructions don't require a strict alignment,
5578     // improve this code to support it better.
5579     unsigned RequiredAlign = VT.getSizeInBits()/8;
5580     SDValue Chain = LD->getChain();
5581     // Make sure the stack object alignment is at least 16 or 32.
5582     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5583     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5584       if (MFI->isFixedObjectIndex(FI)) {
5585         // Can't change the alignment. FIXME: It's possible to compute
5586         // the exact stack offset and reference FI + adjust offset instead.
5587         // If someone *really* cares about this. That's the way to implement it.
5588         return SDValue();
5589       } else {
5590         MFI->setObjectAlignment(FI, RequiredAlign);
5591       }
5592     }
5593
5594     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5595     // Ptr + (Offset & ~15).
5596     if (Offset < 0)
5597       return SDValue();
5598     if ((Offset % RequiredAlign) & 3)
5599       return SDValue();
5600     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5601     if (StartOffset)
5602       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5603                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5604
5605     int EltNo = (Offset - StartOffset) >> 2;
5606     unsigned NumElems = VT.getVectorNumElements();
5607
5608     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5609     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5610                              LD->getPointerInfo().getWithOffset(StartOffset),
5611                              false, false, false, 0);
5612
5613     SmallVector<int, 8> Mask;
5614     for (unsigned i = 0; i != NumElems; ++i)
5615       Mask.push_back(EltNo);
5616
5617     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5618   }
5619
5620   return SDValue();
5621 }
5622
5623 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5624 /// vector of type 'VT', see if the elements can be replaced by a single large
5625 /// load which has the same value as a build_vector whose operands are 'elts'.
5626 ///
5627 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5628 ///
5629 /// FIXME: we'd also like to handle the case where the last elements are zero
5630 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5631 /// There's even a handy isZeroNode for that purpose.
5632 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5633                                         SDLoc &DL, SelectionDAG &DAG,
5634                                         bool isAfterLegalize) {
5635   EVT EltVT = VT.getVectorElementType();
5636   unsigned NumElems = Elts.size();
5637
5638   LoadSDNode *LDBase = nullptr;
5639   unsigned LastLoadedElt = -1U;
5640
5641   // For each element in the initializer, see if we've found a load or an undef.
5642   // If we don't find an initial load element, or later load elements are
5643   // non-consecutive, bail out.
5644   for (unsigned i = 0; i < NumElems; ++i) {
5645     SDValue Elt = Elts[i];
5646
5647     if (!Elt.getNode() ||
5648         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5649       return SDValue();
5650     if (!LDBase) {
5651       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5652         return SDValue();
5653       LDBase = cast<LoadSDNode>(Elt.getNode());
5654       LastLoadedElt = i;
5655       continue;
5656     }
5657     if (Elt.getOpcode() == ISD::UNDEF)
5658       continue;
5659
5660     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5661     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5662       return SDValue();
5663     LastLoadedElt = i;
5664   }
5665
5666   // If we have found an entire vector of loads and undefs, then return a large
5667   // load of the entire vector width starting at the base pointer.  If we found
5668   // consecutive loads for the low half, generate a vzext_load node.
5669   if (LastLoadedElt == NumElems - 1) {
5670
5671     if (isAfterLegalize &&
5672         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5673       return SDValue();
5674
5675     SDValue NewLd = SDValue();
5676
5677     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5678       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5679                           LDBase->getPointerInfo(),
5680                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5681                           LDBase->isInvariant(), 0);
5682     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5683                         LDBase->getPointerInfo(),
5684                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5685                         LDBase->isInvariant(), LDBase->getAlignment());
5686
5687     if (LDBase->hasAnyUseOfValue(1)) {
5688       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5689                                      SDValue(LDBase, 1),
5690                                      SDValue(NewLd.getNode(), 1));
5691       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5692       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5693                              SDValue(NewLd.getNode(), 1));
5694     }
5695
5696     return NewLd;
5697   }
5698   if (NumElems == 4 && LastLoadedElt == 1 &&
5699       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5700     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5701     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5702     SDValue ResNode =
5703         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5704                                 LDBase->getPointerInfo(),
5705                                 LDBase->getAlignment(),
5706                                 false/*isVolatile*/, true/*ReadMem*/,
5707                                 false/*WriteMem*/);
5708
5709     // Make sure the newly-created LOAD is in the same position as LDBase in
5710     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5711     // update uses of LDBase's output chain to use the TokenFactor.
5712     if (LDBase->hasAnyUseOfValue(1)) {
5713       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5714                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5715       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5716       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5717                              SDValue(ResNode.getNode(), 1));
5718     }
5719
5720     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5721   }
5722   return SDValue();
5723 }
5724
5725 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5726 /// to generate a splat value for the following cases:
5727 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5728 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5729 /// a scalar load, or a constant.
5730 /// The VBROADCAST node is returned when a pattern is found,
5731 /// or SDValue() otherwise.
5732 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5733                                     SelectionDAG &DAG) {
5734   if (!Subtarget->hasFp256())
5735     return SDValue();
5736
5737   MVT VT = Op.getSimpleValueType();
5738   SDLoc dl(Op);
5739
5740   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5741          "Unsupported vector type for broadcast.");
5742
5743   SDValue Ld;
5744   bool ConstSplatVal;
5745
5746   switch (Op.getOpcode()) {
5747     default:
5748       // Unknown pattern found.
5749       return SDValue();
5750
5751     case ISD::BUILD_VECTOR: {
5752       // The BUILD_VECTOR node must be a splat.
5753       if (!isSplatVector(Op.getNode()))
5754         return SDValue();
5755
5756       Ld = Op.getOperand(0);
5757       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5758                      Ld.getOpcode() == ISD::ConstantFP);
5759
5760       // The suspected load node has several users. Make sure that all
5761       // of its users are from the BUILD_VECTOR node.
5762       // Constants may have multiple users.
5763       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5764         return SDValue();
5765       break;
5766     }
5767
5768     case ISD::VECTOR_SHUFFLE: {
5769       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5770
5771       // Shuffles must have a splat mask where the first element is
5772       // broadcasted.
5773       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5774         return SDValue();
5775
5776       SDValue Sc = Op.getOperand(0);
5777       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5778           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5779
5780         if (!Subtarget->hasInt256())
5781           return SDValue();
5782
5783         // Use the register form of the broadcast instruction available on AVX2.
5784         if (VT.getSizeInBits() >= 256)
5785           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5786         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5787       }
5788
5789       Ld = Sc.getOperand(0);
5790       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5791                        Ld.getOpcode() == ISD::ConstantFP);
5792
5793       // The scalar_to_vector node and the suspected
5794       // load node must have exactly one user.
5795       // Constants may have multiple users.
5796
5797       // AVX-512 has register version of the broadcast
5798       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5799         Ld.getValueType().getSizeInBits() >= 32;
5800       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5801           !hasRegVer))
5802         return SDValue();
5803       break;
5804     }
5805   }
5806
5807   bool IsGE256 = (VT.getSizeInBits() >= 256);
5808
5809   // Handle the broadcasting a single constant scalar from the constant pool
5810   // into a vector. On Sandybridge it is still better to load a constant vector
5811   // from the constant pool and not to broadcast it from a scalar.
5812   if (ConstSplatVal && Subtarget->hasInt256()) {
5813     EVT CVT = Ld.getValueType();
5814     assert(!CVT.isVector() && "Must not broadcast a vector type");
5815     unsigned ScalarSize = CVT.getSizeInBits();
5816
5817     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5818       const Constant *C = nullptr;
5819       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5820         C = CI->getConstantIntValue();
5821       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5822         C = CF->getConstantFPValue();
5823
5824       assert(C && "Invalid constant type");
5825
5826       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5827       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5828       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5829       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5830                        MachinePointerInfo::getConstantPool(),
5831                        false, false, false, Alignment);
5832
5833       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5834     }
5835   }
5836
5837   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5838   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5839
5840   // Handle AVX2 in-register broadcasts.
5841   if (!IsLoad && Subtarget->hasInt256() &&
5842       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5843     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5844
5845   // The scalar source must be a normal load.
5846   if (!IsLoad)
5847     return SDValue();
5848
5849   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5850     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5851
5852   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5853   // double since there is no vbroadcastsd xmm
5854   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5855     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5856       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5857   }
5858
5859   // Unsupported broadcast.
5860   return SDValue();
5861 }
5862
5863 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5864 /// underlying vector and index.
5865 ///
5866 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5867 /// index.
5868 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5869                                          SDValue ExtIdx) {
5870   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5871   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5872     return Idx;
5873
5874   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5875   // lowered this:
5876   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5877   // to:
5878   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5879   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5880   //                           undef)
5881   //                       Constant<0>)
5882   // In this case the vector is the extract_subvector expression and the index
5883   // is 2, as specified by the shuffle.
5884   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5885   SDValue ShuffleVec = SVOp->getOperand(0);
5886   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5887   assert(ShuffleVecVT.getVectorElementType() ==
5888          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5889
5890   int ShuffleIdx = SVOp->getMaskElt(Idx);
5891   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5892     ExtractedFromVec = ShuffleVec;
5893     return ShuffleIdx;
5894   }
5895   return Idx;
5896 }
5897
5898 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5899   MVT VT = Op.getSimpleValueType();
5900
5901   // Skip if insert_vec_elt is not supported.
5902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5903   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5904     return SDValue();
5905
5906   SDLoc DL(Op);
5907   unsigned NumElems = Op.getNumOperands();
5908
5909   SDValue VecIn1;
5910   SDValue VecIn2;
5911   SmallVector<unsigned, 4> InsertIndices;
5912   SmallVector<int, 8> Mask(NumElems, -1);
5913
5914   for (unsigned i = 0; i != NumElems; ++i) {
5915     unsigned Opc = Op.getOperand(i).getOpcode();
5916
5917     if (Opc == ISD::UNDEF)
5918       continue;
5919
5920     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5921       // Quit if more than 1 elements need inserting.
5922       if (InsertIndices.size() > 1)
5923         return SDValue();
5924
5925       InsertIndices.push_back(i);
5926       continue;
5927     }
5928
5929     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5930     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5931     // Quit if non-constant index.
5932     if (!isa<ConstantSDNode>(ExtIdx))
5933       return SDValue();
5934     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5935
5936     // Quit if extracted from vector of different type.
5937     if (ExtractedFromVec.getValueType() != VT)
5938       return SDValue();
5939
5940     if (!VecIn1.getNode())
5941       VecIn1 = ExtractedFromVec;
5942     else if (VecIn1 != ExtractedFromVec) {
5943       if (!VecIn2.getNode())
5944         VecIn2 = ExtractedFromVec;
5945       else if (VecIn2 != ExtractedFromVec)
5946         // Quit if more than 2 vectors to shuffle
5947         return SDValue();
5948     }
5949
5950     if (ExtractedFromVec == VecIn1)
5951       Mask[i] = Idx;
5952     else if (ExtractedFromVec == VecIn2)
5953       Mask[i] = Idx + NumElems;
5954   }
5955
5956   if (!VecIn1.getNode())
5957     return SDValue();
5958
5959   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5960   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5961   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5962     unsigned Idx = InsertIndices[i];
5963     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5964                      DAG.getIntPtrConstant(Idx));
5965   }
5966
5967   return NV;
5968 }
5969
5970 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5971 SDValue
5972 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5973
5974   MVT VT = Op.getSimpleValueType();
5975   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5976          "Unexpected type in LowerBUILD_VECTORvXi1!");
5977
5978   SDLoc dl(Op);
5979   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5980     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5981     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5982     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5983   }
5984
5985   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5986     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5987     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5988     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5989   }
5990
5991   bool AllContants = true;
5992   uint64_t Immediate = 0;
5993   int NonConstIdx = -1;
5994   bool IsSplat = true;
5995   unsigned NumNonConsts = 0;
5996   unsigned NumConsts = 0;
5997   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5998     SDValue In = Op.getOperand(idx);
5999     if (In.getOpcode() == ISD::UNDEF)
6000       continue;
6001     if (!isa<ConstantSDNode>(In)) {
6002       AllContants = false;
6003       NonConstIdx = idx;
6004       NumNonConsts++;
6005     }
6006     else {
6007       NumConsts++;
6008       if (cast<ConstantSDNode>(In)->getZExtValue())
6009       Immediate |= (1ULL << idx);
6010     }
6011     if (In != Op.getOperand(0))
6012       IsSplat = false;
6013   }
6014
6015   if (AllContants) {
6016     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6017       DAG.getConstant(Immediate, MVT::i16));
6018     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6019                        DAG.getIntPtrConstant(0));
6020   }
6021
6022   if (NumNonConsts == 1 && NonConstIdx != 0) {
6023     SDValue DstVec;
6024     if (NumConsts) {
6025       SDValue VecAsImm = DAG.getConstant(Immediate,
6026                                          MVT::getIntegerVT(VT.getSizeInBits()));
6027       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6028     }
6029     else 
6030       DstVec = DAG.getUNDEF(VT);
6031     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6032                        Op.getOperand(NonConstIdx),
6033                        DAG.getIntPtrConstant(NonConstIdx));
6034   }
6035   if (!IsSplat && (NonConstIdx != 0))
6036     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6037   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6038   SDValue Select;
6039   if (IsSplat)
6040     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6041                           DAG.getConstant(-1, SelectVT),
6042                           DAG.getConstant(0, SelectVT));
6043   else
6044     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6045                          DAG.getConstant((Immediate | 1), SelectVT),
6046                          DAG.getConstant(Immediate, SelectVT));
6047   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6048 }
6049
6050 SDValue
6051 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6052   SDLoc dl(Op);
6053
6054   MVT VT = Op.getSimpleValueType();
6055   MVT ExtVT = VT.getVectorElementType();
6056   unsigned NumElems = Op.getNumOperands();
6057
6058   // Generate vectors for predicate vectors.
6059   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6060     return LowerBUILD_VECTORvXi1(Op, DAG);
6061
6062   // Vectors containing all zeros can be matched by pxor and xorps later
6063   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6064     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6065     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6066     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6067       return Op;
6068
6069     return getZeroVector(VT, Subtarget, DAG, dl);
6070   }
6071
6072   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6073   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6074   // vpcmpeqd on 256-bit vectors.
6075   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6076     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6077       return Op;
6078
6079     if (!VT.is512BitVector())
6080       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6081   }
6082
6083   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6084   if (Broadcast.getNode())
6085     return Broadcast;
6086
6087   unsigned EVTBits = ExtVT.getSizeInBits();
6088
6089   unsigned NumZero  = 0;
6090   unsigned NumNonZero = 0;
6091   unsigned NonZeros = 0;
6092   bool IsAllConstants = true;
6093   SmallSet<SDValue, 8> Values;
6094   for (unsigned i = 0; i < NumElems; ++i) {
6095     SDValue Elt = Op.getOperand(i);
6096     if (Elt.getOpcode() == ISD::UNDEF)
6097       continue;
6098     Values.insert(Elt);
6099     if (Elt.getOpcode() != ISD::Constant &&
6100         Elt.getOpcode() != ISD::ConstantFP)
6101       IsAllConstants = false;
6102     if (X86::isZeroNode(Elt))
6103       NumZero++;
6104     else {
6105       NonZeros |= (1 << i);
6106       NumNonZero++;
6107     }
6108   }
6109
6110   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6111   if (NumNonZero == 0)
6112     return DAG.getUNDEF(VT);
6113
6114   // Special case for single non-zero, non-undef, element.
6115   if (NumNonZero == 1) {
6116     unsigned Idx = countTrailingZeros(NonZeros);
6117     SDValue Item = Op.getOperand(Idx);
6118
6119     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6120     // the value are obviously zero, truncate the value to i32 and do the
6121     // insertion that way.  Only do this if the value is non-constant or if the
6122     // value is a constant being inserted into element 0.  It is cheaper to do
6123     // a constant pool load than it is to do a movd + shuffle.
6124     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6125         (!IsAllConstants || Idx == 0)) {
6126       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6127         // Handle SSE only.
6128         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6129         EVT VecVT = MVT::v4i32;
6130         unsigned VecElts = 4;
6131
6132         // Truncate the value (which may itself be a constant) to i32, and
6133         // convert it to a vector with movd (S2V+shuffle to zero extend).
6134         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6135         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6136         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6137
6138         // Now we have our 32-bit value zero extended in the low element of
6139         // a vector.  If Idx != 0, swizzle it into place.
6140         if (Idx != 0) {
6141           SmallVector<int, 4> Mask;
6142           Mask.push_back(Idx);
6143           for (unsigned i = 1; i != VecElts; ++i)
6144             Mask.push_back(i);
6145           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6146                                       &Mask[0]);
6147         }
6148         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6149       }
6150     }
6151
6152     // If we have a constant or non-constant insertion into the low element of
6153     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6154     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6155     // depending on what the source datatype is.
6156     if (Idx == 0) {
6157       if (NumZero == 0)
6158         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6159
6160       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6161           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6162         if (VT.is256BitVector() || VT.is512BitVector()) {
6163           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6164           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6165                              Item, DAG.getIntPtrConstant(0));
6166         }
6167         assert(VT.is128BitVector() && "Expected an SSE value type!");
6168         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6169         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6170         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6171       }
6172
6173       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6174         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6175         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6176         if (VT.is256BitVector()) {
6177           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6178           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6179         } else {
6180           assert(VT.is128BitVector() && "Expected an SSE value type!");
6181           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6182         }
6183         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6184       }
6185     }
6186
6187     // Is it a vector logical left shift?
6188     if (NumElems == 2 && Idx == 1 &&
6189         X86::isZeroNode(Op.getOperand(0)) &&
6190         !X86::isZeroNode(Op.getOperand(1))) {
6191       unsigned NumBits = VT.getSizeInBits();
6192       return getVShift(true, VT,
6193                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6194                                    VT, Op.getOperand(1)),
6195                        NumBits/2, DAG, *this, dl);
6196     }
6197
6198     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6199       return SDValue();
6200
6201     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6202     // is a non-constant being inserted into an element other than the low one,
6203     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6204     // movd/movss) to move this into the low element, then shuffle it into
6205     // place.
6206     if (EVTBits == 32) {
6207       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6208
6209       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6210       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6211       SmallVector<int, 8> MaskVec;
6212       for (unsigned i = 0; i != NumElems; ++i)
6213         MaskVec.push_back(i == Idx ? 0 : 1);
6214       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6215     }
6216   }
6217
6218   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6219   if (Values.size() == 1) {
6220     if (EVTBits == 32) {
6221       // Instead of a shuffle like this:
6222       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6223       // Check if it's possible to issue this instead.
6224       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6225       unsigned Idx = countTrailingZeros(NonZeros);
6226       SDValue Item = Op.getOperand(Idx);
6227       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6228         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6229     }
6230     return SDValue();
6231   }
6232
6233   // A vector full of immediates; various special cases are already
6234   // handled, so this is best done with a single constant-pool load.
6235   if (IsAllConstants)
6236     return SDValue();
6237
6238   // For AVX-length vectors, build the individual 128-bit pieces and use
6239   // shuffles to put them in place.
6240   if (VT.is256BitVector() || VT.is512BitVector()) {
6241     SmallVector<SDValue, 64> V;
6242     for (unsigned i = 0; i != NumElems; ++i)
6243       V.push_back(Op.getOperand(i));
6244
6245     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6246
6247     // Build both the lower and upper subvector.
6248     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6249                                 makeArrayRef(&V[0], NumElems/2));
6250     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6251                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6252
6253     // Recreate the wider vector with the lower and upper part.
6254     if (VT.is256BitVector())
6255       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6256     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6257   }
6258
6259   // Let legalizer expand 2-wide build_vectors.
6260   if (EVTBits == 64) {
6261     if (NumNonZero == 1) {
6262       // One half is zero or undef.
6263       unsigned Idx = countTrailingZeros(NonZeros);
6264       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6265                                  Op.getOperand(Idx));
6266       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6267     }
6268     return SDValue();
6269   }
6270
6271   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6272   if (EVTBits == 8 && NumElems == 16) {
6273     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6274                                         Subtarget, *this);
6275     if (V.getNode()) return V;
6276   }
6277
6278   if (EVTBits == 16 && NumElems == 8) {
6279     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6280                                       Subtarget, *this);
6281     if (V.getNode()) return V;
6282   }
6283
6284   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6285   if (EVTBits == 32 && NumElems == 4) {
6286     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6287                                       NumZero, DAG, Subtarget, *this);
6288     if (V.getNode())
6289       return V;
6290   }
6291
6292   // If element VT is == 32 bits, turn it into a number of shuffles.
6293   SmallVector<SDValue, 8> V(NumElems);
6294   if (NumElems == 4 && NumZero > 0) {
6295     for (unsigned i = 0; i < 4; ++i) {
6296       bool isZero = !(NonZeros & (1 << i));
6297       if (isZero)
6298         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6299       else
6300         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6301     }
6302
6303     for (unsigned i = 0; i < 2; ++i) {
6304       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6305         default: break;
6306         case 0:
6307           V[i] = V[i*2];  // Must be a zero vector.
6308           break;
6309         case 1:
6310           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6311           break;
6312         case 2:
6313           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6314           break;
6315         case 3:
6316           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6317           break;
6318       }
6319     }
6320
6321     bool Reverse1 = (NonZeros & 0x3) == 2;
6322     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6323     int MaskVec[] = {
6324       Reverse1 ? 1 : 0,
6325       Reverse1 ? 0 : 1,
6326       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6327       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6328     };
6329     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6330   }
6331
6332   if (Values.size() > 1 && VT.is128BitVector()) {
6333     // Check for a build vector of consecutive loads.
6334     for (unsigned i = 0; i < NumElems; ++i)
6335       V[i] = Op.getOperand(i);
6336
6337     // Check for elements which are consecutive loads.
6338     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6339     if (LD.getNode())
6340       return LD;
6341
6342     // Check for a build vector from mostly shuffle plus few inserting.
6343     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6344     if (Sh.getNode())
6345       return Sh;
6346
6347     // For SSE 4.1, use insertps to put the high elements into the low element.
6348     if (getSubtarget()->hasSSE41()) {
6349       SDValue Result;
6350       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6351         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6352       else
6353         Result = DAG.getUNDEF(VT);
6354
6355       for (unsigned i = 1; i < NumElems; ++i) {
6356         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6357         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6358                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6359       }
6360       return Result;
6361     }
6362
6363     // Otherwise, expand into a number of unpckl*, start by extending each of
6364     // our (non-undef) elements to the full vector width with the element in the
6365     // bottom slot of the vector (which generates no code for SSE).
6366     for (unsigned i = 0; i < NumElems; ++i) {
6367       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6368         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6369       else
6370         V[i] = DAG.getUNDEF(VT);
6371     }
6372
6373     // Next, we iteratively mix elements, e.g. for v4f32:
6374     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6375     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6376     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6377     unsigned EltStride = NumElems >> 1;
6378     while (EltStride != 0) {
6379       for (unsigned i = 0; i < EltStride; ++i) {
6380         // If V[i+EltStride] is undef and this is the first round of mixing,
6381         // then it is safe to just drop this shuffle: V[i] is already in the
6382         // right place, the one element (since it's the first round) being
6383         // inserted as undef can be dropped.  This isn't safe for successive
6384         // rounds because they will permute elements within both vectors.
6385         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6386             EltStride == NumElems/2)
6387           continue;
6388
6389         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6390       }
6391       EltStride >>= 1;
6392     }
6393     return V[0];
6394   }
6395   return SDValue();
6396 }
6397
6398 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6399 // to create 256-bit vectors from two other 128-bit ones.
6400 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6401   SDLoc dl(Op);
6402   MVT ResVT = Op.getSimpleValueType();
6403
6404   assert((ResVT.is256BitVector() ||
6405           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6406
6407   SDValue V1 = Op.getOperand(0);
6408   SDValue V2 = Op.getOperand(1);
6409   unsigned NumElems = ResVT.getVectorNumElements();
6410   if(ResVT.is256BitVector())
6411     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6412
6413   if (Op.getNumOperands() == 4) {
6414     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6415                                 ResVT.getVectorNumElements()/2);
6416     SDValue V3 = Op.getOperand(2);
6417     SDValue V4 = Op.getOperand(3);
6418     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6419       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6420   }
6421   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6422 }
6423
6424 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6425   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6426   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6427          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6428           Op.getNumOperands() == 4)));
6429
6430   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6431   // from two other 128-bit ones.
6432
6433   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6434   return LowerAVXCONCAT_VECTORS(Op, DAG);
6435 }
6436
6437 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6438                         bool hasInt256, unsigned *MaskOut = nullptr) {
6439   MVT EltVT = VT.getVectorElementType();
6440
6441   // There is no blend with immediate in AVX-512.
6442   if (VT.is512BitVector())
6443     return false;
6444
6445   if (!hasSSE41 || EltVT == MVT::i8)
6446     return false;
6447   if (!hasInt256 && VT == MVT::v16i16)
6448     return false;
6449
6450   unsigned MaskValue = 0;
6451   unsigned NumElems = VT.getVectorNumElements();
6452   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6453   unsigned NumLanes = (NumElems - 1) / 8 + 1;
6454   unsigned NumElemsInLane = NumElems / NumLanes;
6455
6456   // Blend for v16i16 should be symetric for the both lanes.
6457   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6458
6459     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6460     int EltIdx = MaskVals[i];
6461
6462     if ((EltIdx < 0 || EltIdx == (int)i) &&
6463         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6464       continue;
6465
6466     if (((unsigned)EltIdx == (i + NumElems)) &&
6467         (SndLaneEltIdx < 0 ||
6468          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6469       MaskValue |= (1 << i);
6470     else
6471       return false;
6472   }
6473
6474   if (MaskOut)
6475     *MaskOut = MaskValue;
6476   return true;
6477 }
6478
6479 // Try to lower a shuffle node into a simple blend instruction.
6480 // This function assumes isBlendMask returns true for this
6481 // SuffleVectorSDNode
6482 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6483                                           unsigned MaskValue,
6484                                           const X86Subtarget *Subtarget,
6485                                           SelectionDAG &DAG) {
6486   MVT VT = SVOp->getSimpleValueType(0);
6487   MVT EltVT = VT.getVectorElementType();
6488   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6489                      Subtarget->hasInt256() && "Trying to lower a "
6490                                                "VECTOR_SHUFFLE to a Blend but "
6491                                                "with the wrong mask"));
6492   SDValue V1 = SVOp->getOperand(0);
6493   SDValue V2 = SVOp->getOperand(1);
6494   SDLoc dl(SVOp);
6495   unsigned NumElems = VT.getVectorNumElements();
6496
6497   // Convert i32 vectors to floating point if it is not AVX2.
6498   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6499   MVT BlendVT = VT;
6500   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6501     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6502                                NumElems);
6503     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6504     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6505   }
6506
6507   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6508                             DAG.getConstant(MaskValue, MVT::i32));
6509   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6510 }
6511
6512 /// In vector type \p VT, return true if the element at index \p InputIdx
6513 /// falls on a different 128-bit lane than \p OutputIdx.
6514 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6515                                      unsigned OutputIdx) {
6516   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6517   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6518 }
6519
6520 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6521 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6522 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6523 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6524 /// zero.
6525 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6526                          SelectionDAG &DAG) {
6527   MVT VT = V1.getSimpleValueType();
6528   assert(VT.is128BitVector() || VT.is256BitVector());
6529
6530   MVT EltVT = VT.getVectorElementType();
6531   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6532   unsigned NumElts = VT.getVectorNumElements();
6533
6534   SmallVector<SDValue, 32> PshufbMask;
6535   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6536     int InputIdx = MaskVals[OutputIdx];
6537     unsigned InputByteIdx;
6538
6539     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6540       InputByteIdx = 0x80;
6541     else {
6542       // Cross lane is not allowed.
6543       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6544         return SDValue();
6545       InputByteIdx = InputIdx * EltSizeInBytes;
6546       // Index is an byte offset within the 128-bit lane.
6547       InputByteIdx &= 0xf;
6548     }
6549
6550     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6551       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6552       if (InputByteIdx != 0x80)
6553         ++InputByteIdx;
6554     }
6555   }
6556
6557   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6558   if (ShufVT != VT)
6559     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6560   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6561                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6562 }
6563
6564 // v8i16 shuffles - Prefer shuffles in the following order:
6565 // 1. [all]   pshuflw, pshufhw, optional move
6566 // 2. [ssse3] 1 x pshufb
6567 // 3. [ssse3] 2 x pshufb + 1 x por
6568 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6569 static SDValue
6570 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6571                          SelectionDAG &DAG) {
6572   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6573   SDValue V1 = SVOp->getOperand(0);
6574   SDValue V2 = SVOp->getOperand(1);
6575   SDLoc dl(SVOp);
6576   SmallVector<int, 8> MaskVals;
6577
6578   // Determine if more than 1 of the words in each of the low and high quadwords
6579   // of the result come from the same quadword of one of the two inputs.  Undef
6580   // mask values count as coming from any quadword, for better codegen.
6581   //
6582   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6583   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6584   unsigned LoQuad[] = { 0, 0, 0, 0 };
6585   unsigned HiQuad[] = { 0, 0, 0, 0 };
6586   // Indices of quads used.
6587   std::bitset<4> InputQuads;
6588   for (unsigned i = 0; i < 8; ++i) {
6589     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6590     int EltIdx = SVOp->getMaskElt(i);
6591     MaskVals.push_back(EltIdx);
6592     if (EltIdx < 0) {
6593       ++Quad[0];
6594       ++Quad[1];
6595       ++Quad[2];
6596       ++Quad[3];
6597       continue;
6598     }
6599     ++Quad[EltIdx / 4];
6600     InputQuads.set(EltIdx / 4);
6601   }
6602
6603   int BestLoQuad = -1;
6604   unsigned MaxQuad = 1;
6605   for (unsigned i = 0; i < 4; ++i) {
6606     if (LoQuad[i] > MaxQuad) {
6607       BestLoQuad = i;
6608       MaxQuad = LoQuad[i];
6609     }
6610   }
6611
6612   int BestHiQuad = -1;
6613   MaxQuad = 1;
6614   for (unsigned i = 0; i < 4; ++i) {
6615     if (HiQuad[i] > MaxQuad) {
6616       BestHiQuad = i;
6617       MaxQuad = HiQuad[i];
6618     }
6619   }
6620
6621   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6622   // of the two input vectors, shuffle them into one input vector so only a
6623   // single pshufb instruction is necessary. If there are more than 2 input
6624   // quads, disable the next transformation since it does not help SSSE3.
6625   bool V1Used = InputQuads[0] || InputQuads[1];
6626   bool V2Used = InputQuads[2] || InputQuads[3];
6627   if (Subtarget->hasSSSE3()) {
6628     if (InputQuads.count() == 2 && V1Used && V2Used) {
6629       BestLoQuad = InputQuads[0] ? 0 : 1;
6630       BestHiQuad = InputQuads[2] ? 2 : 3;
6631     }
6632     if (InputQuads.count() > 2) {
6633       BestLoQuad = -1;
6634       BestHiQuad = -1;
6635     }
6636   }
6637
6638   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6639   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6640   // words from all 4 input quadwords.
6641   SDValue NewV;
6642   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6643     int MaskV[] = {
6644       BestLoQuad < 0 ? 0 : BestLoQuad,
6645       BestHiQuad < 0 ? 1 : BestHiQuad
6646     };
6647     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6648                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6649                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6650     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6651
6652     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6653     // source words for the shuffle, to aid later transformations.
6654     bool AllWordsInNewV = true;
6655     bool InOrder[2] = { true, true };
6656     for (unsigned i = 0; i != 8; ++i) {
6657       int idx = MaskVals[i];
6658       if (idx != (int)i)
6659         InOrder[i/4] = false;
6660       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6661         continue;
6662       AllWordsInNewV = false;
6663       break;
6664     }
6665
6666     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6667     if (AllWordsInNewV) {
6668       for (int i = 0; i != 8; ++i) {
6669         int idx = MaskVals[i];
6670         if (idx < 0)
6671           continue;
6672         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6673         if ((idx != i) && idx < 4)
6674           pshufhw = false;
6675         if ((idx != i) && idx > 3)
6676           pshuflw = false;
6677       }
6678       V1 = NewV;
6679       V2Used = false;
6680       BestLoQuad = 0;
6681       BestHiQuad = 1;
6682     }
6683
6684     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6685     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6686     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6687       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6688       unsigned TargetMask = 0;
6689       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6690                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6691       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6692       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6693                              getShufflePSHUFLWImmediate(SVOp);
6694       V1 = NewV.getOperand(0);
6695       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6696     }
6697   }
6698
6699   // Promote splats to a larger type which usually leads to more efficient code.
6700   // FIXME: Is this true if pshufb is available?
6701   if (SVOp->isSplat())
6702     return PromoteSplat(SVOp, DAG);
6703
6704   // If we have SSSE3, and all words of the result are from 1 input vector,
6705   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6706   // is present, fall back to case 4.
6707   if (Subtarget->hasSSSE3()) {
6708     SmallVector<SDValue,16> pshufbMask;
6709
6710     // If we have elements from both input vectors, set the high bit of the
6711     // shuffle mask element to zero out elements that come from V2 in the V1
6712     // mask, and elements that come from V1 in the V2 mask, so that the two
6713     // results can be OR'd together.
6714     bool TwoInputs = V1Used && V2Used;
6715     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6716     if (!TwoInputs)
6717       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6718
6719     // Calculate the shuffle mask for the second input, shuffle it, and
6720     // OR it with the first shuffled input.
6721     CommuteVectorShuffleMask(MaskVals, 8);
6722     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6723     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6724     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6725   }
6726
6727   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6728   // and update MaskVals with new element order.
6729   std::bitset<8> InOrder;
6730   if (BestLoQuad >= 0) {
6731     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6732     for (int i = 0; i != 4; ++i) {
6733       int idx = MaskVals[i];
6734       if (idx < 0) {
6735         InOrder.set(i);
6736       } else if ((idx / 4) == BestLoQuad) {
6737         MaskV[i] = idx & 3;
6738         InOrder.set(i);
6739       }
6740     }
6741     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6742                                 &MaskV[0]);
6743
6744     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6745       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6746       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6747                                   NewV.getOperand(0),
6748                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6749     }
6750   }
6751
6752   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6753   // and update MaskVals with the new element order.
6754   if (BestHiQuad >= 0) {
6755     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6756     for (unsigned i = 4; i != 8; ++i) {
6757       int idx = MaskVals[i];
6758       if (idx < 0) {
6759         InOrder.set(i);
6760       } else if ((idx / 4) == BestHiQuad) {
6761         MaskV[i] = (idx & 3) + 4;
6762         InOrder.set(i);
6763       }
6764     }
6765     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6766                                 &MaskV[0]);
6767
6768     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6769       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6770       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6771                                   NewV.getOperand(0),
6772                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6773     }
6774   }
6775
6776   // In case BestHi & BestLo were both -1, which means each quadword has a word
6777   // from each of the four input quadwords, calculate the InOrder bitvector now
6778   // before falling through to the insert/extract cleanup.
6779   if (BestLoQuad == -1 && BestHiQuad == -1) {
6780     NewV = V1;
6781     for (int i = 0; i != 8; ++i)
6782       if (MaskVals[i] < 0 || MaskVals[i] == i)
6783         InOrder.set(i);
6784   }
6785
6786   // The other elements are put in the right place using pextrw and pinsrw.
6787   for (unsigned i = 0; i != 8; ++i) {
6788     if (InOrder[i])
6789       continue;
6790     int EltIdx = MaskVals[i];
6791     if (EltIdx < 0)
6792       continue;
6793     SDValue ExtOp = (EltIdx < 8) ?
6794       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6795                   DAG.getIntPtrConstant(EltIdx)) :
6796       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6797                   DAG.getIntPtrConstant(EltIdx - 8));
6798     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6799                        DAG.getIntPtrConstant(i));
6800   }
6801   return NewV;
6802 }
6803
6804 /// \brief v16i16 shuffles
6805 ///
6806 /// FIXME: We only support generation of a single pshufb currently.  We can
6807 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6808 /// well (e.g 2 x pshufb + 1 x por).
6809 static SDValue
6810 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6811   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6812   SDValue V1 = SVOp->getOperand(0);
6813   SDValue V2 = SVOp->getOperand(1);
6814   SDLoc dl(SVOp);
6815
6816   if (V2.getOpcode() != ISD::UNDEF)
6817     return SDValue();
6818
6819   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6820   return getPSHUFB(MaskVals, V1, dl, DAG);
6821 }
6822
6823 // v16i8 shuffles - Prefer shuffles in the following order:
6824 // 1. [ssse3] 1 x pshufb
6825 // 2. [ssse3] 2 x pshufb + 1 x por
6826 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6827 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6828                                         const X86Subtarget* Subtarget,
6829                                         SelectionDAG &DAG) {
6830   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6831   SDValue V1 = SVOp->getOperand(0);
6832   SDValue V2 = SVOp->getOperand(1);
6833   SDLoc dl(SVOp);
6834   ArrayRef<int> MaskVals = SVOp->getMask();
6835
6836   // Promote splats to a larger type which usually leads to more efficient code.
6837   // FIXME: Is this true if pshufb is available?
6838   if (SVOp->isSplat())
6839     return PromoteSplat(SVOp, DAG);
6840
6841   // If we have SSSE3, case 1 is generated when all result bytes come from
6842   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6843   // present, fall back to case 3.
6844
6845   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6846   if (Subtarget->hasSSSE3()) {
6847     SmallVector<SDValue,16> pshufbMask;
6848
6849     // If all result elements are from one input vector, then only translate
6850     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6851     //
6852     // Otherwise, we have elements from both input vectors, and must zero out
6853     // elements that come from V2 in the first mask, and V1 in the second mask
6854     // so that we can OR them together.
6855     for (unsigned i = 0; i != 16; ++i) {
6856       int EltIdx = MaskVals[i];
6857       if (EltIdx < 0 || EltIdx >= 16)
6858         EltIdx = 0x80;
6859       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6860     }
6861     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6862                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6863                                  MVT::v16i8, pshufbMask));
6864
6865     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6866     // the 2nd operand if it's undefined or zero.
6867     if (V2.getOpcode() == ISD::UNDEF ||
6868         ISD::isBuildVectorAllZeros(V2.getNode()))
6869       return V1;
6870
6871     // Calculate the shuffle mask for the second input, shuffle it, and
6872     // OR it with the first shuffled input.
6873     pshufbMask.clear();
6874     for (unsigned i = 0; i != 16; ++i) {
6875       int EltIdx = MaskVals[i];
6876       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6877       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6878     }
6879     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6880                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6881                                  MVT::v16i8, pshufbMask));
6882     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6883   }
6884
6885   // No SSSE3 - Calculate in place words and then fix all out of place words
6886   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6887   // the 16 different words that comprise the two doublequadword input vectors.
6888   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6889   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6890   SDValue NewV = V1;
6891   for (int i = 0; i != 8; ++i) {
6892     int Elt0 = MaskVals[i*2];
6893     int Elt1 = MaskVals[i*2+1];
6894
6895     // This word of the result is all undef, skip it.
6896     if (Elt0 < 0 && Elt1 < 0)
6897       continue;
6898
6899     // This word of the result is already in the correct place, skip it.
6900     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6901       continue;
6902
6903     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6904     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6905     SDValue InsElt;
6906
6907     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6908     // using a single extract together, load it and store it.
6909     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6910       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6911                            DAG.getIntPtrConstant(Elt1 / 2));
6912       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6913                         DAG.getIntPtrConstant(i));
6914       continue;
6915     }
6916
6917     // If Elt1 is defined, extract it from the appropriate source.  If the
6918     // source byte is not also odd, shift the extracted word left 8 bits
6919     // otherwise clear the bottom 8 bits if we need to do an or.
6920     if (Elt1 >= 0) {
6921       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6922                            DAG.getIntPtrConstant(Elt1 / 2));
6923       if ((Elt1 & 1) == 0)
6924         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6925                              DAG.getConstant(8,
6926                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6927       else if (Elt0 >= 0)
6928         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6929                              DAG.getConstant(0xFF00, MVT::i16));
6930     }
6931     // If Elt0 is defined, extract it from the appropriate source.  If the
6932     // source byte is not also even, shift the extracted word right 8 bits. If
6933     // Elt1 was also defined, OR the extracted values together before
6934     // inserting them in the result.
6935     if (Elt0 >= 0) {
6936       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6937                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6938       if ((Elt0 & 1) != 0)
6939         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6940                               DAG.getConstant(8,
6941                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6942       else if (Elt1 >= 0)
6943         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6944                              DAG.getConstant(0x00FF, MVT::i16));
6945       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6946                          : InsElt0;
6947     }
6948     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6949                        DAG.getIntPtrConstant(i));
6950   }
6951   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6952 }
6953
6954 // v32i8 shuffles - Translate to VPSHUFB if possible.
6955 static
6956 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6957                                  const X86Subtarget *Subtarget,
6958                                  SelectionDAG &DAG) {
6959   MVT VT = SVOp->getSimpleValueType(0);
6960   SDValue V1 = SVOp->getOperand(0);
6961   SDValue V2 = SVOp->getOperand(1);
6962   SDLoc dl(SVOp);
6963   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6964
6965   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6966   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6967   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6968
6969   // VPSHUFB may be generated if
6970   // (1) one of input vector is undefined or zeroinitializer.
6971   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6972   // And (2) the mask indexes don't cross the 128-bit lane.
6973   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6974       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6975     return SDValue();
6976
6977   if (V1IsAllZero && !V2IsAllZero) {
6978     CommuteVectorShuffleMask(MaskVals, 32);
6979     V1 = V2;
6980   }
6981   return getPSHUFB(MaskVals, V1, dl, DAG);
6982 }
6983
6984 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6985 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6986 /// done when every pair / quad of shuffle mask elements point to elements in
6987 /// the right sequence. e.g.
6988 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6989 static
6990 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6991                                  SelectionDAG &DAG) {
6992   MVT VT = SVOp->getSimpleValueType(0);
6993   SDLoc dl(SVOp);
6994   unsigned NumElems = VT.getVectorNumElements();
6995   MVT NewVT;
6996   unsigned Scale;
6997   switch (VT.SimpleTy) {
6998   default: llvm_unreachable("Unexpected!");
6999   case MVT::v2i64:
7000   case MVT::v2f64:
7001            return SDValue(SVOp, 0);
7002   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
7003   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
7004   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
7005   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
7006   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7007   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
7008   }
7009
7010   SmallVector<int, 8> MaskVec;
7011   for (unsigned i = 0; i != NumElems; i += Scale) {
7012     int StartIdx = -1;
7013     for (unsigned j = 0; j != Scale; ++j) {
7014       int EltIdx = SVOp->getMaskElt(i+j);
7015       if (EltIdx < 0)
7016         continue;
7017       if (StartIdx < 0)
7018         StartIdx = (EltIdx / Scale);
7019       if (EltIdx != (int)(StartIdx*Scale + j))
7020         return SDValue();
7021     }
7022     MaskVec.push_back(StartIdx);
7023   }
7024
7025   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7026   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7027   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7028 }
7029
7030 /// getVZextMovL - Return a zero-extending vector move low node.
7031 ///
7032 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7033                             SDValue SrcOp, SelectionDAG &DAG,
7034                             const X86Subtarget *Subtarget, SDLoc dl) {
7035   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7036     LoadSDNode *LD = nullptr;
7037     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7038       LD = dyn_cast<LoadSDNode>(SrcOp);
7039     if (!LD) {
7040       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7041       // instead.
7042       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7043       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7044           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7045           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7046           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7047         // PR2108
7048         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7049         return DAG.getNode(ISD::BITCAST, dl, VT,
7050                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7051                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7052                                                    OpVT,
7053                                                    SrcOp.getOperand(0)
7054                                                           .getOperand(0))));
7055       }
7056     }
7057   }
7058
7059   return DAG.getNode(ISD::BITCAST, dl, VT,
7060                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7061                                  DAG.getNode(ISD::BITCAST, dl,
7062                                              OpVT, SrcOp)));
7063 }
7064
7065 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7066 /// which could not be matched by any known target speficic shuffle
7067 static SDValue
7068 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7069
7070   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7071   if (NewOp.getNode())
7072     return NewOp;
7073
7074   MVT VT = SVOp->getSimpleValueType(0);
7075
7076   unsigned NumElems = VT.getVectorNumElements();
7077   unsigned NumLaneElems = NumElems / 2;
7078
7079   SDLoc dl(SVOp);
7080   MVT EltVT = VT.getVectorElementType();
7081   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7082   SDValue Output[2];
7083
7084   SmallVector<int, 16> Mask;
7085   for (unsigned l = 0; l < 2; ++l) {
7086     // Build a shuffle mask for the output, discovering on the fly which
7087     // input vectors to use as shuffle operands (recorded in InputUsed).
7088     // If building a suitable shuffle vector proves too hard, then bail
7089     // out with UseBuildVector set.
7090     bool UseBuildVector = false;
7091     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7092     unsigned LaneStart = l * NumLaneElems;
7093     for (unsigned i = 0; i != NumLaneElems; ++i) {
7094       // The mask element.  This indexes into the input.
7095       int Idx = SVOp->getMaskElt(i+LaneStart);
7096       if (Idx < 0) {
7097         // the mask element does not index into any input vector.
7098         Mask.push_back(-1);
7099         continue;
7100       }
7101
7102       // The input vector this mask element indexes into.
7103       int Input = Idx / NumLaneElems;
7104
7105       // Turn the index into an offset from the start of the input vector.
7106       Idx -= Input * NumLaneElems;
7107
7108       // Find or create a shuffle vector operand to hold this input.
7109       unsigned OpNo;
7110       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7111         if (InputUsed[OpNo] == Input)
7112           // This input vector is already an operand.
7113           break;
7114         if (InputUsed[OpNo] < 0) {
7115           // Create a new operand for this input vector.
7116           InputUsed[OpNo] = Input;
7117           break;
7118         }
7119       }
7120
7121       if (OpNo >= array_lengthof(InputUsed)) {
7122         // More than two input vectors used!  Give up on trying to create a
7123         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7124         UseBuildVector = true;
7125         break;
7126       }
7127
7128       // Add the mask index for the new shuffle vector.
7129       Mask.push_back(Idx + OpNo * NumLaneElems);
7130     }
7131
7132     if (UseBuildVector) {
7133       SmallVector<SDValue, 16> SVOps;
7134       for (unsigned i = 0; i != NumLaneElems; ++i) {
7135         // The mask element.  This indexes into the input.
7136         int Idx = SVOp->getMaskElt(i+LaneStart);
7137         if (Idx < 0) {
7138           SVOps.push_back(DAG.getUNDEF(EltVT));
7139           continue;
7140         }
7141
7142         // The input vector this mask element indexes into.
7143         int Input = Idx / NumElems;
7144
7145         // Turn the index into an offset from the start of the input vector.
7146         Idx -= Input * NumElems;
7147
7148         // Extract the vector element by hand.
7149         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7150                                     SVOp->getOperand(Input),
7151                                     DAG.getIntPtrConstant(Idx)));
7152       }
7153
7154       // Construct the output using a BUILD_VECTOR.
7155       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7156     } else if (InputUsed[0] < 0) {
7157       // No input vectors were used! The result is undefined.
7158       Output[l] = DAG.getUNDEF(NVT);
7159     } else {
7160       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7161                                         (InputUsed[0] % 2) * NumLaneElems,
7162                                         DAG, dl);
7163       // If only one input was used, use an undefined vector for the other.
7164       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7165         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7166                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7167       // At least one input vector was used. Create a new shuffle vector.
7168       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7169     }
7170
7171     Mask.clear();
7172   }
7173
7174   // Concatenate the result back
7175   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7176 }
7177
7178 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7179 /// 4 elements, and match them with several different shuffle types.
7180 static SDValue
7181 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7182   SDValue V1 = SVOp->getOperand(0);
7183   SDValue V2 = SVOp->getOperand(1);
7184   SDLoc dl(SVOp);
7185   MVT VT = SVOp->getSimpleValueType(0);
7186
7187   assert(VT.is128BitVector() && "Unsupported vector size");
7188
7189   std::pair<int, int> Locs[4];
7190   int Mask1[] = { -1, -1, -1, -1 };
7191   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7192
7193   unsigned NumHi = 0;
7194   unsigned NumLo = 0;
7195   for (unsigned i = 0; i != 4; ++i) {
7196     int Idx = PermMask[i];
7197     if (Idx < 0) {
7198       Locs[i] = std::make_pair(-1, -1);
7199     } else {
7200       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7201       if (Idx < 4) {
7202         Locs[i] = std::make_pair(0, NumLo);
7203         Mask1[NumLo] = Idx;
7204         NumLo++;
7205       } else {
7206         Locs[i] = std::make_pair(1, NumHi);
7207         if (2+NumHi < 4)
7208           Mask1[2+NumHi] = Idx;
7209         NumHi++;
7210       }
7211     }
7212   }
7213
7214   if (NumLo <= 2 && NumHi <= 2) {
7215     // If no more than two elements come from either vector. This can be
7216     // implemented with two shuffles. First shuffle gather the elements.
7217     // The second shuffle, which takes the first shuffle as both of its
7218     // vector operands, put the elements into the right order.
7219     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7220
7221     int Mask2[] = { -1, -1, -1, -1 };
7222
7223     for (unsigned i = 0; i != 4; ++i)
7224       if (Locs[i].first != -1) {
7225         unsigned Idx = (i < 2) ? 0 : 4;
7226         Idx += Locs[i].first * 2 + Locs[i].second;
7227         Mask2[i] = Idx;
7228       }
7229
7230     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7231   }
7232
7233   if (NumLo == 3 || NumHi == 3) {
7234     // Otherwise, we must have three elements from one vector, call it X, and
7235     // one element from the other, call it Y.  First, use a shufps to build an
7236     // intermediate vector with the one element from Y and the element from X
7237     // that will be in the same half in the final destination (the indexes don't
7238     // matter). Then, use a shufps to build the final vector, taking the half
7239     // containing the element from Y from the intermediate, and the other half
7240     // from X.
7241     if (NumHi == 3) {
7242       // Normalize it so the 3 elements come from V1.
7243       CommuteVectorShuffleMask(PermMask, 4);
7244       std::swap(V1, V2);
7245     }
7246
7247     // Find the element from V2.
7248     unsigned HiIndex;
7249     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7250       int Val = PermMask[HiIndex];
7251       if (Val < 0)
7252         continue;
7253       if (Val >= 4)
7254         break;
7255     }
7256
7257     Mask1[0] = PermMask[HiIndex];
7258     Mask1[1] = -1;
7259     Mask1[2] = PermMask[HiIndex^1];
7260     Mask1[3] = -1;
7261     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7262
7263     if (HiIndex >= 2) {
7264       Mask1[0] = PermMask[0];
7265       Mask1[1] = PermMask[1];
7266       Mask1[2] = HiIndex & 1 ? 6 : 4;
7267       Mask1[3] = HiIndex & 1 ? 4 : 6;
7268       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7269     }
7270
7271     Mask1[0] = HiIndex & 1 ? 2 : 0;
7272     Mask1[1] = HiIndex & 1 ? 0 : 2;
7273     Mask1[2] = PermMask[2];
7274     Mask1[3] = PermMask[3];
7275     if (Mask1[2] >= 0)
7276       Mask1[2] += 4;
7277     if (Mask1[3] >= 0)
7278       Mask1[3] += 4;
7279     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7280   }
7281
7282   // Break it into (shuffle shuffle_hi, shuffle_lo).
7283   int LoMask[] = { -1, -1, -1, -1 };
7284   int HiMask[] = { -1, -1, -1, -1 };
7285
7286   int *MaskPtr = LoMask;
7287   unsigned MaskIdx = 0;
7288   unsigned LoIdx = 0;
7289   unsigned HiIdx = 2;
7290   for (unsigned i = 0; i != 4; ++i) {
7291     if (i == 2) {
7292       MaskPtr = HiMask;
7293       MaskIdx = 1;
7294       LoIdx = 0;
7295       HiIdx = 2;
7296     }
7297     int Idx = PermMask[i];
7298     if (Idx < 0) {
7299       Locs[i] = std::make_pair(-1, -1);
7300     } else if (Idx < 4) {
7301       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7302       MaskPtr[LoIdx] = Idx;
7303       LoIdx++;
7304     } else {
7305       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7306       MaskPtr[HiIdx] = Idx;
7307       HiIdx++;
7308     }
7309   }
7310
7311   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7312   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7313   int MaskOps[] = { -1, -1, -1, -1 };
7314   for (unsigned i = 0; i != 4; ++i)
7315     if (Locs[i].first != -1)
7316       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7317   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7318 }
7319
7320 static bool MayFoldVectorLoad(SDValue V) {
7321   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7322     V = V.getOperand(0);
7323
7324   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7325     V = V.getOperand(0);
7326   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7327       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7328     // BUILD_VECTOR (load), undef
7329     V = V.getOperand(0);
7330
7331   return MayFoldLoad(V);
7332 }
7333
7334 static
7335 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7336   MVT VT = Op.getSimpleValueType();
7337
7338   // Canonizalize to v2f64.
7339   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7340   return DAG.getNode(ISD::BITCAST, dl, VT,
7341                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7342                                           V1, DAG));
7343 }
7344
7345 static
7346 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7347                         bool HasSSE2) {
7348   SDValue V1 = Op.getOperand(0);
7349   SDValue V2 = Op.getOperand(1);
7350   MVT VT = Op.getSimpleValueType();
7351
7352   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7353
7354   if (HasSSE2 && VT == MVT::v2f64)
7355     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7356
7357   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7358   return DAG.getNode(ISD::BITCAST, dl, VT,
7359                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7360                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7361                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7362 }
7363
7364 static
7365 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7366   SDValue V1 = Op.getOperand(0);
7367   SDValue V2 = Op.getOperand(1);
7368   MVT VT = Op.getSimpleValueType();
7369
7370   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7371          "unsupported shuffle type");
7372
7373   if (V2.getOpcode() == ISD::UNDEF)
7374     V2 = V1;
7375
7376   // v4i32 or v4f32
7377   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7378 }
7379
7380 static
7381 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7382   SDValue V1 = Op.getOperand(0);
7383   SDValue V2 = Op.getOperand(1);
7384   MVT VT = Op.getSimpleValueType();
7385   unsigned NumElems = VT.getVectorNumElements();
7386
7387   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7388   // operand of these instructions is only memory, so check if there's a
7389   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7390   // same masks.
7391   bool CanFoldLoad = false;
7392
7393   // Trivial case, when V2 comes from a load.
7394   if (MayFoldVectorLoad(V2))
7395     CanFoldLoad = true;
7396
7397   // When V1 is a load, it can be folded later into a store in isel, example:
7398   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7399   //    turns into:
7400   //  (MOVLPSmr addr:$src1, VR128:$src2)
7401   // So, recognize this potential and also use MOVLPS or MOVLPD
7402   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7403     CanFoldLoad = true;
7404
7405   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7406   if (CanFoldLoad) {
7407     if (HasSSE2 && NumElems == 2)
7408       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7409
7410     if (NumElems == 4)
7411       // If we don't care about the second element, proceed to use movss.
7412       if (SVOp->getMaskElt(1) != -1)
7413         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7414   }
7415
7416   // movl and movlp will both match v2i64, but v2i64 is never matched by
7417   // movl earlier because we make it strict to avoid messing with the movlp load
7418   // folding logic (see the code above getMOVLP call). Match it here then,
7419   // this is horrible, but will stay like this until we move all shuffle
7420   // matching to x86 specific nodes. Note that for the 1st condition all
7421   // types are matched with movsd.
7422   if (HasSSE2) {
7423     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7424     // as to remove this logic from here, as much as possible
7425     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7426       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7427     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7428   }
7429
7430   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7431
7432   // Invert the operand order and use SHUFPS to match it.
7433   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7434                               getShuffleSHUFImmediate(SVOp), DAG);
7435 }
7436
7437 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7438                                          SelectionDAG &DAG) {
7439   SDLoc dl(Load);
7440   MVT VT = Load->getSimpleValueType(0);
7441   MVT EVT = VT.getVectorElementType();
7442   SDValue Addr = Load->getOperand(1);
7443   SDValue NewAddr = DAG.getNode(
7444       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7445       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7446
7447   SDValue NewLoad =
7448       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7449                   DAG.getMachineFunction().getMachineMemOperand(
7450                       Load->getMemOperand(), 0, EVT.getStoreSize()));
7451   return NewLoad;
7452 }
7453
7454 // It is only safe to call this function if isINSERTPSMask is true for
7455 // this shufflevector mask.
7456 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7457                            SelectionDAG &DAG) {
7458   // Generate an insertps instruction when inserting an f32 from memory onto a
7459   // v4f32 or when copying a member from one v4f32 to another.
7460   // We also use it for transferring i32 from one register to another,
7461   // since it simply copies the same bits.
7462   // If we're transferring an i32 from memory to a specific element in a
7463   // register, we output a generic DAG that will match the PINSRD
7464   // instruction.
7465   MVT VT = SVOp->getSimpleValueType(0);
7466   MVT EVT = VT.getVectorElementType();
7467   SDValue V1 = SVOp->getOperand(0);
7468   SDValue V2 = SVOp->getOperand(1);
7469   auto Mask = SVOp->getMask();
7470   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7471          "unsupported vector type for insertps/pinsrd");
7472
7473   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7474   auto FromV2Predicate = [](const int &i) { return i >= 4; };
7475   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7476
7477   SDValue From;
7478   SDValue To;
7479   unsigned DestIndex;
7480   if (FromV1 == 1) {
7481     From = V1;
7482     To = V2;
7483     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7484                 Mask.begin();
7485   } else {
7486     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7487            "More than one element from V1 and from V2, or no elements from one "
7488            "of the vectors. This case should not have returned true from "
7489            "isINSERTPSMask");
7490     From = V2;
7491     To = V1;
7492     DestIndex =
7493         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7494   }
7495
7496   if (MayFoldLoad(From)) {
7497     // Trivial case, when From comes from a load and is only used by the
7498     // shuffle. Make it use insertps from the vector that we need from that
7499     // load.
7500     SDValue NewLoad =
7501         NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7502     if (!NewLoad.getNode())
7503       return SDValue();
7504
7505     if (EVT == MVT::f32) {
7506       // Create this as a scalar to vector to match the instruction pattern.
7507       SDValue LoadScalarToVector =
7508           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7509       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7510       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7511                          InsertpsMask);
7512     } else { // EVT == MVT::i32
7513       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7514       // instruction, to match the PINSRD instruction, which loads an i32 to a
7515       // certain vector element.
7516       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7517                          DAG.getConstant(DestIndex, MVT::i32));
7518     }
7519   }
7520
7521   // Vector-element-to-vector
7522   unsigned SrcIndex = Mask[DestIndex] % 4;
7523   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7524   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7525 }
7526
7527 // Reduce a vector shuffle to zext.
7528 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7529                                     SelectionDAG &DAG) {
7530   // PMOVZX is only available from SSE41.
7531   if (!Subtarget->hasSSE41())
7532     return SDValue();
7533
7534   MVT VT = Op.getSimpleValueType();
7535
7536   // Only AVX2 support 256-bit vector integer extending.
7537   if (!Subtarget->hasInt256() && VT.is256BitVector())
7538     return SDValue();
7539
7540   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7541   SDLoc DL(Op);
7542   SDValue V1 = Op.getOperand(0);
7543   SDValue V2 = Op.getOperand(1);
7544   unsigned NumElems = VT.getVectorNumElements();
7545
7546   // Extending is an unary operation and the element type of the source vector
7547   // won't be equal to or larger than i64.
7548   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7549       VT.getVectorElementType() == MVT::i64)
7550     return SDValue();
7551
7552   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7553   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7554   while ((1U << Shift) < NumElems) {
7555     if (SVOp->getMaskElt(1U << Shift) == 1)
7556       break;
7557     Shift += 1;
7558     // The maximal ratio is 8, i.e. from i8 to i64.
7559     if (Shift > 3)
7560       return SDValue();
7561   }
7562
7563   // Check the shuffle mask.
7564   unsigned Mask = (1U << Shift) - 1;
7565   for (unsigned i = 0; i != NumElems; ++i) {
7566     int EltIdx = SVOp->getMaskElt(i);
7567     if ((i & Mask) != 0 && EltIdx != -1)
7568       return SDValue();
7569     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7570       return SDValue();
7571   }
7572
7573   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7574   MVT NeVT = MVT::getIntegerVT(NBits);
7575   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7576
7577   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7578     return SDValue();
7579
7580   // Simplify the operand as it's prepared to be fed into shuffle.
7581   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7582   if (V1.getOpcode() == ISD::BITCAST &&
7583       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7584       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7585       V1.getOperand(0).getOperand(0)
7586         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7587     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7588     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7589     ConstantSDNode *CIdx =
7590       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7591     // If it's foldable, i.e. normal load with single use, we will let code
7592     // selection to fold it. Otherwise, we will short the conversion sequence.
7593     if (CIdx && CIdx->getZExtValue() == 0 &&
7594         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7595       MVT FullVT = V.getSimpleValueType();
7596       MVT V1VT = V1.getSimpleValueType();
7597       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7598         // The "ext_vec_elt" node is wider than the result node.
7599         // In this case we should extract subvector from V.
7600         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7601         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7602         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7603                                         FullVT.getVectorNumElements()/Ratio);
7604         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7605                         DAG.getIntPtrConstant(0));
7606       }
7607       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7608     }
7609   }
7610
7611   return DAG.getNode(ISD::BITCAST, DL, VT,
7612                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7613 }
7614
7615 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7616                                       SelectionDAG &DAG) {
7617   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7618   MVT VT = Op.getSimpleValueType();
7619   SDLoc dl(Op);
7620   SDValue V1 = Op.getOperand(0);
7621   SDValue V2 = Op.getOperand(1);
7622
7623   if (isZeroShuffle(SVOp))
7624     return getZeroVector(VT, Subtarget, DAG, dl);
7625
7626   // Handle splat operations
7627   if (SVOp->isSplat()) {
7628     // Use vbroadcast whenever the splat comes from a foldable load
7629     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7630     if (Broadcast.getNode())
7631       return Broadcast;
7632   }
7633
7634   // Check integer expanding shuffles.
7635   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7636   if (NewOp.getNode())
7637     return NewOp;
7638
7639   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7640   // do it!
7641   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7642       VT == MVT::v32i8) {
7643     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7644     if (NewOp.getNode())
7645       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7646   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7647     // FIXME: Figure out a cleaner way to do this.
7648     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7649       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7650       if (NewOp.getNode()) {
7651         MVT NewVT = NewOp.getSimpleValueType();
7652         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7653                                NewVT, true, false))
7654           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7655                               dl);
7656       }
7657     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7658       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7659       if (NewOp.getNode()) {
7660         MVT NewVT = NewOp.getSimpleValueType();
7661         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7662           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7663                               dl);
7664       }
7665     }
7666   }
7667   return SDValue();
7668 }
7669
7670 SDValue
7671 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7672   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7673   SDValue V1 = Op.getOperand(0);
7674   SDValue V2 = Op.getOperand(1);
7675   MVT VT = Op.getSimpleValueType();
7676   SDLoc dl(Op);
7677   unsigned NumElems = VT.getVectorNumElements();
7678   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7679   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7680   bool V1IsSplat = false;
7681   bool V2IsSplat = false;
7682   bool HasSSE2 = Subtarget->hasSSE2();
7683   bool HasFp256    = Subtarget->hasFp256();
7684   bool HasInt256   = Subtarget->hasInt256();
7685   MachineFunction &MF = DAG.getMachineFunction();
7686   bool OptForSize = MF.getFunction()->getAttributes().
7687     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7688
7689   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7690
7691   if (V1IsUndef && V2IsUndef)
7692     return DAG.getUNDEF(VT);
7693
7694   // When we create a shuffle node we put the UNDEF node to second operand,
7695   // but in some cases the first operand may be transformed to UNDEF.
7696   // In this case we should just commute the node.
7697   if (V1IsUndef)
7698     return CommuteVectorShuffle(SVOp, DAG);
7699
7700   // Vector shuffle lowering takes 3 steps:
7701   //
7702   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7703   //    narrowing and commutation of operands should be handled.
7704   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7705   //    shuffle nodes.
7706   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7707   //    so the shuffle can be broken into other shuffles and the legalizer can
7708   //    try the lowering again.
7709   //
7710   // The general idea is that no vector_shuffle operation should be left to
7711   // be matched during isel, all of them must be converted to a target specific
7712   // node here.
7713
7714   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7715   // narrowing and commutation of operands should be handled. The actual code
7716   // doesn't include all of those, work in progress...
7717   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7718   if (NewOp.getNode())
7719     return NewOp;
7720
7721   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7722
7723   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7724   // unpckh_undef). Only use pshufd if speed is more important than size.
7725   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7726     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7727   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7728     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7729
7730   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7731       V2IsUndef && MayFoldVectorLoad(V1))
7732     return getMOVDDup(Op, dl, V1, DAG);
7733
7734   if (isMOVHLPS_v_undef_Mask(M, VT))
7735     return getMOVHighToLow(Op, dl, DAG);
7736
7737   // Use to match splats
7738   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7739       (VT == MVT::v2f64 || VT == MVT::v2i64))
7740     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7741
7742   if (isPSHUFDMask(M, VT)) {
7743     // The actual implementation will match the mask in the if above and then
7744     // during isel it can match several different instructions, not only pshufd
7745     // as its name says, sad but true, emulate the behavior for now...
7746     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7747       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7748
7749     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7750
7751     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7752       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7753
7754     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7755       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7756                                   DAG);
7757
7758     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7759                                 TargetMask, DAG);
7760   }
7761
7762   if (isPALIGNRMask(M, VT, Subtarget))
7763     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7764                                 getShufflePALIGNRImmediate(SVOp),
7765                                 DAG);
7766
7767   // Check if this can be converted into a logical shift.
7768   bool isLeft = false;
7769   unsigned ShAmt = 0;
7770   SDValue ShVal;
7771   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7772   if (isShift && ShVal.hasOneUse()) {
7773     // If the shifted value has multiple uses, it may be cheaper to use
7774     // v_set0 + movlhps or movhlps, etc.
7775     MVT EltVT = VT.getVectorElementType();
7776     ShAmt *= EltVT.getSizeInBits();
7777     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7778   }
7779
7780   if (isMOVLMask(M, VT)) {
7781     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7782       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7783     if (!isMOVLPMask(M, VT)) {
7784       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7785         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7786
7787       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7788         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7789     }
7790   }
7791
7792   // FIXME: fold these into legal mask.
7793   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7794     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7795
7796   if (isMOVHLPSMask(M, VT))
7797     return getMOVHighToLow(Op, dl, DAG);
7798
7799   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7800     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7801
7802   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7803     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7804
7805   if (isMOVLPMask(M, VT))
7806     return getMOVLP(Op, dl, DAG, HasSSE2);
7807
7808   if (ShouldXformToMOVHLPS(M, VT) ||
7809       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7810     return CommuteVectorShuffle(SVOp, DAG);
7811
7812   if (isShift) {
7813     // No better options. Use a vshldq / vsrldq.
7814     MVT EltVT = VT.getVectorElementType();
7815     ShAmt *= EltVT.getSizeInBits();
7816     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7817   }
7818
7819   bool Commuted = false;
7820   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7821   // 1,1,1,1 -> v8i16 though.
7822   V1IsSplat = isSplatVector(V1.getNode());
7823   V2IsSplat = isSplatVector(V2.getNode());
7824
7825   // Canonicalize the splat or undef, if present, to be on the RHS.
7826   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7827     CommuteVectorShuffleMask(M, NumElems);
7828     std::swap(V1, V2);
7829     std::swap(V1IsSplat, V2IsSplat);
7830     Commuted = true;
7831   }
7832
7833   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7834     // Shuffling low element of v1 into undef, just return v1.
7835     if (V2IsUndef)
7836       return V1;
7837     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7838     // the instruction selector will not match, so get a canonical MOVL with
7839     // swapped operands to undo the commute.
7840     return getMOVL(DAG, dl, VT, V2, V1);
7841   }
7842
7843   if (isUNPCKLMask(M, VT, HasInt256))
7844     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7845
7846   if (isUNPCKHMask(M, VT, HasInt256))
7847     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7848
7849   if (V2IsSplat) {
7850     // Normalize mask so all entries that point to V2 points to its first
7851     // element then try to match unpck{h|l} again. If match, return a
7852     // new vector_shuffle with the corrected mask.p
7853     SmallVector<int, 8> NewMask(M.begin(), M.end());
7854     NormalizeMask(NewMask, NumElems);
7855     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7856       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7857     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7858       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7859   }
7860
7861   if (Commuted) {
7862     // Commute is back and try unpck* again.
7863     // FIXME: this seems wrong.
7864     CommuteVectorShuffleMask(M, NumElems);
7865     std::swap(V1, V2);
7866     std::swap(V1IsSplat, V2IsSplat);
7867
7868     if (isUNPCKLMask(M, VT, HasInt256))
7869       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7870
7871     if (isUNPCKHMask(M, VT, HasInt256))
7872       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7873   }
7874
7875   // Normalize the node to match x86 shuffle ops if needed
7876   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7877     return CommuteVectorShuffle(SVOp, DAG);
7878
7879   // The checks below are all present in isShuffleMaskLegal, but they are
7880   // inlined here right now to enable us to directly emit target specific
7881   // nodes, and remove one by one until they don't return Op anymore.
7882
7883   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7884       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7885     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7886       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7887   }
7888
7889   if (isPSHUFHWMask(M, VT, HasInt256))
7890     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7891                                 getShufflePSHUFHWImmediate(SVOp),
7892                                 DAG);
7893
7894   if (isPSHUFLWMask(M, VT, HasInt256))
7895     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7896                                 getShufflePSHUFLWImmediate(SVOp),
7897                                 DAG);
7898
7899   if (isSHUFPMask(M, VT))
7900     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7901                                 getShuffleSHUFImmediate(SVOp), DAG);
7902
7903   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7904     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7905   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7906     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7907
7908   //===--------------------------------------------------------------------===//
7909   // Generate target specific nodes for 128 or 256-bit shuffles only
7910   // supported in the AVX instruction set.
7911   //
7912
7913   // Handle VMOVDDUPY permutations
7914   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7915     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7916
7917   // Handle VPERMILPS/D* permutations
7918   if (isVPERMILPMask(M, VT)) {
7919     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7920       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7921                                   getShuffleSHUFImmediate(SVOp), DAG);
7922     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7923                                 getShuffleSHUFImmediate(SVOp), DAG);
7924   }
7925
7926   unsigned Idx;
7927   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7928     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7929                               Idx*(NumElems/2), DAG, dl);
7930
7931   // Handle VPERM2F128/VPERM2I128 permutations
7932   if (isVPERM2X128Mask(M, VT, HasFp256))
7933     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7934                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7935
7936   unsigned MaskValue;
7937   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
7938                   &MaskValue))
7939     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
7940
7941   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7942     return getINSERTPS(SVOp, dl, DAG);
7943
7944   unsigned Imm8;
7945   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7946     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7947
7948   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7949       VT.is512BitVector()) {
7950     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7951     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7952     SmallVector<SDValue, 16> permclMask;
7953     for (unsigned i = 0; i != NumElems; ++i) {
7954       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7955     }
7956
7957     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7958     if (V2IsUndef)
7959       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7960       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7961                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7962     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7963                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7964   }
7965
7966   //===--------------------------------------------------------------------===//
7967   // Since no target specific shuffle was selected for this generic one,
7968   // lower it into other known shuffles. FIXME: this isn't true yet, but
7969   // this is the plan.
7970   //
7971
7972   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7973   if (VT == MVT::v8i16) {
7974     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7975     if (NewOp.getNode())
7976       return NewOp;
7977   }
7978
7979   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7980     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7981     if (NewOp.getNode())
7982       return NewOp;
7983   }
7984
7985   if (VT == MVT::v16i8) {
7986     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7987     if (NewOp.getNode())
7988       return NewOp;
7989   }
7990
7991   if (VT == MVT::v32i8) {
7992     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7993     if (NewOp.getNode())
7994       return NewOp;
7995   }
7996
7997   // Handle all 128-bit wide vectors with 4 elements, and match them with
7998   // several different shuffle types.
7999   if (NumElems == 4 && VT.is128BitVector())
8000     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8001
8002   // Handle general 256-bit shuffles
8003   if (VT.is256BitVector())
8004     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8005
8006   return SDValue();
8007 }
8008
8009 // This function assumes its argument is a BUILD_VECTOR of constants or
8010 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8011 // true.
8012 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8013                                     unsigned &MaskValue) {
8014   MaskValue = 0;
8015   unsigned NumElems = BuildVector->getNumOperands();
8016   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8017   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8018   unsigned NumElemsInLane = NumElems / NumLanes;
8019
8020   // Blend for v16i16 should be symetric for the both lanes.
8021   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8022     SDValue EltCond = BuildVector->getOperand(i);
8023     SDValue SndLaneEltCond =
8024         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8025
8026     int Lane1Cond = -1, Lane2Cond = -1;
8027     if (isa<ConstantSDNode>(EltCond))
8028       Lane1Cond = !isZero(EltCond);
8029     if (isa<ConstantSDNode>(SndLaneEltCond))
8030       Lane2Cond = !isZero(SndLaneEltCond);
8031
8032     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8033       // Lane1Cond != 0, means we want the first argument.
8034       // Lane1Cond == 0, means we want the second argument.
8035       // The encoding of this argument is 0 for the first argument, 1
8036       // for the second. Therefore, invert the condition.
8037       MaskValue |= !Lane1Cond << i;
8038     else if (Lane1Cond < 0)
8039       MaskValue |= !Lane2Cond << i;
8040     else
8041       return false;
8042   }
8043   return true;
8044 }
8045
8046 // Try to lower a vselect node into a simple blend instruction.
8047 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8048                                    SelectionDAG &DAG) {
8049   SDValue Cond = Op.getOperand(0);
8050   SDValue LHS = Op.getOperand(1);
8051   SDValue RHS = Op.getOperand(2);
8052   SDLoc dl(Op);
8053   MVT VT = Op.getSimpleValueType();
8054   MVT EltVT = VT.getVectorElementType();
8055   unsigned NumElems = VT.getVectorNumElements();
8056
8057   // There is no blend with immediate in AVX-512.
8058   if (VT.is512BitVector())
8059     return SDValue();
8060
8061   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8062     return SDValue();
8063   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8064     return SDValue();
8065
8066   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8067     return SDValue();
8068
8069   // Check the mask for BLEND and build the value.
8070   unsigned MaskValue = 0;
8071   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8072     return SDValue();
8073
8074   // Convert i32 vectors to floating point if it is not AVX2.
8075   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8076   MVT BlendVT = VT;
8077   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8078     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8079                                NumElems);
8080     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8081     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8082   }
8083
8084   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8085                             DAG.getConstant(MaskValue, MVT::i32));
8086   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8087 }
8088
8089 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8090   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8091   if (BlendOp.getNode())
8092     return BlendOp;
8093
8094   // Some types for vselect were previously set to Expand, not Legal or
8095   // Custom. Return an empty SDValue so we fall-through to Expand, after
8096   // the Custom lowering phase.
8097   MVT VT = Op.getSimpleValueType();
8098   switch (VT.SimpleTy) {
8099   default:
8100     break;
8101   case MVT::v8i16:
8102   case MVT::v16i16:
8103     return SDValue();
8104   }
8105
8106   // We couldn't create a "Blend with immediate" node.
8107   // This node should still be legal, but we'll have to emit a blendv*
8108   // instruction.
8109   return Op;
8110 }
8111
8112 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8113   MVT VT = Op.getSimpleValueType();
8114   SDLoc dl(Op);
8115
8116   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8117     return SDValue();
8118
8119   if (VT.getSizeInBits() == 8) {
8120     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8121                                   Op.getOperand(0), Op.getOperand(1));
8122     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8123                                   DAG.getValueType(VT));
8124     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8125   }
8126
8127   if (VT.getSizeInBits() == 16) {
8128     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8129     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8130     if (Idx == 0)
8131       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8132                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8133                                      DAG.getNode(ISD::BITCAST, dl,
8134                                                  MVT::v4i32,
8135                                                  Op.getOperand(0)),
8136                                      Op.getOperand(1)));
8137     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8138                                   Op.getOperand(0), Op.getOperand(1));
8139     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8140                                   DAG.getValueType(VT));
8141     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8142   }
8143
8144   if (VT == MVT::f32) {
8145     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8146     // the result back to FR32 register. It's only worth matching if the
8147     // result has a single use which is a store or a bitcast to i32.  And in
8148     // the case of a store, it's not worth it if the index is a constant 0,
8149     // because a MOVSSmr can be used instead, which is smaller and faster.
8150     if (!Op.hasOneUse())
8151       return SDValue();
8152     SDNode *User = *Op.getNode()->use_begin();
8153     if ((User->getOpcode() != ISD::STORE ||
8154          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8155           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8156         (User->getOpcode() != ISD::BITCAST ||
8157          User->getValueType(0) != MVT::i32))
8158       return SDValue();
8159     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8160                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8161                                               Op.getOperand(0)),
8162                                               Op.getOperand(1));
8163     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8164   }
8165
8166   if (VT == MVT::i32 || VT == MVT::i64) {
8167     // ExtractPS/pextrq works with constant index.
8168     if (isa<ConstantSDNode>(Op.getOperand(1)))
8169       return Op;
8170   }
8171   return SDValue();
8172 }
8173
8174 /// Extract one bit from mask vector, like v16i1 or v8i1.
8175 /// AVX-512 feature.
8176 SDValue
8177 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8178   SDValue Vec = Op.getOperand(0);
8179   SDLoc dl(Vec);
8180   MVT VecVT = Vec.getSimpleValueType();
8181   SDValue Idx = Op.getOperand(1);
8182   MVT EltVT = Op.getSimpleValueType();
8183
8184   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8185
8186   // variable index can't be handled in mask registers,
8187   // extend vector to VR512
8188   if (!isa<ConstantSDNode>(Idx)) {
8189     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8190     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8191     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8192                               ExtVT.getVectorElementType(), Ext, Idx);
8193     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8194   }
8195
8196   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8197   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8198   unsigned MaxSift = rc->getSize()*8 - 1;
8199   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8200                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8201   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8202                     DAG.getConstant(MaxSift, MVT::i8));
8203   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8204                        DAG.getIntPtrConstant(0));
8205 }
8206
8207 SDValue
8208 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8209                                            SelectionDAG &DAG) const {
8210   SDLoc dl(Op);
8211   SDValue Vec = Op.getOperand(0);
8212   MVT VecVT = Vec.getSimpleValueType();
8213   SDValue Idx = Op.getOperand(1);
8214
8215   if (Op.getSimpleValueType() == MVT::i1)
8216     return ExtractBitFromMaskVector(Op, DAG);
8217
8218   if (!isa<ConstantSDNode>(Idx)) {
8219     if (VecVT.is512BitVector() ||
8220         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8221          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8222
8223       MVT MaskEltVT =
8224         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8225       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8226                                     MaskEltVT.getSizeInBits());
8227
8228       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8229       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8230                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8231                                 Idx, DAG.getConstant(0, getPointerTy()));
8232       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8233       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8234                         Perm, DAG.getConstant(0, getPointerTy()));
8235     }
8236     return SDValue();
8237   }
8238
8239   // If this is a 256-bit vector result, first extract the 128-bit vector and
8240   // then extract the element from the 128-bit vector.
8241   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8242
8243     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8244     // Get the 128-bit vector.
8245     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8246     MVT EltVT = VecVT.getVectorElementType();
8247
8248     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8249
8250     //if (IdxVal >= NumElems/2)
8251     //  IdxVal -= NumElems/2;
8252     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8253     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8254                        DAG.getConstant(IdxVal, MVT::i32));
8255   }
8256
8257   assert(VecVT.is128BitVector() && "Unexpected vector length");
8258
8259   if (Subtarget->hasSSE41()) {
8260     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8261     if (Res.getNode())
8262       return Res;
8263   }
8264
8265   MVT VT = Op.getSimpleValueType();
8266   // TODO: handle v16i8.
8267   if (VT.getSizeInBits() == 16) {
8268     SDValue Vec = Op.getOperand(0);
8269     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8270     if (Idx == 0)
8271       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8272                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8273                                      DAG.getNode(ISD::BITCAST, dl,
8274                                                  MVT::v4i32, Vec),
8275                                      Op.getOperand(1)));
8276     // Transform it so it match pextrw which produces a 32-bit result.
8277     MVT EltVT = MVT::i32;
8278     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8279                                   Op.getOperand(0), Op.getOperand(1));
8280     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8281                                   DAG.getValueType(VT));
8282     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8283   }
8284
8285   if (VT.getSizeInBits() == 32) {
8286     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8287     if (Idx == 0)
8288       return Op;
8289
8290     // SHUFPS the element to the lowest double word, then movss.
8291     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8292     MVT VVT = Op.getOperand(0).getSimpleValueType();
8293     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8294                                        DAG.getUNDEF(VVT), Mask);
8295     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8296                        DAG.getIntPtrConstant(0));
8297   }
8298
8299   if (VT.getSizeInBits() == 64) {
8300     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8301     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8302     //        to match extract_elt for f64.
8303     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8304     if (Idx == 0)
8305       return Op;
8306
8307     // UNPCKHPD the element to the lowest double word, then movsd.
8308     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8309     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8310     int Mask[2] = { 1, -1 };
8311     MVT VVT = Op.getOperand(0).getSimpleValueType();
8312     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8313                                        DAG.getUNDEF(VVT), Mask);
8314     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8315                        DAG.getIntPtrConstant(0));
8316   }
8317
8318   return SDValue();
8319 }
8320
8321 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8322   MVT VT = Op.getSimpleValueType();
8323   MVT EltVT = VT.getVectorElementType();
8324   SDLoc dl(Op);
8325
8326   SDValue N0 = Op.getOperand(0);
8327   SDValue N1 = Op.getOperand(1);
8328   SDValue N2 = Op.getOperand(2);
8329
8330   if (!VT.is128BitVector())
8331     return SDValue();
8332
8333   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8334       isa<ConstantSDNode>(N2)) {
8335     unsigned Opc;
8336     if (VT == MVT::v8i16)
8337       Opc = X86ISD::PINSRW;
8338     else if (VT == MVT::v16i8)
8339       Opc = X86ISD::PINSRB;
8340     else
8341       Opc = X86ISD::PINSRB;
8342
8343     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8344     // argument.
8345     if (N1.getValueType() != MVT::i32)
8346       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8347     if (N2.getValueType() != MVT::i32)
8348       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8349     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8350   }
8351
8352   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8353     // Bits [7:6] of the constant are the source select.  This will always be
8354     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8355     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8356     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8357     // Bits [5:4] of the constant are the destination select.  This is the
8358     //  value of the incoming immediate.
8359     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8360     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8361     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8362     // Create this as a scalar to vector..
8363     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8364     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8365   }
8366
8367   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8368     // PINSR* works with constant index.
8369     return Op;
8370   }
8371   return SDValue();
8372 }
8373
8374 /// Insert one bit to mask vector, like v16i1 or v8i1.
8375 /// AVX-512 feature.
8376 SDValue 
8377 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8378   SDLoc dl(Op);
8379   SDValue Vec = Op.getOperand(0);
8380   SDValue Elt = Op.getOperand(1);
8381   SDValue Idx = Op.getOperand(2);
8382   MVT VecVT = Vec.getSimpleValueType();
8383
8384   if (!isa<ConstantSDNode>(Idx)) {
8385     // Non constant index. Extend source and destination,
8386     // insert element and then truncate the result.
8387     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8388     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8389     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8390       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8391       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8392     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8393   }
8394
8395   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8396   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8397   if (Vec.getOpcode() == ISD::UNDEF)
8398     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8399                        DAG.getConstant(IdxVal, MVT::i8));
8400   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8401   unsigned MaxSift = rc->getSize()*8 - 1;
8402   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8403                     DAG.getConstant(MaxSift, MVT::i8));
8404   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8405                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8406   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8407 }
8408 SDValue
8409 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8410   MVT VT = Op.getSimpleValueType();
8411   MVT EltVT = VT.getVectorElementType();
8412   
8413   if (EltVT == MVT::i1)
8414     return InsertBitToMaskVector(Op, DAG);
8415
8416   SDLoc dl(Op);
8417   SDValue N0 = Op.getOperand(0);
8418   SDValue N1 = Op.getOperand(1);
8419   SDValue N2 = Op.getOperand(2);
8420
8421   // If this is a 256-bit vector result, first extract the 128-bit vector,
8422   // insert the element into the extracted half and then place it back.
8423   if (VT.is256BitVector() || VT.is512BitVector()) {
8424     if (!isa<ConstantSDNode>(N2))
8425       return SDValue();
8426
8427     // Get the desired 128-bit vector half.
8428     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8429     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8430
8431     // Insert the element into the desired half.
8432     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8433     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8434
8435     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8436                     DAG.getConstant(IdxIn128, MVT::i32));
8437
8438     // Insert the changed part back to the 256-bit vector
8439     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8440   }
8441
8442   if (Subtarget->hasSSE41())
8443     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8444
8445   if (EltVT == MVT::i8)
8446     return SDValue();
8447
8448   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8449     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8450     // as its second argument.
8451     if (N1.getValueType() != MVT::i32)
8452       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8453     if (N2.getValueType() != MVT::i32)
8454       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8455     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8456   }
8457   return SDValue();
8458 }
8459
8460 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8461   SDLoc dl(Op);
8462   MVT OpVT = Op.getSimpleValueType();
8463
8464   // If this is a 256-bit vector result, first insert into a 128-bit
8465   // vector and then insert into the 256-bit vector.
8466   if (!OpVT.is128BitVector()) {
8467     // Insert into a 128-bit vector.
8468     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8469     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8470                                  OpVT.getVectorNumElements() / SizeFactor);
8471
8472     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8473
8474     // Insert the 128-bit vector.
8475     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8476   }
8477
8478   if (OpVT == MVT::v1i64 &&
8479       Op.getOperand(0).getValueType() == MVT::i64)
8480     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8481
8482   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8483   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8484   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8485                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8486 }
8487
8488 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8489 // a simple subregister reference or explicit instructions to grab
8490 // upper bits of a vector.
8491 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8492                                       SelectionDAG &DAG) {
8493   SDLoc dl(Op);
8494   SDValue In =  Op.getOperand(0);
8495   SDValue Idx = Op.getOperand(1);
8496   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8497   MVT ResVT   = Op.getSimpleValueType();
8498   MVT InVT    = In.getSimpleValueType();
8499
8500   if (Subtarget->hasFp256()) {
8501     if (ResVT.is128BitVector() &&
8502         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8503         isa<ConstantSDNode>(Idx)) {
8504       return Extract128BitVector(In, IdxVal, DAG, dl);
8505     }
8506     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8507         isa<ConstantSDNode>(Idx)) {
8508       return Extract256BitVector(In, IdxVal, DAG, dl);
8509     }
8510   }
8511   return SDValue();
8512 }
8513
8514 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8515 // simple superregister reference or explicit instructions to insert
8516 // the upper bits of a vector.
8517 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8518                                      SelectionDAG &DAG) {
8519   if (Subtarget->hasFp256()) {
8520     SDLoc dl(Op.getNode());
8521     SDValue Vec = Op.getNode()->getOperand(0);
8522     SDValue SubVec = Op.getNode()->getOperand(1);
8523     SDValue Idx = Op.getNode()->getOperand(2);
8524
8525     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8526          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8527         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8528         isa<ConstantSDNode>(Idx)) {
8529       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8530       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8531     }
8532
8533     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8534         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8535         isa<ConstantSDNode>(Idx)) {
8536       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8537       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8538     }
8539   }
8540   return SDValue();
8541 }
8542
8543 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8544 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8545 // one of the above mentioned nodes. It has to be wrapped because otherwise
8546 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8547 // be used to form addressing mode. These wrapped nodes will be selected
8548 // into MOV32ri.
8549 SDValue
8550 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8551   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8552
8553   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8554   // global base reg.
8555   unsigned char OpFlag = 0;
8556   unsigned WrapperKind = X86ISD::Wrapper;
8557   CodeModel::Model M = getTargetMachine().getCodeModel();
8558
8559   if (Subtarget->isPICStyleRIPRel() &&
8560       (M == CodeModel::Small || M == CodeModel::Kernel))
8561     WrapperKind = X86ISD::WrapperRIP;
8562   else if (Subtarget->isPICStyleGOT())
8563     OpFlag = X86II::MO_GOTOFF;
8564   else if (Subtarget->isPICStyleStubPIC())
8565     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8566
8567   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8568                                              CP->getAlignment(),
8569                                              CP->getOffset(), OpFlag);
8570   SDLoc DL(CP);
8571   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8572   // With PIC, the address is actually $g + Offset.
8573   if (OpFlag) {
8574     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8575                          DAG.getNode(X86ISD::GlobalBaseReg,
8576                                      SDLoc(), getPointerTy()),
8577                          Result);
8578   }
8579
8580   return Result;
8581 }
8582
8583 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8584   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8585
8586   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8587   // global base reg.
8588   unsigned char OpFlag = 0;
8589   unsigned WrapperKind = X86ISD::Wrapper;
8590   CodeModel::Model M = getTargetMachine().getCodeModel();
8591
8592   if (Subtarget->isPICStyleRIPRel() &&
8593       (M == CodeModel::Small || M == CodeModel::Kernel))
8594     WrapperKind = X86ISD::WrapperRIP;
8595   else if (Subtarget->isPICStyleGOT())
8596     OpFlag = X86II::MO_GOTOFF;
8597   else if (Subtarget->isPICStyleStubPIC())
8598     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8599
8600   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8601                                           OpFlag);
8602   SDLoc DL(JT);
8603   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8604
8605   // With PIC, the address is actually $g + Offset.
8606   if (OpFlag)
8607     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8608                          DAG.getNode(X86ISD::GlobalBaseReg,
8609                                      SDLoc(), getPointerTy()),
8610                          Result);
8611
8612   return Result;
8613 }
8614
8615 SDValue
8616 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8617   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8618
8619   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8620   // global base reg.
8621   unsigned char OpFlag = 0;
8622   unsigned WrapperKind = X86ISD::Wrapper;
8623   CodeModel::Model M = getTargetMachine().getCodeModel();
8624
8625   if (Subtarget->isPICStyleRIPRel() &&
8626       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8627     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8628       OpFlag = X86II::MO_GOTPCREL;
8629     WrapperKind = X86ISD::WrapperRIP;
8630   } else if (Subtarget->isPICStyleGOT()) {
8631     OpFlag = X86II::MO_GOT;
8632   } else if (Subtarget->isPICStyleStubPIC()) {
8633     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8634   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8635     OpFlag = X86II::MO_DARWIN_NONLAZY;
8636   }
8637
8638   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8639
8640   SDLoc DL(Op);
8641   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8642
8643   // With PIC, the address is actually $g + Offset.
8644   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8645       !Subtarget->is64Bit()) {
8646     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8647                          DAG.getNode(X86ISD::GlobalBaseReg,
8648                                      SDLoc(), getPointerTy()),
8649                          Result);
8650   }
8651
8652   // For symbols that require a load from a stub to get the address, emit the
8653   // load.
8654   if (isGlobalStubReference(OpFlag))
8655     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8656                          MachinePointerInfo::getGOT(), false, false, false, 0);
8657
8658   return Result;
8659 }
8660
8661 SDValue
8662 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8663   // Create the TargetBlockAddressAddress node.
8664   unsigned char OpFlags =
8665     Subtarget->ClassifyBlockAddressReference();
8666   CodeModel::Model M = getTargetMachine().getCodeModel();
8667   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8668   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8669   SDLoc dl(Op);
8670   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8671                                              OpFlags);
8672
8673   if (Subtarget->isPICStyleRIPRel() &&
8674       (M == CodeModel::Small || M == CodeModel::Kernel))
8675     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8676   else
8677     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8678
8679   // With PIC, the address is actually $g + Offset.
8680   if (isGlobalRelativeToPICBase(OpFlags)) {
8681     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8682                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8683                          Result);
8684   }
8685
8686   return Result;
8687 }
8688
8689 SDValue
8690 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8691                                       int64_t Offset, SelectionDAG &DAG) const {
8692   // Create the TargetGlobalAddress node, folding in the constant
8693   // offset if it is legal.
8694   unsigned char OpFlags =
8695     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8696   CodeModel::Model M = getTargetMachine().getCodeModel();
8697   SDValue Result;
8698   if (OpFlags == X86II::MO_NO_FLAG &&
8699       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8700     // A direct static reference to a global.
8701     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8702     Offset = 0;
8703   } else {
8704     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8705   }
8706
8707   if (Subtarget->isPICStyleRIPRel() &&
8708       (M == CodeModel::Small || M == CodeModel::Kernel))
8709     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8710   else
8711     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8712
8713   // With PIC, the address is actually $g + Offset.
8714   if (isGlobalRelativeToPICBase(OpFlags)) {
8715     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8716                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8717                          Result);
8718   }
8719
8720   // For globals that require a load from a stub to get the address, emit the
8721   // load.
8722   if (isGlobalStubReference(OpFlags))
8723     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8724                          MachinePointerInfo::getGOT(), false, false, false, 0);
8725
8726   // If there was a non-zero offset that we didn't fold, create an explicit
8727   // addition for it.
8728   if (Offset != 0)
8729     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8730                          DAG.getConstant(Offset, getPointerTy()));
8731
8732   return Result;
8733 }
8734
8735 SDValue
8736 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8737   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8738   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8739   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8740 }
8741
8742 static SDValue
8743 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8744            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8745            unsigned char OperandFlags, bool LocalDynamic = false) {
8746   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8747   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8748   SDLoc dl(GA);
8749   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8750                                            GA->getValueType(0),
8751                                            GA->getOffset(),
8752                                            OperandFlags);
8753
8754   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8755                                            : X86ISD::TLSADDR;
8756
8757   if (InFlag) {
8758     SDValue Ops[] = { Chain,  TGA, *InFlag };
8759     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8760   } else {
8761     SDValue Ops[]  = { Chain, TGA };
8762     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8763   }
8764
8765   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8766   MFI->setAdjustsStack(true);
8767
8768   SDValue Flag = Chain.getValue(1);
8769   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8770 }
8771
8772 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8773 static SDValue
8774 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8775                                 const EVT PtrVT) {
8776   SDValue InFlag;
8777   SDLoc dl(GA);  // ? function entry point might be better
8778   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8779                                    DAG.getNode(X86ISD::GlobalBaseReg,
8780                                                SDLoc(), PtrVT), InFlag);
8781   InFlag = Chain.getValue(1);
8782
8783   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8784 }
8785
8786 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8787 static SDValue
8788 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8789                                 const EVT PtrVT) {
8790   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8791                     X86::RAX, X86II::MO_TLSGD);
8792 }
8793
8794 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8795                                            SelectionDAG &DAG,
8796                                            const EVT PtrVT,
8797                                            bool is64Bit) {
8798   SDLoc dl(GA);
8799
8800   // Get the start address of the TLS block for this module.
8801   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8802       .getInfo<X86MachineFunctionInfo>();
8803   MFI->incNumLocalDynamicTLSAccesses();
8804
8805   SDValue Base;
8806   if (is64Bit) {
8807     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8808                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8809   } else {
8810     SDValue InFlag;
8811     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8812         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8813     InFlag = Chain.getValue(1);
8814     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8815                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8816   }
8817
8818   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8819   // of Base.
8820
8821   // Build x@dtpoff.
8822   unsigned char OperandFlags = X86II::MO_DTPOFF;
8823   unsigned WrapperKind = X86ISD::Wrapper;
8824   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8825                                            GA->getValueType(0),
8826                                            GA->getOffset(), OperandFlags);
8827   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8828
8829   // Add x@dtpoff with the base.
8830   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8831 }
8832
8833 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8834 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8835                                    const EVT PtrVT, TLSModel::Model model,
8836                                    bool is64Bit, bool isPIC) {
8837   SDLoc dl(GA);
8838
8839   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8840   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8841                                                          is64Bit ? 257 : 256));
8842
8843   SDValue ThreadPointer =
8844       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8845                   MachinePointerInfo(Ptr), false, false, false, 0);
8846
8847   unsigned char OperandFlags = 0;
8848   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8849   // initialexec.
8850   unsigned WrapperKind = X86ISD::Wrapper;
8851   if (model == TLSModel::LocalExec) {
8852     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8853   } else if (model == TLSModel::InitialExec) {
8854     if (is64Bit) {
8855       OperandFlags = X86II::MO_GOTTPOFF;
8856       WrapperKind = X86ISD::WrapperRIP;
8857     } else {
8858       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8859     }
8860   } else {
8861     llvm_unreachable("Unexpected model");
8862   }
8863
8864   // emit "addl x@ntpoff,%eax" (local exec)
8865   // or "addl x@indntpoff,%eax" (initial exec)
8866   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8867   SDValue TGA =
8868       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8869                                  GA->getOffset(), OperandFlags);
8870   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8871
8872   if (model == TLSModel::InitialExec) {
8873     if (isPIC && !is64Bit) {
8874       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8875                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8876                            Offset);
8877     }
8878
8879     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8880                          MachinePointerInfo::getGOT(), false, false, false, 0);
8881   }
8882
8883   // The address of the thread local variable is the add of the thread
8884   // pointer with the offset of the variable.
8885   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8886 }
8887
8888 SDValue
8889 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8890
8891   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8892   const GlobalValue *GV = GA->getGlobal();
8893
8894   if (Subtarget->isTargetELF()) {
8895     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8896
8897     switch (model) {
8898       case TLSModel::GeneralDynamic:
8899         if (Subtarget->is64Bit())
8900           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8901         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8902       case TLSModel::LocalDynamic:
8903         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8904                                            Subtarget->is64Bit());
8905       case TLSModel::InitialExec:
8906       case TLSModel::LocalExec:
8907         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8908                                    Subtarget->is64Bit(),
8909                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8910     }
8911     llvm_unreachable("Unknown TLS model.");
8912   }
8913
8914   if (Subtarget->isTargetDarwin()) {
8915     // Darwin only has one model of TLS.  Lower to that.
8916     unsigned char OpFlag = 0;
8917     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8918                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8919
8920     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8921     // global base reg.
8922     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8923                   !Subtarget->is64Bit();
8924     if (PIC32)
8925       OpFlag = X86II::MO_TLVP_PIC_BASE;
8926     else
8927       OpFlag = X86II::MO_TLVP;
8928     SDLoc DL(Op);
8929     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8930                                                 GA->getValueType(0),
8931                                                 GA->getOffset(), OpFlag);
8932     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8933
8934     // With PIC32, the address is actually $g + Offset.
8935     if (PIC32)
8936       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8937                            DAG.getNode(X86ISD::GlobalBaseReg,
8938                                        SDLoc(), getPointerTy()),
8939                            Offset);
8940
8941     // Lowering the machine isd will make sure everything is in the right
8942     // location.
8943     SDValue Chain = DAG.getEntryNode();
8944     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8945     SDValue Args[] = { Chain, Offset };
8946     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8947
8948     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8949     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8950     MFI->setAdjustsStack(true);
8951
8952     // And our return value (tls address) is in the standard call return value
8953     // location.
8954     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8955     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8956                               Chain.getValue(1));
8957   }
8958
8959   if (Subtarget->isTargetKnownWindowsMSVC() ||
8960       Subtarget->isTargetWindowsGNU()) {
8961     // Just use the implicit TLS architecture
8962     // Need to generate someting similar to:
8963     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8964     //                                  ; from TEB
8965     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8966     //   mov     rcx, qword [rdx+rcx*8]
8967     //   mov     eax, .tls$:tlsvar
8968     //   [rax+rcx] contains the address
8969     // Windows 64bit: gs:0x58
8970     // Windows 32bit: fs:__tls_array
8971
8972     SDLoc dl(GA);
8973     SDValue Chain = DAG.getEntryNode();
8974
8975     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8976     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8977     // use its literal value of 0x2C.
8978     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8979                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8980                                                              256)
8981                                         : Type::getInt32PtrTy(*DAG.getContext(),
8982                                                               257));
8983
8984     SDValue TlsArray =
8985         Subtarget->is64Bit()
8986             ? DAG.getIntPtrConstant(0x58)
8987             : (Subtarget->isTargetWindowsGNU()
8988                    ? DAG.getIntPtrConstant(0x2C)
8989                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8990
8991     SDValue ThreadPointer =
8992         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8993                     MachinePointerInfo(Ptr), false, false, false, 0);
8994
8995     // Load the _tls_index variable
8996     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8997     if (Subtarget->is64Bit())
8998       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8999                            IDX, MachinePointerInfo(), MVT::i32,
9000                            false, false, 0);
9001     else
9002       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9003                         false, false, false, 0);
9004
9005     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9006                                     getPointerTy());
9007     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9008
9009     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9010     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9011                       false, false, false, 0);
9012
9013     // Get the offset of start of .tls section
9014     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9015                                              GA->getValueType(0),
9016                                              GA->getOffset(), X86II::MO_SECREL);
9017     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9018
9019     // The address of the thread local variable is the add of the thread
9020     // pointer with the offset of the variable.
9021     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9022   }
9023
9024   llvm_unreachable("TLS not implemented for this target.");
9025 }
9026
9027 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9028 /// and take a 2 x i32 value to shift plus a shift amount.
9029 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9030   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9031   MVT VT = Op.getSimpleValueType();
9032   unsigned VTBits = VT.getSizeInBits();
9033   SDLoc dl(Op);
9034   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9035   SDValue ShOpLo = Op.getOperand(0);
9036   SDValue ShOpHi = Op.getOperand(1);
9037   SDValue ShAmt  = Op.getOperand(2);
9038   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9039   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9040   // during isel.
9041   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9042                                   DAG.getConstant(VTBits - 1, MVT::i8));
9043   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9044                                      DAG.getConstant(VTBits - 1, MVT::i8))
9045                        : DAG.getConstant(0, VT);
9046
9047   SDValue Tmp2, Tmp3;
9048   if (Op.getOpcode() == ISD::SHL_PARTS) {
9049     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9050     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9051   } else {
9052     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9053     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9054   }
9055
9056   // If the shift amount is larger or equal than the width of a part we can't
9057   // rely on the results of shld/shrd. Insert a test and select the appropriate
9058   // values for large shift amounts.
9059   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9060                                 DAG.getConstant(VTBits, MVT::i8));
9061   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9062                              AndNode, DAG.getConstant(0, MVT::i8));
9063
9064   SDValue Hi, Lo;
9065   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9066   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9067   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9068
9069   if (Op.getOpcode() == ISD::SHL_PARTS) {
9070     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9071     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9072   } else {
9073     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9074     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9075   }
9076
9077   SDValue Ops[2] = { Lo, Hi };
9078   return DAG.getMergeValues(Ops, dl);
9079 }
9080
9081 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9082                                            SelectionDAG &DAG) const {
9083   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9084
9085   if (SrcVT.isVector())
9086     return SDValue();
9087
9088   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9089          "Unknown SINT_TO_FP to lower!");
9090
9091   // These are really Legal; return the operand so the caller accepts it as
9092   // Legal.
9093   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9094     return Op;
9095   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9096       Subtarget->is64Bit()) {
9097     return Op;
9098   }
9099
9100   SDLoc dl(Op);
9101   unsigned Size = SrcVT.getSizeInBits()/8;
9102   MachineFunction &MF = DAG.getMachineFunction();
9103   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9104   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9105   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9106                                StackSlot,
9107                                MachinePointerInfo::getFixedStack(SSFI),
9108                                false, false, 0);
9109   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9110 }
9111
9112 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9113                                      SDValue StackSlot,
9114                                      SelectionDAG &DAG) const {
9115   // Build the FILD
9116   SDLoc DL(Op);
9117   SDVTList Tys;
9118   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9119   if (useSSE)
9120     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9121   else
9122     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9123
9124   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9125
9126   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9127   MachineMemOperand *MMO;
9128   if (FI) {
9129     int SSFI = FI->getIndex();
9130     MMO =
9131       DAG.getMachineFunction()
9132       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9133                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9134   } else {
9135     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9136     StackSlot = StackSlot.getOperand(1);
9137   }
9138   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9139   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9140                                            X86ISD::FILD, DL,
9141                                            Tys, Ops, SrcVT, MMO);
9142
9143   if (useSSE) {
9144     Chain = Result.getValue(1);
9145     SDValue InFlag = Result.getValue(2);
9146
9147     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9148     // shouldn't be necessary except that RFP cannot be live across
9149     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9150     MachineFunction &MF = DAG.getMachineFunction();
9151     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9152     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9153     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9154     Tys = DAG.getVTList(MVT::Other);
9155     SDValue Ops[] = {
9156       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9157     };
9158     MachineMemOperand *MMO =
9159       DAG.getMachineFunction()
9160       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9161                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9162
9163     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9164                                     Ops, Op.getValueType(), MMO);
9165     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9166                          MachinePointerInfo::getFixedStack(SSFI),
9167                          false, false, false, 0);
9168   }
9169
9170   return Result;
9171 }
9172
9173 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9174 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9175                                                SelectionDAG &DAG) const {
9176   // This algorithm is not obvious. Here it is what we're trying to output:
9177   /*
9178      movq       %rax,  %xmm0
9179      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9180      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9181      #ifdef __SSE3__
9182        haddpd   %xmm0, %xmm0
9183      #else
9184        pshufd   $0x4e, %xmm0, %xmm1
9185        addpd    %xmm1, %xmm0
9186      #endif
9187   */
9188
9189   SDLoc dl(Op);
9190   LLVMContext *Context = DAG.getContext();
9191
9192   // Build some magic constants.
9193   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9194   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9195   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9196
9197   SmallVector<Constant*,2> CV1;
9198   CV1.push_back(
9199     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9200                                       APInt(64, 0x4330000000000000ULL))));
9201   CV1.push_back(
9202     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9203                                       APInt(64, 0x4530000000000000ULL))));
9204   Constant *C1 = ConstantVector::get(CV1);
9205   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9206
9207   // Load the 64-bit value into an XMM register.
9208   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9209                             Op.getOperand(0));
9210   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9211                               MachinePointerInfo::getConstantPool(),
9212                               false, false, false, 16);
9213   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9214                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9215                               CLod0);
9216
9217   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9218                               MachinePointerInfo::getConstantPool(),
9219                               false, false, false, 16);
9220   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9221   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9222   SDValue Result;
9223
9224   if (Subtarget->hasSSE3()) {
9225     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9226     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9227   } else {
9228     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9229     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9230                                            S2F, 0x4E, DAG);
9231     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9232                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9233                          Sub);
9234   }
9235
9236   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9237                      DAG.getIntPtrConstant(0));
9238 }
9239
9240 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9241 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9242                                                SelectionDAG &DAG) const {
9243   SDLoc dl(Op);
9244   // FP constant to bias correct the final result.
9245   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9246                                    MVT::f64);
9247
9248   // Load the 32-bit value into an XMM register.
9249   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9250                              Op.getOperand(0));
9251
9252   // Zero out the upper parts of the register.
9253   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9254
9255   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9256                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9257                      DAG.getIntPtrConstant(0));
9258
9259   // Or the load with the bias.
9260   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9261                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9262                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9263                                                    MVT::v2f64, Load)),
9264                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9265                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9266                                                    MVT::v2f64, Bias)));
9267   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9268                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9269                    DAG.getIntPtrConstant(0));
9270
9271   // Subtract the bias.
9272   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9273
9274   // Handle final rounding.
9275   EVT DestVT = Op.getValueType();
9276
9277   if (DestVT.bitsLT(MVT::f64))
9278     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9279                        DAG.getIntPtrConstant(0));
9280   if (DestVT.bitsGT(MVT::f64))
9281     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9282
9283   // Handle final rounding.
9284   return Sub;
9285 }
9286
9287 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9288                                                SelectionDAG &DAG) const {
9289   SDValue N0 = Op.getOperand(0);
9290   MVT SVT = N0.getSimpleValueType();
9291   SDLoc dl(Op);
9292
9293   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9294           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9295          "Custom UINT_TO_FP is not supported!");
9296
9297   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9298   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9299                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9300 }
9301
9302 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9303                                            SelectionDAG &DAG) const {
9304   SDValue N0 = Op.getOperand(0);
9305   SDLoc dl(Op);
9306
9307   if (Op.getValueType().isVector())
9308     return lowerUINT_TO_FP_vec(Op, DAG);
9309
9310   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9311   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9312   // the optimization here.
9313   if (DAG.SignBitIsZero(N0))
9314     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9315
9316   MVT SrcVT = N0.getSimpleValueType();
9317   MVT DstVT = Op.getSimpleValueType();
9318   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9319     return LowerUINT_TO_FP_i64(Op, DAG);
9320   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9321     return LowerUINT_TO_FP_i32(Op, DAG);
9322   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9323     return SDValue();
9324
9325   // Make a 64-bit buffer, and use it to build an FILD.
9326   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9327   if (SrcVT == MVT::i32) {
9328     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9329     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9330                                      getPointerTy(), StackSlot, WordOff);
9331     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9332                                   StackSlot, MachinePointerInfo(),
9333                                   false, false, 0);
9334     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9335                                   OffsetSlot, MachinePointerInfo(),
9336                                   false, false, 0);
9337     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9338     return Fild;
9339   }
9340
9341   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9342   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9343                                StackSlot, MachinePointerInfo(),
9344                                false, false, 0);
9345   // For i64 source, we need to add the appropriate power of 2 if the input
9346   // was negative.  This is the same as the optimization in
9347   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9348   // we must be careful to do the computation in x87 extended precision, not
9349   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9350   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9351   MachineMemOperand *MMO =
9352     DAG.getMachineFunction()
9353     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9354                           MachineMemOperand::MOLoad, 8, 8);
9355
9356   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9357   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9358   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9359                                          MVT::i64, MMO);
9360
9361   APInt FF(32, 0x5F800000ULL);
9362
9363   // Check whether the sign bit is set.
9364   SDValue SignSet = DAG.getSetCC(dl,
9365                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9366                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9367                                  ISD::SETLT);
9368
9369   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9370   SDValue FudgePtr = DAG.getConstantPool(
9371                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9372                                          getPointerTy());
9373
9374   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9375   SDValue Zero = DAG.getIntPtrConstant(0);
9376   SDValue Four = DAG.getIntPtrConstant(4);
9377   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9378                                Zero, Four);
9379   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9380
9381   // Load the value out, extending it from f32 to f80.
9382   // FIXME: Avoid the extend by constructing the right constant pool?
9383   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9384                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9385                                  MVT::f32, false, false, 4);
9386   // Extend everything to 80 bits to force it to be done on x87.
9387   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9388   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9389 }
9390
9391 std::pair<SDValue,SDValue>
9392 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9393                                     bool IsSigned, bool IsReplace) const {
9394   SDLoc DL(Op);
9395
9396   EVT DstTy = Op.getValueType();
9397
9398   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9399     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9400     DstTy = MVT::i64;
9401   }
9402
9403   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9404          DstTy.getSimpleVT() >= MVT::i16 &&
9405          "Unknown FP_TO_INT to lower!");
9406
9407   // These are really Legal.
9408   if (DstTy == MVT::i32 &&
9409       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9410     return std::make_pair(SDValue(), SDValue());
9411   if (Subtarget->is64Bit() &&
9412       DstTy == MVT::i64 &&
9413       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9414     return std::make_pair(SDValue(), SDValue());
9415
9416   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9417   // stack slot, or into the FTOL runtime function.
9418   MachineFunction &MF = DAG.getMachineFunction();
9419   unsigned MemSize = DstTy.getSizeInBits()/8;
9420   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9421   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9422
9423   unsigned Opc;
9424   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9425     Opc = X86ISD::WIN_FTOL;
9426   else
9427     switch (DstTy.getSimpleVT().SimpleTy) {
9428     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9429     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9430     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9431     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9432     }
9433
9434   SDValue Chain = DAG.getEntryNode();
9435   SDValue Value = Op.getOperand(0);
9436   EVT TheVT = Op.getOperand(0).getValueType();
9437   // FIXME This causes a redundant load/store if the SSE-class value is already
9438   // in memory, such as if it is on the callstack.
9439   if (isScalarFPTypeInSSEReg(TheVT)) {
9440     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9441     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9442                          MachinePointerInfo::getFixedStack(SSFI),
9443                          false, false, 0);
9444     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9445     SDValue Ops[] = {
9446       Chain, StackSlot, DAG.getValueType(TheVT)
9447     };
9448
9449     MachineMemOperand *MMO =
9450       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9451                               MachineMemOperand::MOLoad, MemSize, MemSize);
9452     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9453     Chain = Value.getValue(1);
9454     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9455     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9456   }
9457
9458   MachineMemOperand *MMO =
9459     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9460                             MachineMemOperand::MOStore, MemSize, MemSize);
9461
9462   if (Opc != X86ISD::WIN_FTOL) {
9463     // Build the FP_TO_INT*_IN_MEM
9464     SDValue Ops[] = { Chain, Value, StackSlot };
9465     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9466                                            Ops, DstTy, MMO);
9467     return std::make_pair(FIST, StackSlot);
9468   } else {
9469     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9470       DAG.getVTList(MVT::Other, MVT::Glue),
9471       Chain, Value);
9472     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9473       MVT::i32, ftol.getValue(1));
9474     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9475       MVT::i32, eax.getValue(2));
9476     SDValue Ops[] = { eax, edx };
9477     SDValue pair = IsReplace
9478       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9479       : DAG.getMergeValues(Ops, DL);
9480     return std::make_pair(pair, SDValue());
9481   }
9482 }
9483
9484 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9485                               const X86Subtarget *Subtarget) {
9486   MVT VT = Op->getSimpleValueType(0);
9487   SDValue In = Op->getOperand(0);
9488   MVT InVT = In.getSimpleValueType();
9489   SDLoc dl(Op);
9490
9491   // Optimize vectors in AVX mode:
9492   //
9493   //   v8i16 -> v8i32
9494   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9495   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9496   //   Concat upper and lower parts.
9497   //
9498   //   v4i32 -> v4i64
9499   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9500   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9501   //   Concat upper and lower parts.
9502   //
9503
9504   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9505       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9506       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9507     return SDValue();
9508
9509   if (Subtarget->hasInt256())
9510     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9511
9512   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9513   SDValue Undef = DAG.getUNDEF(InVT);
9514   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9515   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9516   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9517
9518   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9519                              VT.getVectorNumElements()/2);
9520
9521   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9522   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9523
9524   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9525 }
9526
9527 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9528                                         SelectionDAG &DAG) {
9529   MVT VT = Op->getSimpleValueType(0);
9530   SDValue In = Op->getOperand(0);
9531   MVT InVT = In.getSimpleValueType();
9532   SDLoc DL(Op);
9533   unsigned int NumElts = VT.getVectorNumElements();
9534   if (NumElts != 8 && NumElts != 16)
9535     return SDValue();
9536
9537   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9538     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9539
9540   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9542   // Now we have only mask extension
9543   assert(InVT.getVectorElementType() == MVT::i1);
9544   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9545   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9546   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9547   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9548   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9549                            MachinePointerInfo::getConstantPool(),
9550                            false, false, false, Alignment);
9551
9552   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9553   if (VT.is512BitVector())
9554     return Brcst;
9555   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9556 }
9557
9558 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9559                                SelectionDAG &DAG) {
9560   if (Subtarget->hasFp256()) {
9561     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9562     if (Res.getNode())
9563       return Res;
9564   }
9565
9566   return SDValue();
9567 }
9568
9569 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9570                                 SelectionDAG &DAG) {
9571   SDLoc DL(Op);
9572   MVT VT = Op.getSimpleValueType();
9573   SDValue In = Op.getOperand(0);
9574   MVT SVT = In.getSimpleValueType();
9575
9576   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9577     return LowerZERO_EXTEND_AVX512(Op, DAG);
9578
9579   if (Subtarget->hasFp256()) {
9580     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9581     if (Res.getNode())
9582       return Res;
9583   }
9584
9585   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9586          VT.getVectorNumElements() != SVT.getVectorNumElements());
9587   return SDValue();
9588 }
9589
9590 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9591   SDLoc DL(Op);
9592   MVT VT = Op.getSimpleValueType();
9593   SDValue In = Op.getOperand(0);
9594   MVT InVT = In.getSimpleValueType();
9595
9596   if (VT == MVT::i1) {
9597     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9598            "Invalid scalar TRUNCATE operation");
9599     if (InVT == MVT::i32)
9600       return SDValue();
9601     if (InVT.getSizeInBits() == 64)
9602       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9603     else if (InVT.getSizeInBits() < 32)
9604       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9605     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9606   }
9607   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9608          "Invalid TRUNCATE operation");
9609
9610   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9611     if (VT.getVectorElementType().getSizeInBits() >=8)
9612       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9613
9614     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9615     unsigned NumElts = InVT.getVectorNumElements();
9616     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9617     if (InVT.getSizeInBits() < 512) {
9618       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9619       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9620       InVT = ExtVT;
9621     }
9622     
9623     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9624     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9625     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9626     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9627     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9628                            MachinePointerInfo::getConstantPool(),
9629                            false, false, false, Alignment);
9630     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9631     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9632     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9633   }
9634
9635   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9636     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9637     if (Subtarget->hasInt256()) {
9638       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9639       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9640       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9641                                 ShufMask);
9642       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9643                          DAG.getIntPtrConstant(0));
9644     }
9645
9646     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9647                                DAG.getIntPtrConstant(0));
9648     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9649                                DAG.getIntPtrConstant(2));
9650     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9651     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9652     static const int ShufMask[] = {0, 2, 4, 6};
9653     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9654   }
9655
9656   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9657     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9658     if (Subtarget->hasInt256()) {
9659       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9660
9661       SmallVector<SDValue,32> pshufbMask;
9662       for (unsigned i = 0; i < 2; ++i) {
9663         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9664         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9665         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9666         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9667         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9668         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9669         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9670         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9671         for (unsigned j = 0; j < 8; ++j)
9672           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9673       }
9674       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9675       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9676       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9677
9678       static const int ShufMask[] = {0,  2,  -1,  -1};
9679       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9680                                 &ShufMask[0]);
9681       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9682                        DAG.getIntPtrConstant(0));
9683       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9684     }
9685
9686     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9687                                DAG.getIntPtrConstant(0));
9688
9689     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9690                                DAG.getIntPtrConstant(4));
9691
9692     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9693     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9694
9695     // The PSHUFB mask:
9696     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9697                                    -1, -1, -1, -1, -1, -1, -1, -1};
9698
9699     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9700     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9701     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9702
9703     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9704     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9705
9706     // The MOVLHPS Mask:
9707     static const int ShufMask2[] = {0, 1, 4, 5};
9708     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9709     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9710   }
9711
9712   // Handle truncation of V256 to V128 using shuffles.
9713   if (!VT.is128BitVector() || !InVT.is256BitVector())
9714     return SDValue();
9715
9716   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9717
9718   unsigned NumElems = VT.getVectorNumElements();
9719   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9720
9721   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9722   // Prepare truncation shuffle mask
9723   for (unsigned i = 0; i != NumElems; ++i)
9724     MaskVec[i] = i * 2;
9725   SDValue V = DAG.getVectorShuffle(NVT, DL,
9726                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9727                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9728   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9729                      DAG.getIntPtrConstant(0));
9730 }
9731
9732 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9733                                            SelectionDAG &DAG) const {
9734   assert(!Op.getSimpleValueType().isVector());
9735
9736   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9737     /*IsSigned=*/ true, /*IsReplace=*/ false);
9738   SDValue FIST = Vals.first, StackSlot = Vals.second;
9739   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9740   if (!FIST.getNode()) return Op;
9741
9742   if (StackSlot.getNode())
9743     // Load the result.
9744     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9745                        FIST, StackSlot, MachinePointerInfo(),
9746                        false, false, false, 0);
9747
9748   // The node is the result.
9749   return FIST;
9750 }
9751
9752 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9753                                            SelectionDAG &DAG) const {
9754   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9755     /*IsSigned=*/ false, /*IsReplace=*/ false);
9756   SDValue FIST = Vals.first, StackSlot = Vals.second;
9757   assert(FIST.getNode() && "Unexpected failure");
9758
9759   if (StackSlot.getNode())
9760     // Load the result.
9761     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9762                        FIST, StackSlot, MachinePointerInfo(),
9763                        false, false, false, 0);
9764
9765   // The node is the result.
9766   return FIST;
9767 }
9768
9769 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9770   SDLoc DL(Op);
9771   MVT VT = Op.getSimpleValueType();
9772   SDValue In = Op.getOperand(0);
9773   MVT SVT = In.getSimpleValueType();
9774
9775   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9776
9777   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9778                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9779                                  In, DAG.getUNDEF(SVT)));
9780 }
9781
9782 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9783   LLVMContext *Context = DAG.getContext();
9784   SDLoc dl(Op);
9785   MVT VT = Op.getSimpleValueType();
9786   MVT EltVT = VT;
9787   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9788   if (VT.isVector()) {
9789     EltVT = VT.getVectorElementType();
9790     NumElts = VT.getVectorNumElements();
9791   }
9792   Constant *C;
9793   if (EltVT == MVT::f64)
9794     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9795                                           APInt(64, ~(1ULL << 63))));
9796   else
9797     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9798                                           APInt(32, ~(1U << 31))));
9799   C = ConstantVector::getSplat(NumElts, C);
9800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9801   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9802   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9803   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9804                              MachinePointerInfo::getConstantPool(),
9805                              false, false, false, Alignment);
9806   if (VT.isVector()) {
9807     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9808     return DAG.getNode(ISD::BITCAST, dl, VT,
9809                        DAG.getNode(ISD::AND, dl, ANDVT,
9810                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9811                                                Op.getOperand(0)),
9812                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9813   }
9814   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9815 }
9816
9817 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9818   LLVMContext *Context = DAG.getContext();
9819   SDLoc dl(Op);
9820   MVT VT = Op.getSimpleValueType();
9821   MVT EltVT = VT;
9822   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9823   if (VT.isVector()) {
9824     EltVT = VT.getVectorElementType();
9825     NumElts = VT.getVectorNumElements();
9826   }
9827   Constant *C;
9828   if (EltVT == MVT::f64)
9829     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9830                                           APInt(64, 1ULL << 63)));
9831   else
9832     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9833                                           APInt(32, 1U << 31)));
9834   C = ConstantVector::getSplat(NumElts, C);
9835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9836   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9837   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9838   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9839                              MachinePointerInfo::getConstantPool(),
9840                              false, false, false, Alignment);
9841   if (VT.isVector()) {
9842     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9843     return DAG.getNode(ISD::BITCAST, dl, VT,
9844                        DAG.getNode(ISD::XOR, dl, XORVT,
9845                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9846                                                Op.getOperand(0)),
9847                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9848   }
9849
9850   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9851 }
9852
9853 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9855   LLVMContext *Context = DAG.getContext();
9856   SDValue Op0 = Op.getOperand(0);
9857   SDValue Op1 = Op.getOperand(1);
9858   SDLoc dl(Op);
9859   MVT VT = Op.getSimpleValueType();
9860   MVT SrcVT = Op1.getSimpleValueType();
9861
9862   // If second operand is smaller, extend it first.
9863   if (SrcVT.bitsLT(VT)) {
9864     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9865     SrcVT = VT;
9866   }
9867   // And if it is bigger, shrink it first.
9868   if (SrcVT.bitsGT(VT)) {
9869     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9870     SrcVT = VT;
9871   }
9872
9873   // At this point the operands and the result should have the same
9874   // type, and that won't be f80 since that is not custom lowered.
9875
9876   // First get the sign bit of second operand.
9877   SmallVector<Constant*,4> CV;
9878   if (SrcVT == MVT::f64) {
9879     const fltSemantics &Sem = APFloat::IEEEdouble;
9880     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9881     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9882   } else {
9883     const fltSemantics &Sem = APFloat::IEEEsingle;
9884     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9885     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9886     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9887     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9888   }
9889   Constant *C = ConstantVector::get(CV);
9890   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9891   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9892                               MachinePointerInfo::getConstantPool(),
9893                               false, false, false, 16);
9894   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9895
9896   // Shift sign bit right or left if the two operands have different types.
9897   if (SrcVT.bitsGT(VT)) {
9898     // Op0 is MVT::f32, Op1 is MVT::f64.
9899     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9900     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9901                           DAG.getConstant(32, MVT::i32));
9902     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9903     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9904                           DAG.getIntPtrConstant(0));
9905   }
9906
9907   // Clear first operand sign bit.
9908   CV.clear();
9909   if (VT == MVT::f64) {
9910     const fltSemantics &Sem = APFloat::IEEEdouble;
9911     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9912                                                    APInt(64, ~(1ULL << 63)))));
9913     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9914   } else {
9915     const fltSemantics &Sem = APFloat::IEEEsingle;
9916     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9917                                                    APInt(32, ~(1U << 31)))));
9918     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9919     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9920     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9921   }
9922   C = ConstantVector::get(CV);
9923   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9924   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9925                               MachinePointerInfo::getConstantPool(),
9926                               false, false, false, 16);
9927   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9928
9929   // Or the value with the sign bit.
9930   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9931 }
9932
9933 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9934   SDValue N0 = Op.getOperand(0);
9935   SDLoc dl(Op);
9936   MVT VT = Op.getSimpleValueType();
9937
9938   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9939   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9940                                   DAG.getConstant(1, VT));
9941   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9942 }
9943
9944 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9945 //
9946 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9947                                       SelectionDAG &DAG) {
9948   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9949
9950   if (!Subtarget->hasSSE41())
9951     return SDValue();
9952
9953   if (!Op->hasOneUse())
9954     return SDValue();
9955
9956   SDNode *N = Op.getNode();
9957   SDLoc DL(N);
9958
9959   SmallVector<SDValue, 8> Opnds;
9960   DenseMap<SDValue, unsigned> VecInMap;
9961   SmallVector<SDValue, 8> VecIns;
9962   EVT VT = MVT::Other;
9963
9964   // Recognize a special case where a vector is casted into wide integer to
9965   // test all 0s.
9966   Opnds.push_back(N->getOperand(0));
9967   Opnds.push_back(N->getOperand(1));
9968
9969   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9970     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9971     // BFS traverse all OR'd operands.
9972     if (I->getOpcode() == ISD::OR) {
9973       Opnds.push_back(I->getOperand(0));
9974       Opnds.push_back(I->getOperand(1));
9975       // Re-evaluate the number of nodes to be traversed.
9976       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9977       continue;
9978     }
9979
9980     // Quit if a non-EXTRACT_VECTOR_ELT
9981     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9982       return SDValue();
9983
9984     // Quit if without a constant index.
9985     SDValue Idx = I->getOperand(1);
9986     if (!isa<ConstantSDNode>(Idx))
9987       return SDValue();
9988
9989     SDValue ExtractedFromVec = I->getOperand(0);
9990     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9991     if (M == VecInMap.end()) {
9992       VT = ExtractedFromVec.getValueType();
9993       // Quit if not 128/256-bit vector.
9994       if (!VT.is128BitVector() && !VT.is256BitVector())
9995         return SDValue();
9996       // Quit if not the same type.
9997       if (VecInMap.begin() != VecInMap.end() &&
9998           VT != VecInMap.begin()->first.getValueType())
9999         return SDValue();
10000       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10001       VecIns.push_back(ExtractedFromVec);
10002     }
10003     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10004   }
10005
10006   assert((VT.is128BitVector() || VT.is256BitVector()) &&
10007          "Not extracted from 128-/256-bit vector.");
10008
10009   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10010
10011   for (DenseMap<SDValue, unsigned>::const_iterator
10012         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10013     // Quit if not all elements are used.
10014     if (I->second != FullMask)
10015       return SDValue();
10016   }
10017
10018   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10019
10020   // Cast all vectors into TestVT for PTEST.
10021   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10022     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10023
10024   // If more than one full vectors are evaluated, OR them first before PTEST.
10025   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10026     // Each iteration will OR 2 nodes and append the result until there is only
10027     // 1 node left, i.e. the final OR'd value of all vectors.
10028     SDValue LHS = VecIns[Slot];
10029     SDValue RHS = VecIns[Slot + 1];
10030     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10031   }
10032
10033   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10034                      VecIns.back(), VecIns.back());
10035 }
10036
10037 /// \brief return true if \c Op has a use that doesn't just read flags.
10038 static bool hasNonFlagsUse(SDValue Op) {
10039   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10040        ++UI) {
10041     SDNode *User = *UI;
10042     unsigned UOpNo = UI.getOperandNo();
10043     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10044       // Look pass truncate.
10045       UOpNo = User->use_begin().getOperandNo();
10046       User = *User->use_begin();
10047     }
10048
10049     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10050         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10051       return true;
10052   }
10053   return false;
10054 }
10055
10056 /// Emit nodes that will be selected as "test Op0,Op0", or something
10057 /// equivalent.
10058 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10059                                     SelectionDAG &DAG) const {
10060   if (Op.getValueType() == MVT::i1)
10061     // KORTEST instruction should be selected
10062     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10063                        DAG.getConstant(0, Op.getValueType()));
10064
10065   // CF and OF aren't always set the way we want. Determine which
10066   // of these we need.
10067   bool NeedCF = false;
10068   bool NeedOF = false;
10069   switch (X86CC) {
10070   default: break;
10071   case X86::COND_A: case X86::COND_AE:
10072   case X86::COND_B: case X86::COND_BE:
10073     NeedCF = true;
10074     break;
10075   case X86::COND_G: case X86::COND_GE:
10076   case X86::COND_L: case X86::COND_LE:
10077   case X86::COND_O: case X86::COND_NO:
10078     NeedOF = true;
10079     break;
10080   }
10081   // See if we can use the EFLAGS value from the operand instead of
10082   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10083   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10084   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10085     // Emit a CMP with 0, which is the TEST pattern.
10086     //if (Op.getValueType() == MVT::i1)
10087     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10088     //                     DAG.getConstant(0, MVT::i1));
10089     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10090                        DAG.getConstant(0, Op.getValueType()));
10091   }
10092   unsigned Opcode = 0;
10093   unsigned NumOperands = 0;
10094
10095   // Truncate operations may prevent the merge of the SETCC instruction
10096   // and the arithmetic instruction before it. Attempt to truncate the operands
10097   // of the arithmetic instruction and use a reduced bit-width instruction.
10098   bool NeedTruncation = false;
10099   SDValue ArithOp = Op;
10100   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10101     SDValue Arith = Op->getOperand(0);
10102     // Both the trunc and the arithmetic op need to have one user each.
10103     if (Arith->hasOneUse())
10104       switch (Arith.getOpcode()) {
10105         default: break;
10106         case ISD::ADD:
10107         case ISD::SUB:
10108         case ISD::AND:
10109         case ISD::OR:
10110         case ISD::XOR: {
10111           NeedTruncation = true;
10112           ArithOp = Arith;
10113         }
10114       }
10115   }
10116
10117   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10118   // which may be the result of a CAST.  We use the variable 'Op', which is the
10119   // non-casted variable when we check for possible users.
10120   switch (ArithOp.getOpcode()) {
10121   case ISD::ADD:
10122     // Due to an isel shortcoming, be conservative if this add is likely to be
10123     // selected as part of a load-modify-store instruction. When the root node
10124     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10125     // uses of other nodes in the match, such as the ADD in this case. This
10126     // leads to the ADD being left around and reselected, with the result being
10127     // two adds in the output.  Alas, even if none our users are stores, that
10128     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10129     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10130     // climbing the DAG back to the root, and it doesn't seem to be worth the
10131     // effort.
10132     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10133          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10134       if (UI->getOpcode() != ISD::CopyToReg &&
10135           UI->getOpcode() != ISD::SETCC &&
10136           UI->getOpcode() != ISD::STORE)
10137         goto default_case;
10138
10139     if (ConstantSDNode *C =
10140         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10141       // An add of one will be selected as an INC.
10142       if (C->getAPIntValue() == 1) {
10143         Opcode = X86ISD::INC;
10144         NumOperands = 1;
10145         break;
10146       }
10147
10148       // An add of negative one (subtract of one) will be selected as a DEC.
10149       if (C->getAPIntValue().isAllOnesValue()) {
10150         Opcode = X86ISD::DEC;
10151         NumOperands = 1;
10152         break;
10153       }
10154     }
10155
10156     // Otherwise use a regular EFLAGS-setting add.
10157     Opcode = X86ISD::ADD;
10158     NumOperands = 2;
10159     break;
10160   case ISD::SHL:
10161   case ISD::SRL:
10162     // If we have a constant logical shift that's only used in a comparison
10163     // against zero turn it into an equivalent AND. This allows turning it into
10164     // a TEST instruction later.
10165     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10166         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10167       EVT VT = Op.getValueType();
10168       unsigned BitWidth = VT.getSizeInBits();
10169       unsigned ShAmt = Op->getConstantOperandVal(1);
10170       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10171         break;
10172       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10173                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10174                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10175       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10176         break;
10177       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10178                                 DAG.getConstant(Mask, VT));
10179       DAG.ReplaceAllUsesWith(Op, New);
10180       Op = New;
10181     }
10182     break;
10183
10184   case ISD::AND:
10185     // If the primary and result isn't used, don't bother using X86ISD::AND,
10186     // because a TEST instruction will be better.
10187     if (!hasNonFlagsUse(Op))
10188       break;
10189     // FALL THROUGH
10190   case ISD::SUB:
10191   case ISD::OR:
10192   case ISD::XOR:
10193     // Due to the ISEL shortcoming noted above, be conservative if this op is
10194     // likely to be selected as part of a load-modify-store instruction.
10195     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10196            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10197       if (UI->getOpcode() == ISD::STORE)
10198         goto default_case;
10199
10200     // Otherwise use a regular EFLAGS-setting instruction.
10201     switch (ArithOp.getOpcode()) {
10202     default: llvm_unreachable("unexpected operator!");
10203     case ISD::SUB: Opcode = X86ISD::SUB; break;
10204     case ISD::XOR: Opcode = X86ISD::XOR; break;
10205     case ISD::AND: Opcode = X86ISD::AND; break;
10206     case ISD::OR: {
10207       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10208         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10209         if (EFLAGS.getNode())
10210           return EFLAGS;
10211       }
10212       Opcode = X86ISD::OR;
10213       break;
10214     }
10215     }
10216
10217     NumOperands = 2;
10218     break;
10219   case X86ISD::ADD:
10220   case X86ISD::SUB:
10221   case X86ISD::INC:
10222   case X86ISD::DEC:
10223   case X86ISD::OR:
10224   case X86ISD::XOR:
10225   case X86ISD::AND:
10226     return SDValue(Op.getNode(), 1);
10227   default:
10228   default_case:
10229     break;
10230   }
10231
10232   // If we found that truncation is beneficial, perform the truncation and
10233   // update 'Op'.
10234   if (NeedTruncation) {
10235     EVT VT = Op.getValueType();
10236     SDValue WideVal = Op->getOperand(0);
10237     EVT WideVT = WideVal.getValueType();
10238     unsigned ConvertedOp = 0;
10239     // Use a target machine opcode to prevent further DAGCombine
10240     // optimizations that may separate the arithmetic operations
10241     // from the setcc node.
10242     switch (WideVal.getOpcode()) {
10243       default: break;
10244       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10245       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10246       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10247       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10248       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10249     }
10250
10251     if (ConvertedOp) {
10252       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10253       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10254         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10255         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10256         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10257       }
10258     }
10259   }
10260
10261   if (Opcode == 0)
10262     // Emit a CMP with 0, which is the TEST pattern.
10263     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10264                        DAG.getConstant(0, Op.getValueType()));
10265
10266   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10267   SmallVector<SDValue, 4> Ops;
10268   for (unsigned i = 0; i != NumOperands; ++i)
10269     Ops.push_back(Op.getOperand(i));
10270
10271   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10272   DAG.ReplaceAllUsesWith(Op, New);
10273   return SDValue(New.getNode(), 1);
10274 }
10275
10276 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10277 /// equivalent.
10278 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10279                                    SDLoc dl, SelectionDAG &DAG) const {
10280   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10281     if (C->getAPIntValue() == 0)
10282       return EmitTest(Op0, X86CC, dl, DAG);
10283
10284      if (Op0.getValueType() == MVT::i1)
10285        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10286   }
10287  
10288   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10289        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10290     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10291     // This avoids subregister aliasing issues. Keep the smaller reference 
10292     // if we're optimizing for size, however, as that'll allow better folding 
10293     // of memory operations.
10294     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10295         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10296              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10297         !Subtarget->isAtom()) {
10298       unsigned ExtendOp =
10299           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10300       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10301       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10302     }
10303     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10304     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10305     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10306                               Op0, Op1);
10307     return SDValue(Sub.getNode(), 1);
10308   }
10309   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10310 }
10311
10312 /// Convert a comparison if required by the subtarget.
10313 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10314                                                  SelectionDAG &DAG) const {
10315   // If the subtarget does not support the FUCOMI instruction, floating-point
10316   // comparisons have to be converted.
10317   if (Subtarget->hasCMov() ||
10318       Cmp.getOpcode() != X86ISD::CMP ||
10319       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10320       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10321     return Cmp;
10322
10323   // The instruction selector will select an FUCOM instruction instead of
10324   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10325   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10326   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10327   SDLoc dl(Cmp);
10328   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10329   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10330   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10331                             DAG.getConstant(8, MVT::i8));
10332   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10333   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10334 }
10335
10336 static bool isAllOnes(SDValue V) {
10337   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10338   return C && C->isAllOnesValue();
10339 }
10340
10341 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10342 /// if it's possible.
10343 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10344                                      SDLoc dl, SelectionDAG &DAG) const {
10345   SDValue Op0 = And.getOperand(0);
10346   SDValue Op1 = And.getOperand(1);
10347   if (Op0.getOpcode() == ISD::TRUNCATE)
10348     Op0 = Op0.getOperand(0);
10349   if (Op1.getOpcode() == ISD::TRUNCATE)
10350     Op1 = Op1.getOperand(0);
10351
10352   SDValue LHS, RHS;
10353   if (Op1.getOpcode() == ISD::SHL)
10354     std::swap(Op0, Op1);
10355   if (Op0.getOpcode() == ISD::SHL) {
10356     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10357       if (And00C->getZExtValue() == 1) {
10358         // If we looked past a truncate, check that it's only truncating away
10359         // known zeros.
10360         unsigned BitWidth = Op0.getValueSizeInBits();
10361         unsigned AndBitWidth = And.getValueSizeInBits();
10362         if (BitWidth > AndBitWidth) {
10363           APInt Zeros, Ones;
10364           DAG.computeKnownBits(Op0, Zeros, Ones);
10365           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10366             return SDValue();
10367         }
10368         LHS = Op1;
10369         RHS = Op0.getOperand(1);
10370       }
10371   } else if (Op1.getOpcode() == ISD::Constant) {
10372     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10373     uint64_t AndRHSVal = AndRHS->getZExtValue();
10374     SDValue AndLHS = Op0;
10375
10376     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10377       LHS = AndLHS.getOperand(0);
10378       RHS = AndLHS.getOperand(1);
10379     }
10380
10381     // Use BT if the immediate can't be encoded in a TEST instruction.
10382     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10383       LHS = AndLHS;
10384       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10385     }
10386   }
10387
10388   if (LHS.getNode()) {
10389     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10390     // instruction.  Since the shift amount is in-range-or-undefined, we know
10391     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10392     // the encoding for the i16 version is larger than the i32 version.
10393     // Also promote i16 to i32 for performance / code size reason.
10394     if (LHS.getValueType() == MVT::i8 ||
10395         LHS.getValueType() == MVT::i16)
10396       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10397
10398     // If the operand types disagree, extend the shift amount to match.  Since
10399     // BT ignores high bits (like shifts) we can use anyextend.
10400     if (LHS.getValueType() != RHS.getValueType())
10401       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10402
10403     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10404     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10405     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10406                        DAG.getConstant(Cond, MVT::i8), BT);
10407   }
10408
10409   return SDValue();
10410 }
10411
10412 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10413 /// mask CMPs.
10414 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10415                               SDValue &Op1) {
10416   unsigned SSECC;
10417   bool Swap = false;
10418
10419   // SSE Condition code mapping:
10420   //  0 - EQ
10421   //  1 - LT
10422   //  2 - LE
10423   //  3 - UNORD
10424   //  4 - NEQ
10425   //  5 - NLT
10426   //  6 - NLE
10427   //  7 - ORD
10428   switch (SetCCOpcode) {
10429   default: llvm_unreachable("Unexpected SETCC condition");
10430   case ISD::SETOEQ:
10431   case ISD::SETEQ:  SSECC = 0; break;
10432   case ISD::SETOGT:
10433   case ISD::SETGT:  Swap = true; // Fallthrough
10434   case ISD::SETLT:
10435   case ISD::SETOLT: SSECC = 1; break;
10436   case ISD::SETOGE:
10437   case ISD::SETGE:  Swap = true; // Fallthrough
10438   case ISD::SETLE:
10439   case ISD::SETOLE: SSECC = 2; break;
10440   case ISD::SETUO:  SSECC = 3; break;
10441   case ISD::SETUNE:
10442   case ISD::SETNE:  SSECC = 4; break;
10443   case ISD::SETULE: Swap = true; // Fallthrough
10444   case ISD::SETUGE: SSECC = 5; break;
10445   case ISD::SETULT: Swap = true; // Fallthrough
10446   case ISD::SETUGT: SSECC = 6; break;
10447   case ISD::SETO:   SSECC = 7; break;
10448   case ISD::SETUEQ:
10449   case ISD::SETONE: SSECC = 8; break;
10450   }
10451   if (Swap)
10452     std::swap(Op0, Op1);
10453
10454   return SSECC;
10455 }
10456
10457 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10458 // ones, and then concatenate the result back.
10459 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10460   MVT VT = Op.getSimpleValueType();
10461
10462   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10463          "Unsupported value type for operation");
10464
10465   unsigned NumElems = VT.getVectorNumElements();
10466   SDLoc dl(Op);
10467   SDValue CC = Op.getOperand(2);
10468
10469   // Extract the LHS vectors
10470   SDValue LHS = Op.getOperand(0);
10471   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10472   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10473
10474   // Extract the RHS vectors
10475   SDValue RHS = Op.getOperand(1);
10476   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10477   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10478
10479   // Issue the operation on the smaller types and concatenate the result back
10480   MVT EltVT = VT.getVectorElementType();
10481   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10482   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10483                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10484                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10485 }
10486
10487 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10488                                      const X86Subtarget *Subtarget) {
10489   SDValue Op0 = Op.getOperand(0);
10490   SDValue Op1 = Op.getOperand(1);
10491   SDValue CC = Op.getOperand(2);
10492   MVT VT = Op.getSimpleValueType();
10493   SDLoc dl(Op);
10494
10495   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10496          Op.getValueType().getScalarType() == MVT::i1 &&
10497          "Cannot set masked compare for this operation");
10498
10499   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10500   unsigned  Opc = 0;
10501   bool Unsigned = false;
10502   bool Swap = false;
10503   unsigned SSECC;
10504   switch (SetCCOpcode) {
10505   default: llvm_unreachable("Unexpected SETCC condition");
10506   case ISD::SETNE:  SSECC = 4; break;
10507   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10508   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10509   case ISD::SETLT:  Swap = true; //fall-through
10510   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10511   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10512   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10513   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10514   case ISD::SETULE: Unsigned = true; //fall-through
10515   case ISD::SETLE:  SSECC = 2; break;
10516   }
10517
10518   if (Swap)
10519     std::swap(Op0, Op1);
10520   if (Opc)
10521     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10522   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10523   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10524                      DAG.getConstant(SSECC, MVT::i8));
10525 }
10526
10527 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10528 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10529 /// return an empty value.
10530 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10531 {
10532   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10533   if (!BV)
10534     return SDValue();
10535
10536   MVT VT = Op1.getSimpleValueType();
10537   MVT EVT = VT.getVectorElementType();
10538   unsigned n = VT.getVectorNumElements();
10539   SmallVector<SDValue, 8> ULTOp1;
10540
10541   for (unsigned i = 0; i < n; ++i) {
10542     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10543     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10544       return SDValue();
10545
10546     // Avoid underflow.
10547     APInt Val = Elt->getAPIntValue();
10548     if (Val == 0)
10549       return SDValue();
10550
10551     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10552   }
10553
10554   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10555 }
10556
10557 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10558                            SelectionDAG &DAG) {
10559   SDValue Op0 = Op.getOperand(0);
10560   SDValue Op1 = Op.getOperand(1);
10561   SDValue CC = Op.getOperand(2);
10562   MVT VT = Op.getSimpleValueType();
10563   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10564   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10565   SDLoc dl(Op);
10566
10567   if (isFP) {
10568 #ifndef NDEBUG
10569     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10570     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10571 #endif
10572
10573     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10574     unsigned Opc = X86ISD::CMPP;
10575     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10576       assert(VT.getVectorNumElements() <= 16);
10577       Opc = X86ISD::CMPM;
10578     }
10579     // In the two special cases we can't handle, emit two comparisons.
10580     if (SSECC == 8) {
10581       unsigned CC0, CC1;
10582       unsigned CombineOpc;
10583       if (SetCCOpcode == ISD::SETUEQ) {
10584         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10585       } else {
10586         assert(SetCCOpcode == ISD::SETONE);
10587         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10588       }
10589
10590       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10591                                  DAG.getConstant(CC0, MVT::i8));
10592       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10593                                  DAG.getConstant(CC1, MVT::i8));
10594       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10595     }
10596     // Handle all other FP comparisons here.
10597     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10598                        DAG.getConstant(SSECC, MVT::i8));
10599   }
10600
10601   // Break 256-bit integer vector compare into smaller ones.
10602   if (VT.is256BitVector() && !Subtarget->hasInt256())
10603     return Lower256IntVSETCC(Op, DAG);
10604
10605   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10606   EVT OpVT = Op1.getValueType();
10607   if (Subtarget->hasAVX512()) {
10608     if (Op1.getValueType().is512BitVector() ||
10609         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10610       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10611
10612     // In AVX-512 architecture setcc returns mask with i1 elements,
10613     // But there is no compare instruction for i8 and i16 elements.
10614     // We are not talking about 512-bit operands in this case, these
10615     // types are illegal.
10616     if (MaskResult &&
10617         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10618          OpVT.getVectorElementType().getSizeInBits() >= 8))
10619       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10620                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10621   }
10622
10623   // We are handling one of the integer comparisons here.  Since SSE only has
10624   // GT and EQ comparisons for integer, swapping operands and multiple
10625   // operations may be required for some comparisons.
10626   unsigned Opc;
10627   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10628   bool Subus = false;
10629
10630   switch (SetCCOpcode) {
10631   default: llvm_unreachable("Unexpected SETCC condition");
10632   case ISD::SETNE:  Invert = true;
10633   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10634   case ISD::SETLT:  Swap = true;
10635   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10636   case ISD::SETGE:  Swap = true;
10637   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10638                     Invert = true; break;
10639   case ISD::SETULT: Swap = true;
10640   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10641                     FlipSigns = true; break;
10642   case ISD::SETUGE: Swap = true;
10643   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10644                     FlipSigns = true; Invert = true; break;
10645   }
10646
10647   // Special case: Use min/max operations for SETULE/SETUGE
10648   MVT VET = VT.getVectorElementType();
10649   bool hasMinMax =
10650        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10651     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10652
10653   if (hasMinMax) {
10654     switch (SetCCOpcode) {
10655     default: break;
10656     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10657     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10658     }
10659
10660     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10661   }
10662
10663   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10664   if (!MinMax && hasSubus) {
10665     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10666     // Op0 u<= Op1:
10667     //   t = psubus Op0, Op1
10668     //   pcmpeq t, <0..0>
10669     switch (SetCCOpcode) {
10670     default: break;
10671     case ISD::SETULT: {
10672       // If the comparison is against a constant we can turn this into a
10673       // setule.  With psubus, setule does not require a swap.  This is
10674       // beneficial because the constant in the register is no longer
10675       // destructed as the destination so it can be hoisted out of a loop.
10676       // Only do this pre-AVX since vpcmp* is no longer destructive.
10677       if (Subtarget->hasAVX())
10678         break;
10679       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10680       if (ULEOp1.getNode()) {
10681         Op1 = ULEOp1;
10682         Subus = true; Invert = false; Swap = false;
10683       }
10684       break;
10685     }
10686     // Psubus is better than flip-sign because it requires no inversion.
10687     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10688     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10689     }
10690
10691     if (Subus) {
10692       Opc = X86ISD::SUBUS;
10693       FlipSigns = false;
10694     }
10695   }
10696
10697   if (Swap)
10698     std::swap(Op0, Op1);
10699
10700   // Check that the operation in question is available (most are plain SSE2,
10701   // but PCMPGTQ and PCMPEQQ have different requirements).
10702   if (VT == MVT::v2i64) {
10703     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10704       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10705
10706       // First cast everything to the right type.
10707       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10708       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10709
10710       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10711       // bits of the inputs before performing those operations. The lower
10712       // compare is always unsigned.
10713       SDValue SB;
10714       if (FlipSigns) {
10715         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10716       } else {
10717         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10718         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10719         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10720                          Sign, Zero, Sign, Zero);
10721       }
10722       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10723       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10724
10725       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10726       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10727       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10728
10729       // Create masks for only the low parts/high parts of the 64 bit integers.
10730       static const int MaskHi[] = { 1, 1, 3, 3 };
10731       static const int MaskLo[] = { 0, 0, 2, 2 };
10732       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10733       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10734       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10735
10736       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10737       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10738
10739       if (Invert)
10740         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10741
10742       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10743     }
10744
10745     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10746       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10747       // pcmpeqd + pshufd + pand.
10748       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10749
10750       // First cast everything to the right type.
10751       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10752       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10753
10754       // Do the compare.
10755       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10756
10757       // Make sure the lower and upper halves are both all-ones.
10758       static const int Mask[] = { 1, 0, 3, 2 };
10759       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10760       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10761
10762       if (Invert)
10763         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10764
10765       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10766     }
10767   }
10768
10769   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10770   // bits of the inputs before performing those operations.
10771   if (FlipSigns) {
10772     EVT EltVT = VT.getVectorElementType();
10773     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10774     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10775     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10776   }
10777
10778   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10779
10780   // If the logical-not of the result is required, perform that now.
10781   if (Invert)
10782     Result = DAG.getNOT(dl, Result, VT);
10783
10784   if (MinMax)
10785     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10786
10787   if (Subus)
10788     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10789                          getZeroVector(VT, Subtarget, DAG, dl));
10790
10791   return Result;
10792 }
10793
10794 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10795
10796   MVT VT = Op.getSimpleValueType();
10797
10798   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10799
10800   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10801          && "SetCC type must be 8-bit or 1-bit integer");
10802   SDValue Op0 = Op.getOperand(0);
10803   SDValue Op1 = Op.getOperand(1);
10804   SDLoc dl(Op);
10805   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10806
10807   // Optimize to BT if possible.
10808   // Lower (X & (1 << N)) == 0 to BT(X, N).
10809   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10810   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10811   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10812       Op1.getOpcode() == ISD::Constant &&
10813       cast<ConstantSDNode>(Op1)->isNullValue() &&
10814       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10815     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10816     if (NewSetCC.getNode())
10817       return NewSetCC;
10818   }
10819
10820   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10821   // these.
10822   if (Op1.getOpcode() == ISD::Constant &&
10823       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10824        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10825       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10826
10827     // If the input is a setcc, then reuse the input setcc or use a new one with
10828     // the inverted condition.
10829     if (Op0.getOpcode() == X86ISD::SETCC) {
10830       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10831       bool Invert = (CC == ISD::SETNE) ^
10832         cast<ConstantSDNode>(Op1)->isNullValue();
10833       if (!Invert)
10834         return Op0;
10835
10836       CCode = X86::GetOppositeBranchCondition(CCode);
10837       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10838                                   DAG.getConstant(CCode, MVT::i8),
10839                                   Op0.getOperand(1));
10840       if (VT == MVT::i1)
10841         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10842       return SetCC;
10843     }
10844   }
10845   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10846       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10847       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10848
10849     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10850     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10851   }
10852
10853   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10854   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10855   if (X86CC == X86::COND_INVALID)
10856     return SDValue();
10857
10858   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10859   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10860   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10861                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10862   if (VT == MVT::i1)
10863     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10864   return SetCC;
10865 }
10866
10867 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10868 static bool isX86LogicalCmp(SDValue Op) {
10869   unsigned Opc = Op.getNode()->getOpcode();
10870   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10871       Opc == X86ISD::SAHF)
10872     return true;
10873   if (Op.getResNo() == 1 &&
10874       (Opc == X86ISD::ADD ||
10875        Opc == X86ISD::SUB ||
10876        Opc == X86ISD::ADC ||
10877        Opc == X86ISD::SBB ||
10878        Opc == X86ISD::SMUL ||
10879        Opc == X86ISD::UMUL ||
10880        Opc == X86ISD::INC ||
10881        Opc == X86ISD::DEC ||
10882        Opc == X86ISD::OR ||
10883        Opc == X86ISD::XOR ||
10884        Opc == X86ISD::AND))
10885     return true;
10886
10887   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10888     return true;
10889
10890   return false;
10891 }
10892
10893 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10894   if (V.getOpcode() != ISD::TRUNCATE)
10895     return false;
10896
10897   SDValue VOp0 = V.getOperand(0);
10898   unsigned InBits = VOp0.getValueSizeInBits();
10899   unsigned Bits = V.getValueSizeInBits();
10900   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10901 }
10902
10903 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10904   bool addTest = true;
10905   SDValue Cond  = Op.getOperand(0);
10906   SDValue Op1 = Op.getOperand(1);
10907   SDValue Op2 = Op.getOperand(2);
10908   SDLoc DL(Op);
10909   EVT VT = Op1.getValueType();
10910   SDValue CC;
10911
10912   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10913   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10914   // sequence later on.
10915   if (Cond.getOpcode() == ISD::SETCC &&
10916       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10917        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10918       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10919     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10920     int SSECC = translateX86FSETCC(
10921         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10922
10923     if (SSECC != 8) {
10924       if (Subtarget->hasAVX512()) {
10925         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10926                                   DAG.getConstant(SSECC, MVT::i8));
10927         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10928       }
10929       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10930                                 DAG.getConstant(SSECC, MVT::i8));
10931       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10932       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10933       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10934     }
10935   }
10936
10937   if (Cond.getOpcode() == ISD::SETCC) {
10938     SDValue NewCond = LowerSETCC(Cond, DAG);
10939     if (NewCond.getNode())
10940       Cond = NewCond;
10941   }
10942
10943   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10944   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10945   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10946   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10947   if (Cond.getOpcode() == X86ISD::SETCC &&
10948       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10949       isZero(Cond.getOperand(1).getOperand(1))) {
10950     SDValue Cmp = Cond.getOperand(1);
10951
10952     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10953
10954     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10955         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10956       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10957
10958       SDValue CmpOp0 = Cmp.getOperand(0);
10959       // Apply further optimizations for special cases
10960       // (select (x != 0), -1, 0) -> neg & sbb
10961       // (select (x == 0), 0, -1) -> neg & sbb
10962       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10963         if (YC->isNullValue() &&
10964             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10965           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10966           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10967                                     DAG.getConstant(0, CmpOp0.getValueType()),
10968                                     CmpOp0);
10969           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10970                                     DAG.getConstant(X86::COND_B, MVT::i8),
10971                                     SDValue(Neg.getNode(), 1));
10972           return Res;
10973         }
10974
10975       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10976                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10977       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10978
10979       SDValue Res =   // Res = 0 or -1.
10980         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10981                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10982
10983       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10984         Res = DAG.getNOT(DL, Res, Res.getValueType());
10985
10986       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10987       if (!N2C || !N2C->isNullValue())
10988         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10989       return Res;
10990     }
10991   }
10992
10993   // Look past (and (setcc_carry (cmp ...)), 1).
10994   if (Cond.getOpcode() == ISD::AND &&
10995       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10996     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10997     if (C && C->getAPIntValue() == 1)
10998       Cond = Cond.getOperand(0);
10999   }
11000
11001   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11002   // setting operand in place of the X86ISD::SETCC.
11003   unsigned CondOpcode = Cond.getOpcode();
11004   if (CondOpcode == X86ISD::SETCC ||
11005       CondOpcode == X86ISD::SETCC_CARRY) {
11006     CC = Cond.getOperand(0);
11007
11008     SDValue Cmp = Cond.getOperand(1);
11009     unsigned Opc = Cmp.getOpcode();
11010     MVT VT = Op.getSimpleValueType();
11011
11012     bool IllegalFPCMov = false;
11013     if (VT.isFloatingPoint() && !VT.isVector() &&
11014         !isScalarFPTypeInSSEReg(VT))  // FPStack?
11015       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11016
11017     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11018         Opc == X86ISD::BT) { // FIXME
11019       Cond = Cmp;
11020       addTest = false;
11021     }
11022   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11023              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11024              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11025               Cond.getOperand(0).getValueType() != MVT::i8)) {
11026     SDValue LHS = Cond.getOperand(0);
11027     SDValue RHS = Cond.getOperand(1);
11028     unsigned X86Opcode;
11029     unsigned X86Cond;
11030     SDVTList VTs;
11031     switch (CondOpcode) {
11032     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11033     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11034     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11035     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11036     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11037     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11038     default: llvm_unreachable("unexpected overflowing operator");
11039     }
11040     if (CondOpcode == ISD::UMULO)
11041       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11042                           MVT::i32);
11043     else
11044       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11045
11046     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11047
11048     if (CondOpcode == ISD::UMULO)
11049       Cond = X86Op.getValue(2);
11050     else
11051       Cond = X86Op.getValue(1);
11052
11053     CC = DAG.getConstant(X86Cond, MVT::i8);
11054     addTest = false;
11055   }
11056
11057   if (addTest) {
11058     // Look pass the truncate if the high bits are known zero.
11059     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11060         Cond = Cond.getOperand(0);
11061
11062     // We know the result of AND is compared against zero. Try to match
11063     // it to BT.
11064     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11065       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11066       if (NewSetCC.getNode()) {
11067         CC = NewSetCC.getOperand(0);
11068         Cond = NewSetCC.getOperand(1);
11069         addTest = false;
11070       }
11071     }
11072   }
11073
11074   if (addTest) {
11075     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11076     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11077   }
11078
11079   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11080   // a <  b ?  0 : -1 -> RES = setcc_carry
11081   // a >= b ? -1 :  0 -> RES = setcc_carry
11082   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11083   if (Cond.getOpcode() == X86ISD::SUB) {
11084     Cond = ConvertCmpIfNecessary(Cond, DAG);
11085     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11086
11087     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11088         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11089       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11090                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11091       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11092         return DAG.getNOT(DL, Res, Res.getValueType());
11093       return Res;
11094     }
11095   }
11096
11097   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11098   // widen the cmov and push the truncate through. This avoids introducing a new
11099   // branch during isel and doesn't add any extensions.
11100   if (Op.getValueType() == MVT::i8 &&
11101       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11102     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11103     if (T1.getValueType() == T2.getValueType() &&
11104         // Blacklist CopyFromReg to avoid partial register stalls.
11105         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11106       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11107       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11108       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11109     }
11110   }
11111
11112   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11113   // condition is true.
11114   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11115   SDValue Ops[] = { Op2, Op1, CC, Cond };
11116   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11117 }
11118
11119 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11120   MVT VT = Op->getSimpleValueType(0);
11121   SDValue In = Op->getOperand(0);
11122   MVT InVT = In.getSimpleValueType();
11123   SDLoc dl(Op);
11124
11125   unsigned int NumElts = VT.getVectorNumElements();
11126   if (NumElts != 8 && NumElts != 16)
11127     return SDValue();
11128
11129   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11130     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11131
11132   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11133   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11134
11135   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11136   Constant *C = ConstantInt::get(*DAG.getContext(),
11137     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11138
11139   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11140   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11141   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11142                           MachinePointerInfo::getConstantPool(),
11143                           false, false, false, Alignment);
11144   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11145   if (VT.is512BitVector())
11146     return Brcst;
11147   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11148 }
11149
11150 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11151                                 SelectionDAG &DAG) {
11152   MVT VT = Op->getSimpleValueType(0);
11153   SDValue In = Op->getOperand(0);
11154   MVT InVT = In.getSimpleValueType();
11155   SDLoc dl(Op);
11156
11157   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11158     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11159
11160   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11161       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11162       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11163     return SDValue();
11164
11165   if (Subtarget->hasInt256())
11166     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11167
11168   // Optimize vectors in AVX mode
11169   // Sign extend  v8i16 to v8i32 and
11170   //              v4i32 to v4i64
11171   //
11172   // Divide input vector into two parts
11173   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11174   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11175   // concat the vectors to original VT
11176
11177   unsigned NumElems = InVT.getVectorNumElements();
11178   SDValue Undef = DAG.getUNDEF(InVT);
11179
11180   SmallVector<int,8> ShufMask1(NumElems, -1);
11181   for (unsigned i = 0; i != NumElems/2; ++i)
11182     ShufMask1[i] = i;
11183
11184   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11185
11186   SmallVector<int,8> ShufMask2(NumElems, -1);
11187   for (unsigned i = 0; i != NumElems/2; ++i)
11188     ShufMask2[i] = i + NumElems/2;
11189
11190   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11191
11192   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11193                                 VT.getVectorNumElements()/2);
11194
11195   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11196   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11197
11198   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11199 }
11200
11201 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11202 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11203 // from the AND / OR.
11204 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11205   Opc = Op.getOpcode();
11206   if (Opc != ISD::OR && Opc != ISD::AND)
11207     return false;
11208   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11209           Op.getOperand(0).hasOneUse() &&
11210           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11211           Op.getOperand(1).hasOneUse());
11212 }
11213
11214 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11215 // 1 and that the SETCC node has a single use.
11216 static bool isXor1OfSetCC(SDValue Op) {
11217   if (Op.getOpcode() != ISD::XOR)
11218     return false;
11219   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11220   if (N1C && N1C->getAPIntValue() == 1) {
11221     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11222       Op.getOperand(0).hasOneUse();
11223   }
11224   return false;
11225 }
11226
11227 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11228   bool addTest = true;
11229   SDValue Chain = Op.getOperand(0);
11230   SDValue Cond  = Op.getOperand(1);
11231   SDValue Dest  = Op.getOperand(2);
11232   SDLoc dl(Op);
11233   SDValue CC;
11234   bool Inverted = false;
11235
11236   if (Cond.getOpcode() == ISD::SETCC) {
11237     // Check for setcc([su]{add,sub,mul}o == 0).
11238     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11239         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11240         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11241         Cond.getOperand(0).getResNo() == 1 &&
11242         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11243          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11244          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11245          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11246          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11247          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11248       Inverted = true;
11249       Cond = Cond.getOperand(0);
11250     } else {
11251       SDValue NewCond = LowerSETCC(Cond, DAG);
11252       if (NewCond.getNode())
11253         Cond = NewCond;
11254     }
11255   }
11256 #if 0
11257   // FIXME: LowerXALUO doesn't handle these!!
11258   else if (Cond.getOpcode() == X86ISD::ADD  ||
11259            Cond.getOpcode() == X86ISD::SUB  ||
11260            Cond.getOpcode() == X86ISD::SMUL ||
11261            Cond.getOpcode() == X86ISD::UMUL)
11262     Cond = LowerXALUO(Cond, DAG);
11263 #endif
11264
11265   // Look pass (and (setcc_carry (cmp ...)), 1).
11266   if (Cond.getOpcode() == ISD::AND &&
11267       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11268     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11269     if (C && C->getAPIntValue() == 1)
11270       Cond = Cond.getOperand(0);
11271   }
11272
11273   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11274   // setting operand in place of the X86ISD::SETCC.
11275   unsigned CondOpcode = Cond.getOpcode();
11276   if (CondOpcode == X86ISD::SETCC ||
11277       CondOpcode == X86ISD::SETCC_CARRY) {
11278     CC = Cond.getOperand(0);
11279
11280     SDValue Cmp = Cond.getOperand(1);
11281     unsigned Opc = Cmp.getOpcode();
11282     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11283     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11284       Cond = Cmp;
11285       addTest = false;
11286     } else {
11287       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11288       default: break;
11289       case X86::COND_O:
11290       case X86::COND_B:
11291         // These can only come from an arithmetic instruction with overflow,
11292         // e.g. SADDO, UADDO.
11293         Cond = Cond.getNode()->getOperand(1);
11294         addTest = false;
11295         break;
11296       }
11297     }
11298   }
11299   CondOpcode = Cond.getOpcode();
11300   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11301       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11302       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11303        Cond.getOperand(0).getValueType() != MVT::i8)) {
11304     SDValue LHS = Cond.getOperand(0);
11305     SDValue RHS = Cond.getOperand(1);
11306     unsigned X86Opcode;
11307     unsigned X86Cond;
11308     SDVTList VTs;
11309     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11310     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11311     // X86ISD::INC).
11312     switch (CondOpcode) {
11313     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11314     case ISD::SADDO:
11315       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11316         if (C->isOne()) {
11317           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11318           break;
11319         }
11320       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11321     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11322     case ISD::SSUBO:
11323       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11324         if (C->isOne()) {
11325           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11326           break;
11327         }
11328       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11329     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11330     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11331     default: llvm_unreachable("unexpected overflowing operator");
11332     }
11333     if (Inverted)
11334       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11335     if (CondOpcode == ISD::UMULO)
11336       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11337                           MVT::i32);
11338     else
11339       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11340
11341     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11342
11343     if (CondOpcode == ISD::UMULO)
11344       Cond = X86Op.getValue(2);
11345     else
11346       Cond = X86Op.getValue(1);
11347
11348     CC = DAG.getConstant(X86Cond, MVT::i8);
11349     addTest = false;
11350   } else {
11351     unsigned CondOpc;
11352     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11353       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11354       if (CondOpc == ISD::OR) {
11355         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11356         // two branches instead of an explicit OR instruction with a
11357         // separate test.
11358         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11359             isX86LogicalCmp(Cmp)) {
11360           CC = Cond.getOperand(0).getOperand(0);
11361           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11362                               Chain, Dest, CC, Cmp);
11363           CC = Cond.getOperand(1).getOperand(0);
11364           Cond = Cmp;
11365           addTest = false;
11366         }
11367       } else { // ISD::AND
11368         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11369         // two branches instead of an explicit AND instruction with a
11370         // separate test. However, we only do this if this block doesn't
11371         // have a fall-through edge, because this requires an explicit
11372         // jmp when the condition is false.
11373         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11374             isX86LogicalCmp(Cmp) &&
11375             Op.getNode()->hasOneUse()) {
11376           X86::CondCode CCode =
11377             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11378           CCode = X86::GetOppositeBranchCondition(CCode);
11379           CC = DAG.getConstant(CCode, MVT::i8);
11380           SDNode *User = *Op.getNode()->use_begin();
11381           // Look for an unconditional branch following this conditional branch.
11382           // We need this because we need to reverse the successors in order
11383           // to implement FCMP_OEQ.
11384           if (User->getOpcode() == ISD::BR) {
11385             SDValue FalseBB = User->getOperand(1);
11386             SDNode *NewBR =
11387               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11388             assert(NewBR == User);
11389             (void)NewBR;
11390             Dest = FalseBB;
11391
11392             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11393                                 Chain, Dest, CC, Cmp);
11394             X86::CondCode CCode =
11395               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11396             CCode = X86::GetOppositeBranchCondition(CCode);
11397             CC = DAG.getConstant(CCode, MVT::i8);
11398             Cond = Cmp;
11399             addTest = false;
11400           }
11401         }
11402       }
11403     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11404       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11405       // It should be transformed during dag combiner except when the condition
11406       // is set by a arithmetics with overflow node.
11407       X86::CondCode CCode =
11408         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11409       CCode = X86::GetOppositeBranchCondition(CCode);
11410       CC = DAG.getConstant(CCode, MVT::i8);
11411       Cond = Cond.getOperand(0).getOperand(1);
11412       addTest = false;
11413     } else if (Cond.getOpcode() == ISD::SETCC &&
11414                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11415       // For FCMP_OEQ, we can emit
11416       // two branches instead of an explicit AND instruction with a
11417       // separate test. However, we only do this if this block doesn't
11418       // have a fall-through edge, because this requires an explicit
11419       // jmp when the condition is false.
11420       if (Op.getNode()->hasOneUse()) {
11421         SDNode *User = *Op.getNode()->use_begin();
11422         // Look for an unconditional branch following this conditional branch.
11423         // We need this because we need to reverse the successors in order
11424         // to implement FCMP_OEQ.
11425         if (User->getOpcode() == ISD::BR) {
11426           SDValue FalseBB = User->getOperand(1);
11427           SDNode *NewBR =
11428             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11429           assert(NewBR == User);
11430           (void)NewBR;
11431           Dest = FalseBB;
11432
11433           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11434                                     Cond.getOperand(0), Cond.getOperand(1));
11435           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11436           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11437           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11438                               Chain, Dest, CC, Cmp);
11439           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11440           Cond = Cmp;
11441           addTest = false;
11442         }
11443       }
11444     } else if (Cond.getOpcode() == ISD::SETCC &&
11445                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11446       // For FCMP_UNE, we can emit
11447       // two branches instead of an explicit AND instruction with a
11448       // separate test. However, we only do this if this block doesn't
11449       // have a fall-through edge, because this requires an explicit
11450       // jmp when the condition is false.
11451       if (Op.getNode()->hasOneUse()) {
11452         SDNode *User = *Op.getNode()->use_begin();
11453         // Look for an unconditional branch following this conditional branch.
11454         // We need this because we need to reverse the successors in order
11455         // to implement FCMP_UNE.
11456         if (User->getOpcode() == ISD::BR) {
11457           SDValue FalseBB = User->getOperand(1);
11458           SDNode *NewBR =
11459             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11460           assert(NewBR == User);
11461           (void)NewBR;
11462
11463           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11464                                     Cond.getOperand(0), Cond.getOperand(1));
11465           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11466           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11467           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11468                               Chain, Dest, CC, Cmp);
11469           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11470           Cond = Cmp;
11471           addTest = false;
11472           Dest = FalseBB;
11473         }
11474       }
11475     }
11476   }
11477
11478   if (addTest) {
11479     // Look pass the truncate if the high bits are known zero.
11480     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11481         Cond = Cond.getOperand(0);
11482
11483     // We know the result of AND is compared against zero. Try to match
11484     // it to BT.
11485     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11486       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11487       if (NewSetCC.getNode()) {
11488         CC = NewSetCC.getOperand(0);
11489         Cond = NewSetCC.getOperand(1);
11490         addTest = false;
11491       }
11492     }
11493   }
11494
11495   if (addTest) {
11496     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11497     CC = DAG.getConstant(X86Cond, MVT::i8);
11498     Cond = EmitTest(Cond, X86Cond, dl, DAG);
11499   }
11500   Cond = ConvertCmpIfNecessary(Cond, DAG);
11501   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11502                      Chain, Dest, CC, Cond);
11503 }
11504
11505 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11506 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11507 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11508 // that the guard pages used by the OS virtual memory manager are allocated in
11509 // correct sequence.
11510 SDValue
11511 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11512                                            SelectionDAG &DAG) const {
11513   MachineFunction &MF = DAG.getMachineFunction();
11514   bool SplitStack = MF.shouldSplitStack();
11515   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11516                SplitStack;
11517   SDLoc dl(Op);
11518
11519   if (!Lower) {
11520     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11521     SDNode* Node = Op.getNode();
11522
11523     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11524     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11525         " not tell us which reg is the stack pointer!");
11526     EVT VT = Node->getValueType(0);
11527     SDValue Tmp1 = SDValue(Node, 0);
11528     SDValue Tmp2 = SDValue(Node, 1);
11529     SDValue Tmp3 = Node->getOperand(2);
11530     SDValue Chain = Tmp1.getOperand(0);
11531
11532     // Chain the dynamic stack allocation so that it doesn't modify the stack
11533     // pointer when other instructions are using the stack.
11534     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11535         SDLoc(Node));
11536
11537     SDValue Size = Tmp2.getOperand(1);
11538     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11539     Chain = SP.getValue(1);
11540     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11541     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11542     unsigned StackAlign = TFI.getStackAlignment();
11543     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11544     if (Align > StackAlign)
11545       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11546           DAG.getConstant(-(uint64_t)Align, VT));
11547     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11548
11549     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11550         DAG.getIntPtrConstant(0, true), SDValue(),
11551         SDLoc(Node));
11552
11553     SDValue Ops[2] = { Tmp1, Tmp2 };
11554     return DAG.getMergeValues(Ops, dl);
11555   }
11556
11557   // Get the inputs.
11558   SDValue Chain = Op.getOperand(0);
11559   SDValue Size  = Op.getOperand(1);
11560   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11561   EVT VT = Op.getNode()->getValueType(0);
11562
11563   bool Is64Bit = Subtarget->is64Bit();
11564   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11565
11566   if (SplitStack) {
11567     MachineRegisterInfo &MRI = MF.getRegInfo();
11568
11569     if (Is64Bit) {
11570       // The 64 bit implementation of segmented stacks needs to clobber both r10
11571       // r11. This makes it impossible to use it along with nested parameters.
11572       const Function *F = MF.getFunction();
11573
11574       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11575            I != E; ++I)
11576         if (I->hasNestAttr())
11577           report_fatal_error("Cannot use segmented stacks with functions that "
11578                              "have nested arguments.");
11579     }
11580
11581     const TargetRegisterClass *AddrRegClass =
11582       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11583     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11584     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11585     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11586                                 DAG.getRegister(Vreg, SPTy));
11587     SDValue Ops1[2] = { Value, Chain };
11588     return DAG.getMergeValues(Ops1, dl);
11589   } else {
11590     SDValue Flag;
11591     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11592
11593     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11594     Flag = Chain.getValue(1);
11595     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11596
11597     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11598
11599     const X86RegisterInfo *RegInfo =
11600       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11601     unsigned SPReg = RegInfo->getStackRegister();
11602     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11603     Chain = SP.getValue(1);
11604
11605     if (Align) {
11606       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11607                        DAG.getConstant(-(uint64_t)Align, VT));
11608       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11609     }
11610
11611     SDValue Ops1[2] = { SP, Chain };
11612     return DAG.getMergeValues(Ops1, dl);
11613   }
11614 }
11615
11616 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11617   MachineFunction &MF = DAG.getMachineFunction();
11618   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11619
11620   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11621   SDLoc DL(Op);
11622
11623   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11624     // vastart just stores the address of the VarArgsFrameIndex slot into the
11625     // memory location argument.
11626     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11627                                    getPointerTy());
11628     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11629                         MachinePointerInfo(SV), false, false, 0);
11630   }
11631
11632   // __va_list_tag:
11633   //   gp_offset         (0 - 6 * 8)
11634   //   fp_offset         (48 - 48 + 8 * 16)
11635   //   overflow_arg_area (point to parameters coming in memory).
11636   //   reg_save_area
11637   SmallVector<SDValue, 8> MemOps;
11638   SDValue FIN = Op.getOperand(1);
11639   // Store gp_offset
11640   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11641                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11642                                                MVT::i32),
11643                                FIN, MachinePointerInfo(SV), false, false, 0);
11644   MemOps.push_back(Store);
11645
11646   // Store fp_offset
11647   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11648                     FIN, DAG.getIntPtrConstant(4));
11649   Store = DAG.getStore(Op.getOperand(0), DL,
11650                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11651                                        MVT::i32),
11652                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11653   MemOps.push_back(Store);
11654
11655   // Store ptr to overflow_arg_area
11656   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11657                     FIN, DAG.getIntPtrConstant(4));
11658   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11659                                     getPointerTy());
11660   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11661                        MachinePointerInfo(SV, 8),
11662                        false, false, 0);
11663   MemOps.push_back(Store);
11664
11665   // Store ptr to reg_save_area.
11666   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11667                     FIN, DAG.getIntPtrConstant(8));
11668   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11669                                     getPointerTy());
11670   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11671                        MachinePointerInfo(SV, 16), false, false, 0);
11672   MemOps.push_back(Store);
11673   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11674 }
11675
11676 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11677   assert(Subtarget->is64Bit() &&
11678          "LowerVAARG only handles 64-bit va_arg!");
11679   assert((Subtarget->isTargetLinux() ||
11680           Subtarget->isTargetDarwin()) &&
11681           "Unhandled target in LowerVAARG");
11682   assert(Op.getNode()->getNumOperands() == 4);
11683   SDValue Chain = Op.getOperand(0);
11684   SDValue SrcPtr = Op.getOperand(1);
11685   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11686   unsigned Align = Op.getConstantOperandVal(3);
11687   SDLoc dl(Op);
11688
11689   EVT ArgVT = Op.getNode()->getValueType(0);
11690   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11691   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11692   uint8_t ArgMode;
11693
11694   // Decide which area this value should be read from.
11695   // TODO: Implement the AMD64 ABI in its entirety. This simple
11696   // selection mechanism works only for the basic types.
11697   if (ArgVT == MVT::f80) {
11698     llvm_unreachable("va_arg for f80 not yet implemented");
11699   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11700     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11701   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11702     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11703   } else {
11704     llvm_unreachable("Unhandled argument type in LowerVAARG");
11705   }
11706
11707   if (ArgMode == 2) {
11708     // Sanity Check: Make sure using fp_offset makes sense.
11709     assert(!getTargetMachine().Options.UseSoftFloat &&
11710            !(DAG.getMachineFunction()
11711                 .getFunction()->getAttributes()
11712                 .hasAttribute(AttributeSet::FunctionIndex,
11713                               Attribute::NoImplicitFloat)) &&
11714            Subtarget->hasSSE1());
11715   }
11716
11717   // Insert VAARG_64 node into the DAG
11718   // VAARG_64 returns two values: Variable Argument Address, Chain
11719   SmallVector<SDValue, 11> InstOps;
11720   InstOps.push_back(Chain);
11721   InstOps.push_back(SrcPtr);
11722   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11723   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11724   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11725   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11726   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11727                                           VTs, InstOps, MVT::i64,
11728                                           MachinePointerInfo(SV),
11729                                           /*Align=*/0,
11730                                           /*Volatile=*/false,
11731                                           /*ReadMem=*/true,
11732                                           /*WriteMem=*/true);
11733   Chain = VAARG.getValue(1);
11734
11735   // Load the next argument and return it
11736   return DAG.getLoad(ArgVT, dl,
11737                      Chain,
11738                      VAARG,
11739                      MachinePointerInfo(),
11740                      false, false, false, 0);
11741 }
11742
11743 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11744                            SelectionDAG &DAG) {
11745   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11746   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11747   SDValue Chain = Op.getOperand(0);
11748   SDValue DstPtr = Op.getOperand(1);
11749   SDValue SrcPtr = Op.getOperand(2);
11750   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11751   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11752   SDLoc DL(Op);
11753
11754   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11755                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11756                        false,
11757                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11758 }
11759
11760 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11761 // amount is a constant. Takes immediate version of shift as input.
11762 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11763                                           SDValue SrcOp, uint64_t ShiftAmt,
11764                                           SelectionDAG &DAG) {
11765   MVT ElementType = VT.getVectorElementType();
11766
11767   // Fold this packed shift into its first operand if ShiftAmt is 0.
11768   if (ShiftAmt == 0)
11769     return SrcOp;
11770
11771   // Check for ShiftAmt >= element width
11772   if (ShiftAmt >= ElementType.getSizeInBits()) {
11773     if (Opc == X86ISD::VSRAI)
11774       ShiftAmt = ElementType.getSizeInBits() - 1;
11775     else
11776       return DAG.getConstant(0, VT);
11777   }
11778
11779   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11780          && "Unknown target vector shift-by-constant node");
11781
11782   // Fold this packed vector shift into a build vector if SrcOp is a
11783   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11784   if (VT == SrcOp.getSimpleValueType() &&
11785       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11786     SmallVector<SDValue, 8> Elts;
11787     unsigned NumElts = SrcOp->getNumOperands();
11788     ConstantSDNode *ND;
11789
11790     switch(Opc) {
11791     default: llvm_unreachable(nullptr);
11792     case X86ISD::VSHLI:
11793       for (unsigned i=0; i!=NumElts; ++i) {
11794         SDValue CurrentOp = SrcOp->getOperand(i);
11795         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11796           Elts.push_back(CurrentOp);
11797           continue;
11798         }
11799         ND = cast<ConstantSDNode>(CurrentOp);
11800         const APInt &C = ND->getAPIntValue();
11801         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11802       }
11803       break;
11804     case X86ISD::VSRLI:
11805       for (unsigned i=0; i!=NumElts; ++i) {
11806         SDValue CurrentOp = SrcOp->getOperand(i);
11807         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11808           Elts.push_back(CurrentOp);
11809           continue;
11810         }
11811         ND = cast<ConstantSDNode>(CurrentOp);
11812         const APInt &C = ND->getAPIntValue();
11813         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11814       }
11815       break;
11816     case X86ISD::VSRAI:
11817       for (unsigned i=0; i!=NumElts; ++i) {
11818         SDValue CurrentOp = SrcOp->getOperand(i);
11819         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11820           Elts.push_back(CurrentOp);
11821           continue;
11822         }
11823         ND = cast<ConstantSDNode>(CurrentOp);
11824         const APInt &C = ND->getAPIntValue();
11825         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11826       }
11827       break;
11828     }
11829
11830     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11831   }
11832
11833   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11834 }
11835
11836 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11837 // may or may not be a constant. Takes immediate version of shift as input.
11838 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11839                                    SDValue SrcOp, SDValue ShAmt,
11840                                    SelectionDAG &DAG) {
11841   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11842
11843   // Catch shift-by-constant.
11844   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11845     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11846                                       CShAmt->getZExtValue(), DAG);
11847
11848   // Change opcode to non-immediate version
11849   switch (Opc) {
11850     default: llvm_unreachable("Unknown target vector shift node");
11851     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11852     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11853     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11854   }
11855
11856   // Need to build a vector containing shift amount
11857   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11858   SDValue ShOps[4];
11859   ShOps[0] = ShAmt;
11860   ShOps[1] = DAG.getConstant(0, MVT::i32);
11861   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11862   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11863
11864   // The return type has to be a 128-bit type with the same element
11865   // type as the input type.
11866   MVT EltVT = VT.getVectorElementType();
11867   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11868
11869   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11870   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11871 }
11872
11873 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11874   SDLoc dl(Op);
11875   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11876   switch (IntNo) {
11877   default: return SDValue();    // Don't custom lower most intrinsics.
11878   // Comparison intrinsics.
11879   case Intrinsic::x86_sse_comieq_ss:
11880   case Intrinsic::x86_sse_comilt_ss:
11881   case Intrinsic::x86_sse_comile_ss:
11882   case Intrinsic::x86_sse_comigt_ss:
11883   case Intrinsic::x86_sse_comige_ss:
11884   case Intrinsic::x86_sse_comineq_ss:
11885   case Intrinsic::x86_sse_ucomieq_ss:
11886   case Intrinsic::x86_sse_ucomilt_ss:
11887   case Intrinsic::x86_sse_ucomile_ss:
11888   case Intrinsic::x86_sse_ucomigt_ss:
11889   case Intrinsic::x86_sse_ucomige_ss:
11890   case Intrinsic::x86_sse_ucomineq_ss:
11891   case Intrinsic::x86_sse2_comieq_sd:
11892   case Intrinsic::x86_sse2_comilt_sd:
11893   case Intrinsic::x86_sse2_comile_sd:
11894   case Intrinsic::x86_sse2_comigt_sd:
11895   case Intrinsic::x86_sse2_comige_sd:
11896   case Intrinsic::x86_sse2_comineq_sd:
11897   case Intrinsic::x86_sse2_ucomieq_sd:
11898   case Intrinsic::x86_sse2_ucomilt_sd:
11899   case Intrinsic::x86_sse2_ucomile_sd:
11900   case Intrinsic::x86_sse2_ucomigt_sd:
11901   case Intrinsic::x86_sse2_ucomige_sd:
11902   case Intrinsic::x86_sse2_ucomineq_sd: {
11903     unsigned Opc;
11904     ISD::CondCode CC;
11905     switch (IntNo) {
11906     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11907     case Intrinsic::x86_sse_comieq_ss:
11908     case Intrinsic::x86_sse2_comieq_sd:
11909       Opc = X86ISD::COMI;
11910       CC = ISD::SETEQ;
11911       break;
11912     case Intrinsic::x86_sse_comilt_ss:
11913     case Intrinsic::x86_sse2_comilt_sd:
11914       Opc = X86ISD::COMI;
11915       CC = ISD::SETLT;
11916       break;
11917     case Intrinsic::x86_sse_comile_ss:
11918     case Intrinsic::x86_sse2_comile_sd:
11919       Opc = X86ISD::COMI;
11920       CC = ISD::SETLE;
11921       break;
11922     case Intrinsic::x86_sse_comigt_ss:
11923     case Intrinsic::x86_sse2_comigt_sd:
11924       Opc = X86ISD::COMI;
11925       CC = ISD::SETGT;
11926       break;
11927     case Intrinsic::x86_sse_comige_ss:
11928     case Intrinsic::x86_sse2_comige_sd:
11929       Opc = X86ISD::COMI;
11930       CC = ISD::SETGE;
11931       break;
11932     case Intrinsic::x86_sse_comineq_ss:
11933     case Intrinsic::x86_sse2_comineq_sd:
11934       Opc = X86ISD::COMI;
11935       CC = ISD::SETNE;
11936       break;
11937     case Intrinsic::x86_sse_ucomieq_ss:
11938     case Intrinsic::x86_sse2_ucomieq_sd:
11939       Opc = X86ISD::UCOMI;
11940       CC = ISD::SETEQ;
11941       break;
11942     case Intrinsic::x86_sse_ucomilt_ss:
11943     case Intrinsic::x86_sse2_ucomilt_sd:
11944       Opc = X86ISD::UCOMI;
11945       CC = ISD::SETLT;
11946       break;
11947     case Intrinsic::x86_sse_ucomile_ss:
11948     case Intrinsic::x86_sse2_ucomile_sd:
11949       Opc = X86ISD::UCOMI;
11950       CC = ISD::SETLE;
11951       break;
11952     case Intrinsic::x86_sse_ucomigt_ss:
11953     case Intrinsic::x86_sse2_ucomigt_sd:
11954       Opc = X86ISD::UCOMI;
11955       CC = ISD::SETGT;
11956       break;
11957     case Intrinsic::x86_sse_ucomige_ss:
11958     case Intrinsic::x86_sse2_ucomige_sd:
11959       Opc = X86ISD::UCOMI;
11960       CC = ISD::SETGE;
11961       break;
11962     case Intrinsic::x86_sse_ucomineq_ss:
11963     case Intrinsic::x86_sse2_ucomineq_sd:
11964       Opc = X86ISD::UCOMI;
11965       CC = ISD::SETNE;
11966       break;
11967     }
11968
11969     SDValue LHS = Op.getOperand(1);
11970     SDValue RHS = Op.getOperand(2);
11971     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11972     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11973     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11974     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11975                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11976     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11977   }
11978
11979   // Arithmetic intrinsics.
11980   case Intrinsic::x86_sse2_pmulu_dq:
11981   case Intrinsic::x86_avx2_pmulu_dq:
11982     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11983                        Op.getOperand(1), Op.getOperand(2));
11984
11985   case Intrinsic::x86_sse41_pmuldq:
11986   case Intrinsic::x86_avx2_pmul_dq:
11987     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11988                        Op.getOperand(1), Op.getOperand(2));
11989
11990   case Intrinsic::x86_sse2_pmulhu_w:
11991   case Intrinsic::x86_avx2_pmulhu_w:
11992     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11993                        Op.getOperand(1), Op.getOperand(2));
11994
11995   case Intrinsic::x86_sse2_pmulh_w:
11996   case Intrinsic::x86_avx2_pmulh_w:
11997     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11998                        Op.getOperand(1), Op.getOperand(2));
11999
12000   // SSE2/AVX2 sub with unsigned saturation intrinsics
12001   case Intrinsic::x86_sse2_psubus_b:
12002   case Intrinsic::x86_sse2_psubus_w:
12003   case Intrinsic::x86_avx2_psubus_b:
12004   case Intrinsic::x86_avx2_psubus_w:
12005     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12006                        Op.getOperand(1), Op.getOperand(2));
12007
12008   // SSE3/AVX horizontal add/sub intrinsics
12009   case Intrinsic::x86_sse3_hadd_ps:
12010   case Intrinsic::x86_sse3_hadd_pd:
12011   case Intrinsic::x86_avx_hadd_ps_256:
12012   case Intrinsic::x86_avx_hadd_pd_256:
12013   case Intrinsic::x86_sse3_hsub_ps:
12014   case Intrinsic::x86_sse3_hsub_pd:
12015   case Intrinsic::x86_avx_hsub_ps_256:
12016   case Intrinsic::x86_avx_hsub_pd_256:
12017   case Intrinsic::x86_ssse3_phadd_w_128:
12018   case Intrinsic::x86_ssse3_phadd_d_128:
12019   case Intrinsic::x86_avx2_phadd_w:
12020   case Intrinsic::x86_avx2_phadd_d:
12021   case Intrinsic::x86_ssse3_phsub_w_128:
12022   case Intrinsic::x86_ssse3_phsub_d_128:
12023   case Intrinsic::x86_avx2_phsub_w:
12024   case Intrinsic::x86_avx2_phsub_d: {
12025     unsigned Opcode;
12026     switch (IntNo) {
12027     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12028     case Intrinsic::x86_sse3_hadd_ps:
12029     case Intrinsic::x86_sse3_hadd_pd:
12030     case Intrinsic::x86_avx_hadd_ps_256:
12031     case Intrinsic::x86_avx_hadd_pd_256:
12032       Opcode = X86ISD::FHADD;
12033       break;
12034     case Intrinsic::x86_sse3_hsub_ps:
12035     case Intrinsic::x86_sse3_hsub_pd:
12036     case Intrinsic::x86_avx_hsub_ps_256:
12037     case Intrinsic::x86_avx_hsub_pd_256:
12038       Opcode = X86ISD::FHSUB;
12039       break;
12040     case Intrinsic::x86_ssse3_phadd_w_128:
12041     case Intrinsic::x86_ssse3_phadd_d_128:
12042     case Intrinsic::x86_avx2_phadd_w:
12043     case Intrinsic::x86_avx2_phadd_d:
12044       Opcode = X86ISD::HADD;
12045       break;
12046     case Intrinsic::x86_ssse3_phsub_w_128:
12047     case Intrinsic::x86_ssse3_phsub_d_128:
12048     case Intrinsic::x86_avx2_phsub_w:
12049     case Intrinsic::x86_avx2_phsub_d:
12050       Opcode = X86ISD::HSUB;
12051       break;
12052     }
12053     return DAG.getNode(Opcode, dl, Op.getValueType(),
12054                        Op.getOperand(1), Op.getOperand(2));
12055   }
12056
12057   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12058   case Intrinsic::x86_sse2_pmaxu_b:
12059   case Intrinsic::x86_sse41_pmaxuw:
12060   case Intrinsic::x86_sse41_pmaxud:
12061   case Intrinsic::x86_avx2_pmaxu_b:
12062   case Intrinsic::x86_avx2_pmaxu_w:
12063   case Intrinsic::x86_avx2_pmaxu_d:
12064   case Intrinsic::x86_sse2_pminu_b:
12065   case Intrinsic::x86_sse41_pminuw:
12066   case Intrinsic::x86_sse41_pminud:
12067   case Intrinsic::x86_avx2_pminu_b:
12068   case Intrinsic::x86_avx2_pminu_w:
12069   case Intrinsic::x86_avx2_pminu_d:
12070   case Intrinsic::x86_sse41_pmaxsb:
12071   case Intrinsic::x86_sse2_pmaxs_w:
12072   case Intrinsic::x86_sse41_pmaxsd:
12073   case Intrinsic::x86_avx2_pmaxs_b:
12074   case Intrinsic::x86_avx2_pmaxs_w:
12075   case Intrinsic::x86_avx2_pmaxs_d:
12076   case Intrinsic::x86_sse41_pminsb:
12077   case Intrinsic::x86_sse2_pmins_w:
12078   case Intrinsic::x86_sse41_pminsd:
12079   case Intrinsic::x86_avx2_pmins_b:
12080   case Intrinsic::x86_avx2_pmins_w:
12081   case Intrinsic::x86_avx2_pmins_d: {
12082     unsigned Opcode;
12083     switch (IntNo) {
12084     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12085     case Intrinsic::x86_sse2_pmaxu_b:
12086     case Intrinsic::x86_sse41_pmaxuw:
12087     case Intrinsic::x86_sse41_pmaxud:
12088     case Intrinsic::x86_avx2_pmaxu_b:
12089     case Intrinsic::x86_avx2_pmaxu_w:
12090     case Intrinsic::x86_avx2_pmaxu_d:
12091       Opcode = X86ISD::UMAX;
12092       break;
12093     case Intrinsic::x86_sse2_pminu_b:
12094     case Intrinsic::x86_sse41_pminuw:
12095     case Intrinsic::x86_sse41_pminud:
12096     case Intrinsic::x86_avx2_pminu_b:
12097     case Intrinsic::x86_avx2_pminu_w:
12098     case Intrinsic::x86_avx2_pminu_d:
12099       Opcode = X86ISD::UMIN;
12100       break;
12101     case Intrinsic::x86_sse41_pmaxsb:
12102     case Intrinsic::x86_sse2_pmaxs_w:
12103     case Intrinsic::x86_sse41_pmaxsd:
12104     case Intrinsic::x86_avx2_pmaxs_b:
12105     case Intrinsic::x86_avx2_pmaxs_w:
12106     case Intrinsic::x86_avx2_pmaxs_d:
12107       Opcode = X86ISD::SMAX;
12108       break;
12109     case Intrinsic::x86_sse41_pminsb:
12110     case Intrinsic::x86_sse2_pmins_w:
12111     case Intrinsic::x86_sse41_pminsd:
12112     case Intrinsic::x86_avx2_pmins_b:
12113     case Intrinsic::x86_avx2_pmins_w:
12114     case Intrinsic::x86_avx2_pmins_d:
12115       Opcode = X86ISD::SMIN;
12116       break;
12117     }
12118     return DAG.getNode(Opcode, dl, Op.getValueType(),
12119                        Op.getOperand(1), Op.getOperand(2));
12120   }
12121
12122   // SSE/SSE2/AVX floating point max/min intrinsics.
12123   case Intrinsic::x86_sse_max_ps:
12124   case Intrinsic::x86_sse2_max_pd:
12125   case Intrinsic::x86_avx_max_ps_256:
12126   case Intrinsic::x86_avx_max_pd_256:
12127   case Intrinsic::x86_sse_min_ps:
12128   case Intrinsic::x86_sse2_min_pd:
12129   case Intrinsic::x86_avx_min_ps_256:
12130   case Intrinsic::x86_avx_min_pd_256: {
12131     unsigned Opcode;
12132     switch (IntNo) {
12133     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12134     case Intrinsic::x86_sse_max_ps:
12135     case Intrinsic::x86_sse2_max_pd:
12136     case Intrinsic::x86_avx_max_ps_256:
12137     case Intrinsic::x86_avx_max_pd_256:
12138       Opcode = X86ISD::FMAX;
12139       break;
12140     case Intrinsic::x86_sse_min_ps:
12141     case Intrinsic::x86_sse2_min_pd:
12142     case Intrinsic::x86_avx_min_ps_256:
12143     case Intrinsic::x86_avx_min_pd_256:
12144       Opcode = X86ISD::FMIN;
12145       break;
12146     }
12147     return DAG.getNode(Opcode, dl, Op.getValueType(),
12148                        Op.getOperand(1), Op.getOperand(2));
12149   }
12150
12151   // AVX2 variable shift intrinsics
12152   case Intrinsic::x86_avx2_psllv_d:
12153   case Intrinsic::x86_avx2_psllv_q:
12154   case Intrinsic::x86_avx2_psllv_d_256:
12155   case Intrinsic::x86_avx2_psllv_q_256:
12156   case Intrinsic::x86_avx2_psrlv_d:
12157   case Intrinsic::x86_avx2_psrlv_q:
12158   case Intrinsic::x86_avx2_psrlv_d_256:
12159   case Intrinsic::x86_avx2_psrlv_q_256:
12160   case Intrinsic::x86_avx2_psrav_d:
12161   case Intrinsic::x86_avx2_psrav_d_256: {
12162     unsigned Opcode;
12163     switch (IntNo) {
12164     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12165     case Intrinsic::x86_avx2_psllv_d:
12166     case Intrinsic::x86_avx2_psllv_q:
12167     case Intrinsic::x86_avx2_psllv_d_256:
12168     case Intrinsic::x86_avx2_psllv_q_256:
12169       Opcode = ISD::SHL;
12170       break;
12171     case Intrinsic::x86_avx2_psrlv_d:
12172     case Intrinsic::x86_avx2_psrlv_q:
12173     case Intrinsic::x86_avx2_psrlv_d_256:
12174     case Intrinsic::x86_avx2_psrlv_q_256:
12175       Opcode = ISD::SRL;
12176       break;
12177     case Intrinsic::x86_avx2_psrav_d:
12178     case Intrinsic::x86_avx2_psrav_d_256:
12179       Opcode = ISD::SRA;
12180       break;
12181     }
12182     return DAG.getNode(Opcode, dl, Op.getValueType(),
12183                        Op.getOperand(1), Op.getOperand(2));
12184   }
12185
12186   case Intrinsic::x86_ssse3_pshuf_b_128:
12187   case Intrinsic::x86_avx2_pshuf_b:
12188     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12189                        Op.getOperand(1), Op.getOperand(2));
12190
12191   case Intrinsic::x86_ssse3_psign_b_128:
12192   case Intrinsic::x86_ssse3_psign_w_128:
12193   case Intrinsic::x86_ssse3_psign_d_128:
12194   case Intrinsic::x86_avx2_psign_b:
12195   case Intrinsic::x86_avx2_psign_w:
12196   case Intrinsic::x86_avx2_psign_d:
12197     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12198                        Op.getOperand(1), Op.getOperand(2));
12199
12200   case Intrinsic::x86_sse41_insertps:
12201     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12202                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12203
12204   case Intrinsic::x86_avx_vperm2f128_ps_256:
12205   case Intrinsic::x86_avx_vperm2f128_pd_256:
12206   case Intrinsic::x86_avx_vperm2f128_si_256:
12207   case Intrinsic::x86_avx2_vperm2i128:
12208     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12209                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12210
12211   case Intrinsic::x86_avx2_permd:
12212   case Intrinsic::x86_avx2_permps:
12213     // Operands intentionally swapped. Mask is last operand to intrinsic,
12214     // but second operand for node/instruction.
12215     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12216                        Op.getOperand(2), Op.getOperand(1));
12217
12218   case Intrinsic::x86_sse_sqrt_ps:
12219   case Intrinsic::x86_sse2_sqrt_pd:
12220   case Intrinsic::x86_avx_sqrt_ps_256:
12221   case Intrinsic::x86_avx_sqrt_pd_256:
12222     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12223
12224   // ptest and testp intrinsics. The intrinsic these come from are designed to
12225   // return an integer value, not just an instruction so lower it to the ptest
12226   // or testp pattern and a setcc for the result.
12227   case Intrinsic::x86_sse41_ptestz:
12228   case Intrinsic::x86_sse41_ptestc:
12229   case Intrinsic::x86_sse41_ptestnzc:
12230   case Intrinsic::x86_avx_ptestz_256:
12231   case Intrinsic::x86_avx_ptestc_256:
12232   case Intrinsic::x86_avx_ptestnzc_256:
12233   case Intrinsic::x86_avx_vtestz_ps:
12234   case Intrinsic::x86_avx_vtestc_ps:
12235   case Intrinsic::x86_avx_vtestnzc_ps:
12236   case Intrinsic::x86_avx_vtestz_pd:
12237   case Intrinsic::x86_avx_vtestc_pd:
12238   case Intrinsic::x86_avx_vtestnzc_pd:
12239   case Intrinsic::x86_avx_vtestz_ps_256:
12240   case Intrinsic::x86_avx_vtestc_ps_256:
12241   case Intrinsic::x86_avx_vtestnzc_ps_256:
12242   case Intrinsic::x86_avx_vtestz_pd_256:
12243   case Intrinsic::x86_avx_vtestc_pd_256:
12244   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12245     bool IsTestPacked = false;
12246     unsigned X86CC;
12247     switch (IntNo) {
12248     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12249     case Intrinsic::x86_avx_vtestz_ps:
12250     case Intrinsic::x86_avx_vtestz_pd:
12251     case Intrinsic::x86_avx_vtestz_ps_256:
12252     case Intrinsic::x86_avx_vtestz_pd_256:
12253       IsTestPacked = true; // Fallthrough
12254     case Intrinsic::x86_sse41_ptestz:
12255     case Intrinsic::x86_avx_ptestz_256:
12256       // ZF = 1
12257       X86CC = X86::COND_E;
12258       break;
12259     case Intrinsic::x86_avx_vtestc_ps:
12260     case Intrinsic::x86_avx_vtestc_pd:
12261     case Intrinsic::x86_avx_vtestc_ps_256:
12262     case Intrinsic::x86_avx_vtestc_pd_256:
12263       IsTestPacked = true; // Fallthrough
12264     case Intrinsic::x86_sse41_ptestc:
12265     case Intrinsic::x86_avx_ptestc_256:
12266       // CF = 1
12267       X86CC = X86::COND_B;
12268       break;
12269     case Intrinsic::x86_avx_vtestnzc_ps:
12270     case Intrinsic::x86_avx_vtestnzc_pd:
12271     case Intrinsic::x86_avx_vtestnzc_ps_256:
12272     case Intrinsic::x86_avx_vtestnzc_pd_256:
12273       IsTestPacked = true; // Fallthrough
12274     case Intrinsic::x86_sse41_ptestnzc:
12275     case Intrinsic::x86_avx_ptestnzc_256:
12276       // ZF and CF = 0
12277       X86CC = X86::COND_A;
12278       break;
12279     }
12280
12281     SDValue LHS = Op.getOperand(1);
12282     SDValue RHS = Op.getOperand(2);
12283     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12284     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12285     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12286     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12287     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12288   }
12289   case Intrinsic::x86_avx512_kortestz_w:
12290   case Intrinsic::x86_avx512_kortestc_w: {
12291     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12292     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12293     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12294     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12295     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12296     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12297     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12298   }
12299
12300   // SSE/AVX shift intrinsics
12301   case Intrinsic::x86_sse2_psll_w:
12302   case Intrinsic::x86_sse2_psll_d:
12303   case Intrinsic::x86_sse2_psll_q:
12304   case Intrinsic::x86_avx2_psll_w:
12305   case Intrinsic::x86_avx2_psll_d:
12306   case Intrinsic::x86_avx2_psll_q:
12307   case Intrinsic::x86_sse2_psrl_w:
12308   case Intrinsic::x86_sse2_psrl_d:
12309   case Intrinsic::x86_sse2_psrl_q:
12310   case Intrinsic::x86_avx2_psrl_w:
12311   case Intrinsic::x86_avx2_psrl_d:
12312   case Intrinsic::x86_avx2_psrl_q:
12313   case Intrinsic::x86_sse2_psra_w:
12314   case Intrinsic::x86_sse2_psra_d:
12315   case Intrinsic::x86_avx2_psra_w:
12316   case Intrinsic::x86_avx2_psra_d: {
12317     unsigned Opcode;
12318     switch (IntNo) {
12319     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12320     case Intrinsic::x86_sse2_psll_w:
12321     case Intrinsic::x86_sse2_psll_d:
12322     case Intrinsic::x86_sse2_psll_q:
12323     case Intrinsic::x86_avx2_psll_w:
12324     case Intrinsic::x86_avx2_psll_d:
12325     case Intrinsic::x86_avx2_psll_q:
12326       Opcode = X86ISD::VSHL;
12327       break;
12328     case Intrinsic::x86_sse2_psrl_w:
12329     case Intrinsic::x86_sse2_psrl_d:
12330     case Intrinsic::x86_sse2_psrl_q:
12331     case Intrinsic::x86_avx2_psrl_w:
12332     case Intrinsic::x86_avx2_psrl_d:
12333     case Intrinsic::x86_avx2_psrl_q:
12334       Opcode = X86ISD::VSRL;
12335       break;
12336     case Intrinsic::x86_sse2_psra_w:
12337     case Intrinsic::x86_sse2_psra_d:
12338     case Intrinsic::x86_avx2_psra_w:
12339     case Intrinsic::x86_avx2_psra_d:
12340       Opcode = X86ISD::VSRA;
12341       break;
12342     }
12343     return DAG.getNode(Opcode, dl, Op.getValueType(),
12344                        Op.getOperand(1), Op.getOperand(2));
12345   }
12346
12347   // SSE/AVX immediate shift intrinsics
12348   case Intrinsic::x86_sse2_pslli_w:
12349   case Intrinsic::x86_sse2_pslli_d:
12350   case Intrinsic::x86_sse2_pslli_q:
12351   case Intrinsic::x86_avx2_pslli_w:
12352   case Intrinsic::x86_avx2_pslli_d:
12353   case Intrinsic::x86_avx2_pslli_q:
12354   case Intrinsic::x86_sse2_psrli_w:
12355   case Intrinsic::x86_sse2_psrli_d:
12356   case Intrinsic::x86_sse2_psrli_q:
12357   case Intrinsic::x86_avx2_psrli_w:
12358   case Intrinsic::x86_avx2_psrli_d:
12359   case Intrinsic::x86_avx2_psrli_q:
12360   case Intrinsic::x86_sse2_psrai_w:
12361   case Intrinsic::x86_sse2_psrai_d:
12362   case Intrinsic::x86_avx2_psrai_w:
12363   case Intrinsic::x86_avx2_psrai_d: {
12364     unsigned Opcode;
12365     switch (IntNo) {
12366     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12367     case Intrinsic::x86_sse2_pslli_w:
12368     case Intrinsic::x86_sse2_pslli_d:
12369     case Intrinsic::x86_sse2_pslli_q:
12370     case Intrinsic::x86_avx2_pslli_w:
12371     case Intrinsic::x86_avx2_pslli_d:
12372     case Intrinsic::x86_avx2_pslli_q:
12373       Opcode = X86ISD::VSHLI;
12374       break;
12375     case Intrinsic::x86_sse2_psrli_w:
12376     case Intrinsic::x86_sse2_psrli_d:
12377     case Intrinsic::x86_sse2_psrli_q:
12378     case Intrinsic::x86_avx2_psrli_w:
12379     case Intrinsic::x86_avx2_psrli_d:
12380     case Intrinsic::x86_avx2_psrli_q:
12381       Opcode = X86ISD::VSRLI;
12382       break;
12383     case Intrinsic::x86_sse2_psrai_w:
12384     case Intrinsic::x86_sse2_psrai_d:
12385     case Intrinsic::x86_avx2_psrai_w:
12386     case Intrinsic::x86_avx2_psrai_d:
12387       Opcode = X86ISD::VSRAI;
12388       break;
12389     }
12390     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12391                                Op.getOperand(1), Op.getOperand(2), DAG);
12392   }
12393
12394   case Intrinsic::x86_sse42_pcmpistria128:
12395   case Intrinsic::x86_sse42_pcmpestria128:
12396   case Intrinsic::x86_sse42_pcmpistric128:
12397   case Intrinsic::x86_sse42_pcmpestric128:
12398   case Intrinsic::x86_sse42_pcmpistrio128:
12399   case Intrinsic::x86_sse42_pcmpestrio128:
12400   case Intrinsic::x86_sse42_pcmpistris128:
12401   case Intrinsic::x86_sse42_pcmpestris128:
12402   case Intrinsic::x86_sse42_pcmpistriz128:
12403   case Intrinsic::x86_sse42_pcmpestriz128: {
12404     unsigned Opcode;
12405     unsigned X86CC;
12406     switch (IntNo) {
12407     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12408     case Intrinsic::x86_sse42_pcmpistria128:
12409       Opcode = X86ISD::PCMPISTRI;
12410       X86CC = X86::COND_A;
12411       break;
12412     case Intrinsic::x86_sse42_pcmpestria128:
12413       Opcode = X86ISD::PCMPESTRI;
12414       X86CC = X86::COND_A;
12415       break;
12416     case Intrinsic::x86_sse42_pcmpistric128:
12417       Opcode = X86ISD::PCMPISTRI;
12418       X86CC = X86::COND_B;
12419       break;
12420     case Intrinsic::x86_sse42_pcmpestric128:
12421       Opcode = X86ISD::PCMPESTRI;
12422       X86CC = X86::COND_B;
12423       break;
12424     case Intrinsic::x86_sse42_pcmpistrio128:
12425       Opcode = X86ISD::PCMPISTRI;
12426       X86CC = X86::COND_O;
12427       break;
12428     case Intrinsic::x86_sse42_pcmpestrio128:
12429       Opcode = X86ISD::PCMPESTRI;
12430       X86CC = X86::COND_O;
12431       break;
12432     case Intrinsic::x86_sse42_pcmpistris128:
12433       Opcode = X86ISD::PCMPISTRI;
12434       X86CC = X86::COND_S;
12435       break;
12436     case Intrinsic::x86_sse42_pcmpestris128:
12437       Opcode = X86ISD::PCMPESTRI;
12438       X86CC = X86::COND_S;
12439       break;
12440     case Intrinsic::x86_sse42_pcmpistriz128:
12441       Opcode = X86ISD::PCMPISTRI;
12442       X86CC = X86::COND_E;
12443       break;
12444     case Intrinsic::x86_sse42_pcmpestriz128:
12445       Opcode = X86ISD::PCMPESTRI;
12446       X86CC = X86::COND_E;
12447       break;
12448     }
12449     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12450     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12451     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12452     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12453                                 DAG.getConstant(X86CC, MVT::i8),
12454                                 SDValue(PCMP.getNode(), 1));
12455     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12456   }
12457
12458   case Intrinsic::x86_sse42_pcmpistri128:
12459   case Intrinsic::x86_sse42_pcmpestri128: {
12460     unsigned Opcode;
12461     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12462       Opcode = X86ISD::PCMPISTRI;
12463     else
12464       Opcode = X86ISD::PCMPESTRI;
12465
12466     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12467     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12468     return DAG.getNode(Opcode, dl, VTs, NewOps);
12469   }
12470   case Intrinsic::x86_fma_vfmadd_ps:
12471   case Intrinsic::x86_fma_vfmadd_pd:
12472   case Intrinsic::x86_fma_vfmsub_ps:
12473   case Intrinsic::x86_fma_vfmsub_pd:
12474   case Intrinsic::x86_fma_vfnmadd_ps:
12475   case Intrinsic::x86_fma_vfnmadd_pd:
12476   case Intrinsic::x86_fma_vfnmsub_ps:
12477   case Intrinsic::x86_fma_vfnmsub_pd:
12478   case Intrinsic::x86_fma_vfmaddsub_ps:
12479   case Intrinsic::x86_fma_vfmaddsub_pd:
12480   case Intrinsic::x86_fma_vfmsubadd_ps:
12481   case Intrinsic::x86_fma_vfmsubadd_pd:
12482   case Intrinsic::x86_fma_vfmadd_ps_256:
12483   case Intrinsic::x86_fma_vfmadd_pd_256:
12484   case Intrinsic::x86_fma_vfmsub_ps_256:
12485   case Intrinsic::x86_fma_vfmsub_pd_256:
12486   case Intrinsic::x86_fma_vfnmadd_ps_256:
12487   case Intrinsic::x86_fma_vfnmadd_pd_256:
12488   case Intrinsic::x86_fma_vfnmsub_ps_256:
12489   case Intrinsic::x86_fma_vfnmsub_pd_256:
12490   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12491   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12492   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12493   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12494   case Intrinsic::x86_fma_vfmadd_ps_512:
12495   case Intrinsic::x86_fma_vfmadd_pd_512:
12496   case Intrinsic::x86_fma_vfmsub_ps_512:
12497   case Intrinsic::x86_fma_vfmsub_pd_512:
12498   case Intrinsic::x86_fma_vfnmadd_ps_512:
12499   case Intrinsic::x86_fma_vfnmadd_pd_512:
12500   case Intrinsic::x86_fma_vfnmsub_ps_512:
12501   case Intrinsic::x86_fma_vfnmsub_pd_512:
12502   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12503   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12504   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12505   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12506     unsigned Opc;
12507     switch (IntNo) {
12508     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12509     case Intrinsic::x86_fma_vfmadd_ps:
12510     case Intrinsic::x86_fma_vfmadd_pd:
12511     case Intrinsic::x86_fma_vfmadd_ps_256:
12512     case Intrinsic::x86_fma_vfmadd_pd_256:
12513     case Intrinsic::x86_fma_vfmadd_ps_512:
12514     case Intrinsic::x86_fma_vfmadd_pd_512:
12515       Opc = X86ISD::FMADD;
12516       break;
12517     case Intrinsic::x86_fma_vfmsub_ps:
12518     case Intrinsic::x86_fma_vfmsub_pd:
12519     case Intrinsic::x86_fma_vfmsub_ps_256:
12520     case Intrinsic::x86_fma_vfmsub_pd_256:
12521     case Intrinsic::x86_fma_vfmsub_ps_512:
12522     case Intrinsic::x86_fma_vfmsub_pd_512:
12523       Opc = X86ISD::FMSUB;
12524       break;
12525     case Intrinsic::x86_fma_vfnmadd_ps:
12526     case Intrinsic::x86_fma_vfnmadd_pd:
12527     case Intrinsic::x86_fma_vfnmadd_ps_256:
12528     case Intrinsic::x86_fma_vfnmadd_pd_256:
12529     case Intrinsic::x86_fma_vfnmadd_ps_512:
12530     case Intrinsic::x86_fma_vfnmadd_pd_512:
12531       Opc = X86ISD::FNMADD;
12532       break;
12533     case Intrinsic::x86_fma_vfnmsub_ps:
12534     case Intrinsic::x86_fma_vfnmsub_pd:
12535     case Intrinsic::x86_fma_vfnmsub_ps_256:
12536     case Intrinsic::x86_fma_vfnmsub_pd_256:
12537     case Intrinsic::x86_fma_vfnmsub_ps_512:
12538     case Intrinsic::x86_fma_vfnmsub_pd_512:
12539       Opc = X86ISD::FNMSUB;
12540       break;
12541     case Intrinsic::x86_fma_vfmaddsub_ps:
12542     case Intrinsic::x86_fma_vfmaddsub_pd:
12543     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12544     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12545     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12546     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12547       Opc = X86ISD::FMADDSUB;
12548       break;
12549     case Intrinsic::x86_fma_vfmsubadd_ps:
12550     case Intrinsic::x86_fma_vfmsubadd_pd:
12551     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12552     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12553     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12554     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12555       Opc = X86ISD::FMSUBADD;
12556       break;
12557     }
12558
12559     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12560                        Op.getOperand(2), Op.getOperand(3));
12561   }
12562   }
12563 }
12564
12565 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12566                               SDValue Src, SDValue Mask, SDValue Base,
12567                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12568                               const X86Subtarget * Subtarget) {
12569   SDLoc dl(Op);
12570   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12571   assert(C && "Invalid scale type");
12572   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12573   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12574                              Index.getSimpleValueType().getVectorNumElements());
12575   SDValue MaskInReg;
12576   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12577   if (MaskC)
12578     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12579   else
12580     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12581   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12582   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12583   SDValue Segment = DAG.getRegister(0, MVT::i32);
12584   if (Src.getOpcode() == ISD::UNDEF)
12585     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12586   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12587   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12588   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12589   return DAG.getMergeValues(RetOps, dl);
12590 }
12591
12592 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12593                                SDValue Src, SDValue Mask, SDValue Base,
12594                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12595   SDLoc dl(Op);
12596   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12597   assert(C && "Invalid scale type");
12598   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12599   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12600   SDValue Segment = DAG.getRegister(0, MVT::i32);
12601   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12602                              Index.getSimpleValueType().getVectorNumElements());
12603   SDValue MaskInReg;
12604   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12605   if (MaskC)
12606     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12607   else
12608     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12609   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12610   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12611   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12612   return SDValue(Res, 1);
12613 }
12614
12615 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12616                                SDValue Mask, SDValue Base, SDValue Index,
12617                                SDValue ScaleOp, SDValue Chain) {
12618   SDLoc dl(Op);
12619   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12620   assert(C && "Invalid scale type");
12621   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12622   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12623   SDValue Segment = DAG.getRegister(0, MVT::i32);
12624   EVT MaskVT =
12625     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12626   SDValue MaskInReg;
12627   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12628   if (MaskC)
12629     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12630   else
12631     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12632   //SDVTList VTs = DAG.getVTList(MVT::Other);
12633   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12634   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12635   return SDValue(Res, 0);
12636 }
12637
12638 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12639 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12640 // also used to custom lower READCYCLECOUNTER nodes.
12641 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12642                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12643                               SmallVectorImpl<SDValue> &Results) {
12644   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12645   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12646   SDValue LO, HI;
12647
12648   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12649   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12650   // and the EAX register is loaded with the low-order 32 bits.
12651   if (Subtarget->is64Bit()) {
12652     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12653     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12654                             LO.getValue(2));
12655   } else {
12656     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12657     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12658                             LO.getValue(2));
12659   }
12660   SDValue Chain = HI.getValue(1);
12661
12662   if (Opcode == X86ISD::RDTSCP_DAG) {
12663     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12664
12665     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12666     // the ECX register. Add 'ecx' explicitly to the chain.
12667     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12668                                      HI.getValue(2));
12669     // Explicitly store the content of ECX at the location passed in input
12670     // to the 'rdtscp' intrinsic.
12671     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12672                          MachinePointerInfo(), false, false, 0);
12673   }
12674
12675   if (Subtarget->is64Bit()) {
12676     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12677     // the EAX register is loaded with the low-order 32 bits.
12678     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12679                               DAG.getConstant(32, MVT::i8));
12680     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12681     Results.push_back(Chain);
12682     return;
12683   }
12684
12685   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12686   SDValue Ops[] = { LO, HI };
12687   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12688   Results.push_back(Pair);
12689   Results.push_back(Chain);
12690 }
12691
12692 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12693                                      SelectionDAG &DAG) {
12694   SmallVector<SDValue, 2> Results;
12695   SDLoc DL(Op);
12696   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12697                           Results);
12698   return DAG.getMergeValues(Results, DL);
12699 }
12700
12701 enum IntrinsicType {
12702   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12703 };
12704
12705 struct IntrinsicData {
12706   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12707     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12708   IntrinsicType Type;
12709   unsigned      Opc0;
12710   unsigned      Opc1;
12711 };
12712
12713 std::map < unsigned, IntrinsicData> IntrMap;
12714 static void InitIntinsicsMap() {
12715   static bool Initialized = false;
12716   if (Initialized) 
12717     return;
12718   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12719                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12720   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12721                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12722   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12723                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12724   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12725                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12726   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12727                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12728   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
12729                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12730   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
12731                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12732   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
12733                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12734   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
12735                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12736
12737   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12738                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12739   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
12740                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12741   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
12742                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12743   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
12744                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12745   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
12746                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12747   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
12748                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12749   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
12750                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12751   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
12752                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12753    
12754   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
12755                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12756                                                         X86::VGATHERPF1QPSm)));
12757   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
12758                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12759                                                         X86::VGATHERPF1QPDm)));
12760   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
12761                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12762                                                         X86::VGATHERPF1DPDm)));
12763   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
12764                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12765                                                         X86::VGATHERPF1DPSm)));
12766   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
12767                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12768                                                         X86::VSCATTERPF1QPSm)));
12769   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
12770                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12771                                                         X86::VSCATTERPF1QPDm)));
12772   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
12773                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12774                                                         X86::VSCATTERPF1DPDm)));
12775   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
12776                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12777                                                         X86::VSCATTERPF1DPSm)));
12778   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12779                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12780   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12781                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12782   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12783                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12784   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12785                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12786   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12787                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12788   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12789                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12790   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12791                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
12792   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12793                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
12794   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12795                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
12796   Initialized = true;
12797 }
12798
12799 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12800                                       SelectionDAG &DAG) {
12801   InitIntinsicsMap();
12802   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12803   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12804   if (itr == IntrMap.end())
12805     return SDValue();
12806
12807   SDLoc dl(Op);
12808   IntrinsicData Intr = itr->second;
12809   switch(Intr.Type) {
12810   case RDSEED:
12811   case RDRAND: {
12812     // Emit the node with the right value type.
12813     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12814     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12815
12816     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12817     // Otherwise return the value from Rand, which is always 0, casted to i32.
12818     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12819                       DAG.getConstant(1, Op->getValueType(1)),
12820                       DAG.getConstant(X86::COND_B, MVT::i32),
12821                       SDValue(Result.getNode(), 1) };
12822     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12823                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12824                                   Ops);
12825
12826     // Return { result, isValid, chain }.
12827     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12828                        SDValue(Result.getNode(), 2));
12829   }
12830   case GATHER: {
12831   //gather(v1, mask, index, base, scale);
12832     SDValue Chain = Op.getOperand(0);
12833     SDValue Src   = Op.getOperand(2);
12834     SDValue Base  = Op.getOperand(3);
12835     SDValue Index = Op.getOperand(4);
12836     SDValue Mask  = Op.getOperand(5);
12837     SDValue Scale = Op.getOperand(6);
12838     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12839                           Subtarget);
12840   }
12841   case SCATTER: {
12842   //scatter(base, mask, index, v1, scale);
12843     SDValue Chain = Op.getOperand(0);
12844     SDValue Base  = Op.getOperand(2);
12845     SDValue Mask  = Op.getOperand(3);
12846     SDValue Index = Op.getOperand(4);
12847     SDValue Src   = Op.getOperand(5);
12848     SDValue Scale = Op.getOperand(6);
12849     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12850   }
12851   case PREFETCH: {
12852     SDValue Hint = Op.getOperand(6);
12853     unsigned HintVal;
12854     if (dyn_cast<ConstantSDNode> (Hint) == 0 ||
12855         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12856       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12857     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12858     SDValue Chain = Op.getOperand(0);
12859     SDValue Mask  = Op.getOperand(2);
12860     SDValue Index = Op.getOperand(3);
12861     SDValue Base  = Op.getOperand(4);
12862     SDValue Scale = Op.getOperand(5);
12863     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12864   }
12865   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12866   case RDTSC: {
12867     SmallVector<SDValue, 2> Results;
12868     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12869     return DAG.getMergeValues(Results, dl);
12870   }
12871   // XTEST intrinsics.
12872   case XTEST: {
12873     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12874     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12875     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12876                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12877                                 InTrans);
12878     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12879     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12880                        Ret, SDValue(InTrans.getNode(), 1));
12881   }
12882   }
12883   llvm_unreachable("Unknown Intrinsic Type");
12884 }
12885
12886 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12887                                            SelectionDAG &DAG) const {
12888   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12889   MFI->setReturnAddressIsTaken(true);
12890
12891   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12892     return SDValue();
12893
12894   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12895   SDLoc dl(Op);
12896   EVT PtrVT = getPointerTy();
12897
12898   if (Depth > 0) {
12899     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12900     const X86RegisterInfo *RegInfo =
12901       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12902     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12903     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12904                        DAG.getNode(ISD::ADD, dl, PtrVT,
12905                                    FrameAddr, Offset),
12906                        MachinePointerInfo(), false, false, false, 0);
12907   }
12908
12909   // Just load the return address.
12910   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12911   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12912                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12913 }
12914
12915 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12916   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12917   MFI->setFrameAddressIsTaken(true);
12918
12919   EVT VT = Op.getValueType();
12920   SDLoc dl(Op);  // FIXME probably not meaningful
12921   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12922   const X86RegisterInfo *RegInfo =
12923     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12924   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12925   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12926           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12927          "Invalid Frame Register!");
12928   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12929   while (Depth--)
12930     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12931                             MachinePointerInfo(),
12932                             false, false, false, 0);
12933   return FrameAddr;
12934 }
12935
12936 // FIXME? Maybe this could be a TableGen attribute on some registers and
12937 // this table could be generated automatically from RegInfo.
12938 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12939                                               EVT VT) const {
12940   unsigned Reg = StringSwitch<unsigned>(RegName)
12941                        .Case("esp", X86::ESP)
12942                        .Case("rsp", X86::RSP)
12943                        .Default(0);
12944   if (Reg)
12945     return Reg;
12946   report_fatal_error("Invalid register name global variable");
12947 }
12948
12949 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12950                                                      SelectionDAG &DAG) const {
12951   const X86RegisterInfo *RegInfo =
12952     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12953   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12954 }
12955
12956 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12957   SDValue Chain     = Op.getOperand(0);
12958   SDValue Offset    = Op.getOperand(1);
12959   SDValue Handler   = Op.getOperand(2);
12960   SDLoc dl      (Op);
12961
12962   EVT PtrVT = getPointerTy();
12963   const X86RegisterInfo *RegInfo =
12964     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12965   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12966   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12967           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12968          "Invalid Frame Register!");
12969   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12970   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12971
12972   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12973                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12974   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12975   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12976                        false, false, 0);
12977   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12978
12979   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12980                      DAG.getRegister(StoreAddrReg, PtrVT));
12981 }
12982
12983 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12984                                                SelectionDAG &DAG) const {
12985   SDLoc DL(Op);
12986   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12987                      DAG.getVTList(MVT::i32, MVT::Other),
12988                      Op.getOperand(0), Op.getOperand(1));
12989 }
12990
12991 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12992                                                 SelectionDAG &DAG) const {
12993   SDLoc DL(Op);
12994   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12995                      Op.getOperand(0), Op.getOperand(1));
12996 }
12997
12998 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12999   return Op.getOperand(0);
13000 }
13001
13002 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13003                                                 SelectionDAG &DAG) const {
13004   SDValue Root = Op.getOperand(0);
13005   SDValue Trmp = Op.getOperand(1); // trampoline
13006   SDValue FPtr = Op.getOperand(2); // nested function
13007   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13008   SDLoc dl (Op);
13009
13010   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13011   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13012
13013   if (Subtarget->is64Bit()) {
13014     SDValue OutChains[6];
13015
13016     // Large code-model.
13017     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
13018     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13019
13020     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13021     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13022
13023     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13024
13025     // Load the pointer to the nested function into R11.
13026     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13027     SDValue Addr = Trmp;
13028     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13029                                 Addr, MachinePointerInfo(TrmpAddr),
13030                                 false, false, 0);
13031
13032     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13033                        DAG.getConstant(2, MVT::i64));
13034     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13035                                 MachinePointerInfo(TrmpAddr, 2),
13036                                 false, false, 2);
13037
13038     // Load the 'nest' parameter value into R10.
13039     // R10 is specified in X86CallingConv.td
13040     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13041     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13042                        DAG.getConstant(10, MVT::i64));
13043     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13044                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13045                                 false, false, 0);
13046
13047     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13048                        DAG.getConstant(12, MVT::i64));
13049     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13050                                 MachinePointerInfo(TrmpAddr, 12),
13051                                 false, false, 2);
13052
13053     // Jump to the nested function.
13054     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13055     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13056                        DAG.getConstant(20, MVT::i64));
13057     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13058                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13059                                 false, false, 0);
13060
13061     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13062     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13063                        DAG.getConstant(22, MVT::i64));
13064     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13065                                 MachinePointerInfo(TrmpAddr, 22),
13066                                 false, false, 0);
13067
13068     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13069   } else {
13070     const Function *Func =
13071       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13072     CallingConv::ID CC = Func->getCallingConv();
13073     unsigned NestReg;
13074
13075     switch (CC) {
13076     default:
13077       llvm_unreachable("Unsupported calling convention");
13078     case CallingConv::C:
13079     case CallingConv::X86_StdCall: {
13080       // Pass 'nest' parameter in ECX.
13081       // Must be kept in sync with X86CallingConv.td
13082       NestReg = X86::ECX;
13083
13084       // Check that ECX wasn't needed by an 'inreg' parameter.
13085       FunctionType *FTy = Func->getFunctionType();
13086       const AttributeSet &Attrs = Func->getAttributes();
13087
13088       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13089         unsigned InRegCount = 0;
13090         unsigned Idx = 1;
13091
13092         for (FunctionType::param_iterator I = FTy->param_begin(),
13093              E = FTy->param_end(); I != E; ++I, ++Idx)
13094           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13095             // FIXME: should only count parameters that are lowered to integers.
13096             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13097
13098         if (InRegCount > 2) {
13099           report_fatal_error("Nest register in use - reduce number of inreg"
13100                              " parameters!");
13101         }
13102       }
13103       break;
13104     }
13105     case CallingConv::X86_FastCall:
13106     case CallingConv::X86_ThisCall:
13107     case CallingConv::Fast:
13108       // Pass 'nest' parameter in EAX.
13109       // Must be kept in sync with X86CallingConv.td
13110       NestReg = X86::EAX;
13111       break;
13112     }
13113
13114     SDValue OutChains[4];
13115     SDValue Addr, Disp;
13116
13117     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13118                        DAG.getConstant(10, MVT::i32));
13119     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13120
13121     // This is storing the opcode for MOV32ri.
13122     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13123     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13124     OutChains[0] = DAG.getStore(Root, dl,
13125                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13126                                 Trmp, MachinePointerInfo(TrmpAddr),
13127                                 false, false, 0);
13128
13129     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13130                        DAG.getConstant(1, MVT::i32));
13131     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13132                                 MachinePointerInfo(TrmpAddr, 1),
13133                                 false, false, 1);
13134
13135     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13136     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13137                        DAG.getConstant(5, MVT::i32));
13138     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13139                                 MachinePointerInfo(TrmpAddr, 5),
13140                                 false, false, 1);
13141
13142     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13143                        DAG.getConstant(6, MVT::i32));
13144     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13145                                 MachinePointerInfo(TrmpAddr, 6),
13146                                 false, false, 1);
13147
13148     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13149   }
13150 }
13151
13152 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13153                                             SelectionDAG &DAG) const {
13154   /*
13155    The rounding mode is in bits 11:10 of FPSR, and has the following
13156    settings:
13157      00 Round to nearest
13158      01 Round to -inf
13159      10 Round to +inf
13160      11 Round to 0
13161
13162   FLT_ROUNDS, on the other hand, expects the following:
13163     -1 Undefined
13164      0 Round to 0
13165      1 Round to nearest
13166      2 Round to +inf
13167      3 Round to -inf
13168
13169   To perform the conversion, we do:
13170     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13171   */
13172
13173   MachineFunction &MF = DAG.getMachineFunction();
13174   const TargetMachine &TM = MF.getTarget();
13175   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13176   unsigned StackAlignment = TFI.getStackAlignment();
13177   MVT VT = Op.getSimpleValueType();
13178   SDLoc DL(Op);
13179
13180   // Save FP Control Word to stack slot
13181   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13182   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13183
13184   MachineMemOperand *MMO =
13185    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13186                            MachineMemOperand::MOStore, 2, 2);
13187
13188   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13189   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13190                                           DAG.getVTList(MVT::Other),
13191                                           Ops, MVT::i16, MMO);
13192
13193   // Load FP Control Word from stack slot
13194   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13195                             MachinePointerInfo(), false, false, false, 0);
13196
13197   // Transform as necessary
13198   SDValue CWD1 =
13199     DAG.getNode(ISD::SRL, DL, MVT::i16,
13200                 DAG.getNode(ISD::AND, DL, MVT::i16,
13201                             CWD, DAG.getConstant(0x800, MVT::i16)),
13202                 DAG.getConstant(11, MVT::i8));
13203   SDValue CWD2 =
13204     DAG.getNode(ISD::SRL, DL, MVT::i16,
13205                 DAG.getNode(ISD::AND, DL, MVT::i16,
13206                             CWD, DAG.getConstant(0x400, MVT::i16)),
13207                 DAG.getConstant(9, MVT::i8));
13208
13209   SDValue RetVal =
13210     DAG.getNode(ISD::AND, DL, MVT::i16,
13211                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13212                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13213                             DAG.getConstant(1, MVT::i16)),
13214                 DAG.getConstant(3, MVT::i16));
13215
13216   return DAG.getNode((VT.getSizeInBits() < 16 ?
13217                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13218 }
13219
13220 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13221   MVT VT = Op.getSimpleValueType();
13222   EVT OpVT = VT;
13223   unsigned NumBits = VT.getSizeInBits();
13224   SDLoc dl(Op);
13225
13226   Op = Op.getOperand(0);
13227   if (VT == MVT::i8) {
13228     // Zero extend to i32 since there is not an i8 bsr.
13229     OpVT = MVT::i32;
13230     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13231   }
13232
13233   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13234   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13235   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13236
13237   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13238   SDValue Ops[] = {
13239     Op,
13240     DAG.getConstant(NumBits+NumBits-1, OpVT),
13241     DAG.getConstant(X86::COND_E, MVT::i8),
13242     Op.getValue(1)
13243   };
13244   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13245
13246   // Finally xor with NumBits-1.
13247   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13248
13249   if (VT == MVT::i8)
13250     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13251   return Op;
13252 }
13253
13254 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13255   MVT VT = Op.getSimpleValueType();
13256   EVT OpVT = VT;
13257   unsigned NumBits = VT.getSizeInBits();
13258   SDLoc dl(Op);
13259
13260   Op = Op.getOperand(0);
13261   if (VT == MVT::i8) {
13262     // Zero extend to i32 since there is not an i8 bsr.
13263     OpVT = MVT::i32;
13264     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13265   }
13266
13267   // Issue a bsr (scan bits in reverse).
13268   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13269   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13270
13271   // And xor with NumBits-1.
13272   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13273
13274   if (VT == MVT::i8)
13275     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13276   return Op;
13277 }
13278
13279 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13280   MVT VT = Op.getSimpleValueType();
13281   unsigned NumBits = VT.getSizeInBits();
13282   SDLoc dl(Op);
13283   Op = Op.getOperand(0);
13284
13285   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13286   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13287   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13288
13289   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13290   SDValue Ops[] = {
13291     Op,
13292     DAG.getConstant(NumBits, VT),
13293     DAG.getConstant(X86::COND_E, MVT::i8),
13294     Op.getValue(1)
13295   };
13296   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13297 }
13298
13299 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13300 // ones, and then concatenate the result back.
13301 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13302   MVT VT = Op.getSimpleValueType();
13303
13304   assert(VT.is256BitVector() && VT.isInteger() &&
13305          "Unsupported value type for operation");
13306
13307   unsigned NumElems = VT.getVectorNumElements();
13308   SDLoc dl(Op);
13309
13310   // Extract the LHS vectors
13311   SDValue LHS = Op.getOperand(0);
13312   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13313   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13314
13315   // Extract the RHS vectors
13316   SDValue RHS = Op.getOperand(1);
13317   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13318   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13319
13320   MVT EltVT = VT.getVectorElementType();
13321   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13322
13323   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13324                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13325                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13326 }
13327
13328 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13329   assert(Op.getSimpleValueType().is256BitVector() &&
13330          Op.getSimpleValueType().isInteger() &&
13331          "Only handle AVX 256-bit vector integer operation");
13332   return Lower256IntArith(Op, DAG);
13333 }
13334
13335 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13336   assert(Op.getSimpleValueType().is256BitVector() &&
13337          Op.getSimpleValueType().isInteger() &&
13338          "Only handle AVX 256-bit vector integer operation");
13339   return Lower256IntArith(Op, DAG);
13340 }
13341
13342 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13343                         SelectionDAG &DAG) {
13344   SDLoc dl(Op);
13345   MVT VT = Op.getSimpleValueType();
13346
13347   // Decompose 256-bit ops into smaller 128-bit ops.
13348   if (VT.is256BitVector() && !Subtarget->hasInt256())
13349     return Lower256IntArith(Op, DAG);
13350
13351   SDValue A = Op.getOperand(0);
13352   SDValue B = Op.getOperand(1);
13353
13354   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13355   if (VT == MVT::v4i32) {
13356     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13357            "Should not custom lower when pmuldq is available!");
13358
13359     // Extract the odd parts.
13360     static const int UnpackMask[] = { 1, -1, 3, -1 };
13361     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13362     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13363
13364     // Multiply the even parts.
13365     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13366     // Now multiply odd parts.
13367     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13368
13369     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13370     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13371
13372     // Merge the two vectors back together with a shuffle. This expands into 2
13373     // shuffles.
13374     static const int ShufMask[] = { 0, 4, 2, 6 };
13375     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13376   }
13377
13378   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13379          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13380
13381   //  Ahi = psrlqi(a, 32);
13382   //  Bhi = psrlqi(b, 32);
13383   //
13384   //  AloBlo = pmuludq(a, b);
13385   //  AloBhi = pmuludq(a, Bhi);
13386   //  AhiBlo = pmuludq(Ahi, b);
13387
13388   //  AloBhi = psllqi(AloBhi, 32);
13389   //  AhiBlo = psllqi(AhiBlo, 32);
13390   //  return AloBlo + AloBhi + AhiBlo;
13391
13392   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13393   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13394
13395   // Bit cast to 32-bit vectors for MULUDQ
13396   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13397                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13398   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13399   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13400   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13401   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13402
13403   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13404   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13405   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13406
13407   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13408   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13409
13410   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13411   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13412 }
13413
13414 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13415   assert(Subtarget->isTargetWin64() && "Unexpected target");
13416   EVT VT = Op.getValueType();
13417   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13418          "Unexpected return type for lowering");
13419
13420   RTLIB::Libcall LC;
13421   bool isSigned;
13422   switch (Op->getOpcode()) {
13423   default: llvm_unreachable("Unexpected request for libcall!");
13424   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13425   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13426   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13427   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13428   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13429   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13430   }
13431
13432   SDLoc dl(Op);
13433   SDValue InChain = DAG.getEntryNode();
13434
13435   TargetLowering::ArgListTy Args;
13436   TargetLowering::ArgListEntry Entry;
13437   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13438     EVT ArgVT = Op->getOperand(i).getValueType();
13439     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13440            "Unexpected argument type for lowering");
13441     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13442     Entry.Node = StackPtr;
13443     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13444                            false, false, 16);
13445     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13446     Entry.Ty = PointerType::get(ArgTy,0);
13447     Entry.isSExt = false;
13448     Entry.isZExt = false;
13449     Args.push_back(Entry);
13450   }
13451
13452   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13453                                          getPointerTy());
13454
13455   TargetLowering::CallLoweringInfo CLI(DAG);
13456   CLI.setDebugLoc(dl).setChain(InChain)
13457     .setCallee(getLibcallCallingConv(LC),
13458                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13459                Callee, &Args, 0)
13460     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13461
13462   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13463   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13464 }
13465
13466 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13467                              SelectionDAG &DAG) {
13468   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13469   EVT VT = Op0.getValueType();
13470   SDLoc dl(Op);
13471
13472   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13473          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13474
13475   // Get the high parts.
13476   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13477   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13478   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13479
13480   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13481   // ints.
13482   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13483   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13484   unsigned Opcode =
13485       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13486   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13487                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13488   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13489                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13490
13491   // Shuffle it back into the right order.
13492   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13493   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13494   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13495   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13496
13497   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13498   // unsigned multiply.
13499   if (IsSigned && !Subtarget->hasSSE41()) {
13500     SDValue ShAmt =
13501         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13502     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13503                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13504     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13505                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13506
13507     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13508     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13509   }
13510
13511   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13512 }
13513
13514 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13515                                          const X86Subtarget *Subtarget) {
13516   MVT VT = Op.getSimpleValueType();
13517   SDLoc dl(Op);
13518   SDValue R = Op.getOperand(0);
13519   SDValue Amt = Op.getOperand(1);
13520
13521   // Optimize shl/srl/sra with constant shift amount.
13522   if (isSplatVector(Amt.getNode())) {
13523     SDValue SclrAmt = Amt->getOperand(0);
13524     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13525       uint64_t ShiftAmt = C->getZExtValue();
13526
13527       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13528           (Subtarget->hasInt256() &&
13529            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13530           (Subtarget->hasAVX512() &&
13531            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13532         if (Op.getOpcode() == ISD::SHL)
13533           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13534                                             DAG);
13535         if (Op.getOpcode() == ISD::SRL)
13536           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13537                                             DAG);
13538         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13539           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13540                                             DAG);
13541       }
13542
13543       if (VT == MVT::v16i8) {
13544         if (Op.getOpcode() == ISD::SHL) {
13545           // Make a large shift.
13546           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13547                                                    MVT::v8i16, R, ShiftAmt,
13548                                                    DAG);
13549           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13550           // Zero out the rightmost bits.
13551           SmallVector<SDValue, 16> V(16,
13552                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13553                                                      MVT::i8));
13554           return DAG.getNode(ISD::AND, dl, VT, SHL,
13555                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13556         }
13557         if (Op.getOpcode() == ISD::SRL) {
13558           // Make a large shift.
13559           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13560                                                    MVT::v8i16, R, ShiftAmt,
13561                                                    DAG);
13562           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13563           // Zero out the leftmost bits.
13564           SmallVector<SDValue, 16> V(16,
13565                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13566                                                      MVT::i8));
13567           return DAG.getNode(ISD::AND, dl, VT, SRL,
13568                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13569         }
13570         if (Op.getOpcode() == ISD::SRA) {
13571           if (ShiftAmt == 7) {
13572             // R s>> 7  ===  R s< 0
13573             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13574             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13575           }
13576
13577           // R s>> a === ((R u>> a) ^ m) - m
13578           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13579           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13580                                                          MVT::i8));
13581           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13582           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13583           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13584           return Res;
13585         }
13586         llvm_unreachable("Unknown shift opcode.");
13587       }
13588
13589       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13590         if (Op.getOpcode() == ISD::SHL) {
13591           // Make a large shift.
13592           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13593                                                    MVT::v16i16, R, ShiftAmt,
13594                                                    DAG);
13595           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13596           // Zero out the rightmost bits.
13597           SmallVector<SDValue, 32> V(32,
13598                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13599                                                      MVT::i8));
13600           return DAG.getNode(ISD::AND, dl, VT, SHL,
13601                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13602         }
13603         if (Op.getOpcode() == ISD::SRL) {
13604           // Make a large shift.
13605           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13606                                                    MVT::v16i16, R, ShiftAmt,
13607                                                    DAG);
13608           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13609           // Zero out the leftmost bits.
13610           SmallVector<SDValue, 32> V(32,
13611                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13612                                                      MVT::i8));
13613           return DAG.getNode(ISD::AND, dl, VT, SRL,
13614                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13615         }
13616         if (Op.getOpcode() == ISD::SRA) {
13617           if (ShiftAmt == 7) {
13618             // R s>> 7  ===  R s< 0
13619             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13620             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13621           }
13622
13623           // R s>> a === ((R u>> a) ^ m) - m
13624           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13625           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13626                                                          MVT::i8));
13627           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13628           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13629           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13630           return Res;
13631         }
13632         llvm_unreachable("Unknown shift opcode.");
13633       }
13634     }
13635   }
13636
13637   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13638   if (!Subtarget->is64Bit() &&
13639       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13640       Amt.getOpcode() == ISD::BITCAST &&
13641       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13642     Amt = Amt.getOperand(0);
13643     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13644                      VT.getVectorNumElements();
13645     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13646     uint64_t ShiftAmt = 0;
13647     for (unsigned i = 0; i != Ratio; ++i) {
13648       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13649       if (!C)
13650         return SDValue();
13651       // 6 == Log2(64)
13652       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13653     }
13654     // Check remaining shift amounts.
13655     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13656       uint64_t ShAmt = 0;
13657       for (unsigned j = 0; j != Ratio; ++j) {
13658         ConstantSDNode *C =
13659           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13660         if (!C)
13661           return SDValue();
13662         // 6 == Log2(64)
13663         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13664       }
13665       if (ShAmt != ShiftAmt)
13666         return SDValue();
13667     }
13668     switch (Op.getOpcode()) {
13669     default:
13670       llvm_unreachable("Unknown shift opcode!");
13671     case ISD::SHL:
13672       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13673                                         DAG);
13674     case ISD::SRL:
13675       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13676                                         DAG);
13677     case ISD::SRA:
13678       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13679                                         DAG);
13680     }
13681   }
13682
13683   return SDValue();
13684 }
13685
13686 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13687                                         const X86Subtarget* Subtarget) {
13688   MVT VT = Op.getSimpleValueType();
13689   SDLoc dl(Op);
13690   SDValue R = Op.getOperand(0);
13691   SDValue Amt = Op.getOperand(1);
13692
13693   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13694       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13695       (Subtarget->hasInt256() &&
13696        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13697         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13698        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13699     SDValue BaseShAmt;
13700     EVT EltVT = VT.getVectorElementType();
13701
13702     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13703       unsigned NumElts = VT.getVectorNumElements();
13704       unsigned i, j;
13705       for (i = 0; i != NumElts; ++i) {
13706         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13707           continue;
13708         break;
13709       }
13710       for (j = i; j != NumElts; ++j) {
13711         SDValue Arg = Amt.getOperand(j);
13712         if (Arg.getOpcode() == ISD::UNDEF) continue;
13713         if (Arg != Amt.getOperand(i))
13714           break;
13715       }
13716       if (i != NumElts && j == NumElts)
13717         BaseShAmt = Amt.getOperand(i);
13718     } else {
13719       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13720         Amt = Amt.getOperand(0);
13721       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13722                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13723         SDValue InVec = Amt.getOperand(0);
13724         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13725           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13726           unsigned i = 0;
13727           for (; i != NumElts; ++i) {
13728             SDValue Arg = InVec.getOperand(i);
13729             if (Arg.getOpcode() == ISD::UNDEF) continue;
13730             BaseShAmt = Arg;
13731             break;
13732           }
13733         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13734            if (ConstantSDNode *C =
13735                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13736              unsigned SplatIdx =
13737                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13738              if (C->getZExtValue() == SplatIdx)
13739                BaseShAmt = InVec.getOperand(1);
13740            }
13741         }
13742         if (!BaseShAmt.getNode())
13743           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13744                                   DAG.getIntPtrConstant(0));
13745       }
13746     }
13747
13748     if (BaseShAmt.getNode()) {
13749       if (EltVT.bitsGT(MVT::i32))
13750         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13751       else if (EltVT.bitsLT(MVT::i32))
13752         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13753
13754       switch (Op.getOpcode()) {
13755       default:
13756         llvm_unreachable("Unknown shift opcode!");
13757       case ISD::SHL:
13758         switch (VT.SimpleTy) {
13759         default: return SDValue();
13760         case MVT::v2i64:
13761         case MVT::v4i32:
13762         case MVT::v8i16:
13763         case MVT::v4i64:
13764         case MVT::v8i32:
13765         case MVT::v16i16:
13766         case MVT::v16i32:
13767         case MVT::v8i64:
13768           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13769         }
13770       case ISD::SRA:
13771         switch (VT.SimpleTy) {
13772         default: return SDValue();
13773         case MVT::v4i32:
13774         case MVT::v8i16:
13775         case MVT::v8i32:
13776         case MVT::v16i16:
13777         case MVT::v16i32:
13778         case MVT::v8i64:
13779           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13780         }
13781       case ISD::SRL:
13782         switch (VT.SimpleTy) {
13783         default: return SDValue();
13784         case MVT::v2i64:
13785         case MVT::v4i32:
13786         case MVT::v8i16:
13787         case MVT::v4i64:
13788         case MVT::v8i32:
13789         case MVT::v16i16:
13790         case MVT::v16i32:
13791         case MVT::v8i64:
13792           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13793         }
13794       }
13795     }
13796   }
13797
13798   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13799   if (!Subtarget->is64Bit() &&
13800       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13801       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13802       Amt.getOpcode() == ISD::BITCAST &&
13803       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13804     Amt = Amt.getOperand(0);
13805     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13806                      VT.getVectorNumElements();
13807     std::vector<SDValue> Vals(Ratio);
13808     for (unsigned i = 0; i != Ratio; ++i)
13809       Vals[i] = Amt.getOperand(i);
13810     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13811       for (unsigned j = 0; j != Ratio; ++j)
13812         if (Vals[j] != Amt.getOperand(i + j))
13813           return SDValue();
13814     }
13815     switch (Op.getOpcode()) {
13816     default:
13817       llvm_unreachable("Unknown shift opcode!");
13818     case ISD::SHL:
13819       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13820     case ISD::SRL:
13821       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13822     case ISD::SRA:
13823       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13824     }
13825   }
13826
13827   return SDValue();
13828 }
13829
13830 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13831                           SelectionDAG &DAG) {
13832
13833   MVT VT = Op.getSimpleValueType();
13834   SDLoc dl(Op);
13835   SDValue R = Op.getOperand(0);
13836   SDValue Amt = Op.getOperand(1);
13837   SDValue V;
13838
13839   if (!Subtarget->hasSSE2())
13840     return SDValue();
13841
13842   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13843   if (V.getNode())
13844     return V;
13845
13846   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13847   if (V.getNode())
13848       return V;
13849
13850   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13851     return Op;
13852   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13853   if (Subtarget->hasInt256()) {
13854     if (Op.getOpcode() == ISD::SRL &&
13855         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13856          VT == MVT::v4i64 || VT == MVT::v8i32))
13857       return Op;
13858     if (Op.getOpcode() == ISD::SHL &&
13859         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13860          VT == MVT::v4i64 || VT == MVT::v8i32))
13861       return Op;
13862     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13863       return Op;
13864   }
13865
13866   // If possible, lower this packed shift into a vector multiply instead of
13867   // expanding it into a sequence of scalar shifts.
13868   // Do this only if the vector shift count is a constant build_vector.
13869   if (Op.getOpcode() == ISD::SHL && 
13870       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13871        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13872       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13873     SmallVector<SDValue, 8> Elts;
13874     EVT SVT = VT.getScalarType();
13875     unsigned SVTBits = SVT.getSizeInBits();
13876     const APInt &One = APInt(SVTBits, 1);
13877     unsigned NumElems = VT.getVectorNumElements();
13878
13879     for (unsigned i=0; i !=NumElems; ++i) {
13880       SDValue Op = Amt->getOperand(i);
13881       if (Op->getOpcode() == ISD::UNDEF) {
13882         Elts.push_back(Op);
13883         continue;
13884       }
13885
13886       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13887       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13888       uint64_t ShAmt = C.getZExtValue();
13889       if (ShAmt >= SVTBits) {
13890         Elts.push_back(DAG.getUNDEF(SVT));
13891         continue;
13892       }
13893       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13894     }
13895     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13896     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13897   }
13898
13899   // Lower SHL with variable shift amount.
13900   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13901     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13902
13903     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13904     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13905     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13906     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13907   }
13908
13909   // If possible, lower this shift as a sequence of two shifts by
13910   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13911   // Example:
13912   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13913   //
13914   // Could be rewritten as:
13915   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13916   //
13917   // The advantage is that the two shifts from the example would be
13918   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13919   // the vector shift into four scalar shifts plus four pairs of vector
13920   // insert/extract.
13921   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13922       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13923     unsigned TargetOpcode = X86ISD::MOVSS;
13924     bool CanBeSimplified;
13925     // The splat value for the first packed shift (the 'X' from the example).
13926     SDValue Amt1 = Amt->getOperand(0);
13927     // The splat value for the second packed shift (the 'Y' from the example).
13928     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13929                                         Amt->getOperand(2);
13930
13931     // See if it is possible to replace this node with a sequence of
13932     // two shifts followed by a MOVSS/MOVSD
13933     if (VT == MVT::v4i32) {
13934       // Check if it is legal to use a MOVSS.
13935       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13936                         Amt2 == Amt->getOperand(3);
13937       if (!CanBeSimplified) {
13938         // Otherwise, check if we can still simplify this node using a MOVSD.
13939         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13940                           Amt->getOperand(2) == Amt->getOperand(3);
13941         TargetOpcode = X86ISD::MOVSD;
13942         Amt2 = Amt->getOperand(2);
13943       }
13944     } else {
13945       // Do similar checks for the case where the machine value type
13946       // is MVT::v8i16.
13947       CanBeSimplified = Amt1 == Amt->getOperand(1);
13948       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13949         CanBeSimplified = Amt2 == Amt->getOperand(i);
13950
13951       if (!CanBeSimplified) {
13952         TargetOpcode = X86ISD::MOVSD;
13953         CanBeSimplified = true;
13954         Amt2 = Amt->getOperand(4);
13955         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13956           CanBeSimplified = Amt1 == Amt->getOperand(i);
13957         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13958           CanBeSimplified = Amt2 == Amt->getOperand(j);
13959       }
13960     }
13961     
13962     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13963         isa<ConstantSDNode>(Amt2)) {
13964       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13965       EVT CastVT = MVT::v4i32;
13966       SDValue Splat1 = 
13967         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13968       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13969       SDValue Splat2 = 
13970         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13971       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13972       if (TargetOpcode == X86ISD::MOVSD)
13973         CastVT = MVT::v2i64;
13974       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13975       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13976       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13977                                             BitCast1, DAG);
13978       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13979     }
13980   }
13981
13982   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13983     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13984
13985     // a = a << 5;
13986     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13987     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13988
13989     // Turn 'a' into a mask suitable for VSELECT
13990     SDValue VSelM = DAG.getConstant(0x80, VT);
13991     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13992     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13993
13994     SDValue CM1 = DAG.getConstant(0x0f, VT);
13995     SDValue CM2 = DAG.getConstant(0x3f, VT);
13996
13997     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13998     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13999     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14000     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14001     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14002
14003     // a += a
14004     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14005     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14006     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14007
14008     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14009     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14010     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14011     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14012     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14013
14014     // a += a
14015     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14016     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14017     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14018
14019     // return VSELECT(r, r+r, a);
14020     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14021                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14022     return R;
14023   }
14024
14025   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14026   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14027   // solution better.
14028   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14029     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14030     unsigned ExtOpc =
14031         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14032     R = DAG.getNode(ExtOpc, dl, NewVT, R);
14033     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14034     return DAG.getNode(ISD::TRUNCATE, dl, VT,
14035                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14036     }
14037
14038   // Decompose 256-bit shifts into smaller 128-bit shifts.
14039   if (VT.is256BitVector()) {
14040     unsigned NumElems = VT.getVectorNumElements();
14041     MVT EltVT = VT.getVectorElementType();
14042     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14043
14044     // Extract the two vectors
14045     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14046     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14047
14048     // Recreate the shift amount vectors
14049     SDValue Amt1, Amt2;
14050     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14051       // Constant shift amount
14052       SmallVector<SDValue, 4> Amt1Csts;
14053       SmallVector<SDValue, 4> Amt2Csts;
14054       for (unsigned i = 0; i != NumElems/2; ++i)
14055         Amt1Csts.push_back(Amt->getOperand(i));
14056       for (unsigned i = NumElems/2; i != NumElems; ++i)
14057         Amt2Csts.push_back(Amt->getOperand(i));
14058
14059       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14060       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14061     } else {
14062       // Variable shift amount
14063       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14064       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14065     }
14066
14067     // Issue new vector shifts for the smaller types
14068     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14069     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14070
14071     // Concatenate the result back
14072     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14073   }
14074
14075   return SDValue();
14076 }
14077
14078 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14079   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14080   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14081   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14082   // has only one use.
14083   SDNode *N = Op.getNode();
14084   SDValue LHS = N->getOperand(0);
14085   SDValue RHS = N->getOperand(1);
14086   unsigned BaseOp = 0;
14087   unsigned Cond = 0;
14088   SDLoc DL(Op);
14089   switch (Op.getOpcode()) {
14090   default: llvm_unreachable("Unknown ovf instruction!");
14091   case ISD::SADDO:
14092     // A subtract of one will be selected as a INC. Note that INC doesn't
14093     // set CF, so we can't do this for UADDO.
14094     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14095       if (C->isOne()) {
14096         BaseOp = X86ISD::INC;
14097         Cond = X86::COND_O;
14098         break;
14099       }
14100     BaseOp = X86ISD::ADD;
14101     Cond = X86::COND_O;
14102     break;
14103   case ISD::UADDO:
14104     BaseOp = X86ISD::ADD;
14105     Cond = X86::COND_B;
14106     break;
14107   case ISD::SSUBO:
14108     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14109     // set CF, so we can't do this for USUBO.
14110     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14111       if (C->isOne()) {
14112         BaseOp = X86ISD::DEC;
14113         Cond = X86::COND_O;
14114         break;
14115       }
14116     BaseOp = X86ISD::SUB;
14117     Cond = X86::COND_O;
14118     break;
14119   case ISD::USUBO:
14120     BaseOp = X86ISD::SUB;
14121     Cond = X86::COND_B;
14122     break;
14123   case ISD::SMULO:
14124     BaseOp = X86ISD::SMUL;
14125     Cond = X86::COND_O;
14126     break;
14127   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14128     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14129                                  MVT::i32);
14130     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14131
14132     SDValue SetCC =
14133       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14134                   DAG.getConstant(X86::COND_O, MVT::i32),
14135                   SDValue(Sum.getNode(), 2));
14136
14137     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14138   }
14139   }
14140
14141   // Also sets EFLAGS.
14142   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14143   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14144
14145   SDValue SetCC =
14146     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14147                 DAG.getConstant(Cond, MVT::i32),
14148                 SDValue(Sum.getNode(), 1));
14149
14150   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14151 }
14152
14153 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14154                                                   SelectionDAG &DAG) const {
14155   SDLoc dl(Op);
14156   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14157   MVT VT = Op.getSimpleValueType();
14158
14159   if (!Subtarget->hasSSE2() || !VT.isVector())
14160     return SDValue();
14161
14162   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14163                       ExtraVT.getScalarType().getSizeInBits();
14164
14165   switch (VT.SimpleTy) {
14166     default: return SDValue();
14167     case MVT::v8i32:
14168     case MVT::v16i16:
14169       if (!Subtarget->hasFp256())
14170         return SDValue();
14171       if (!Subtarget->hasInt256()) {
14172         // needs to be split
14173         unsigned NumElems = VT.getVectorNumElements();
14174
14175         // Extract the LHS vectors
14176         SDValue LHS = Op.getOperand(0);
14177         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14178         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14179
14180         MVT EltVT = VT.getVectorElementType();
14181         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14182
14183         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14184         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14185         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14186                                    ExtraNumElems/2);
14187         SDValue Extra = DAG.getValueType(ExtraVT);
14188
14189         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14190         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14191
14192         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14193       }
14194       // fall through
14195     case MVT::v4i32:
14196     case MVT::v8i16: {
14197       SDValue Op0 = Op.getOperand(0);
14198       SDValue Op00 = Op0.getOperand(0);
14199       SDValue Tmp1;
14200       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14201       if (Op0.getOpcode() == ISD::BITCAST &&
14202           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14203         // (sext (vzext x)) -> (vsext x)
14204         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14205         if (Tmp1.getNode()) {
14206           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14207           // This folding is only valid when the in-reg type is a vector of i8,
14208           // i16, or i32.
14209           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14210               ExtraEltVT == MVT::i32) {
14211             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14212             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14213                    "This optimization is invalid without a VZEXT.");
14214             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14215           }
14216           Op0 = Tmp1;
14217         }
14218       }
14219
14220       // If the above didn't work, then just use Shift-Left + Shift-Right.
14221       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14222                                         DAG);
14223       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14224                                         DAG);
14225     }
14226   }
14227 }
14228
14229 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14230                                  SelectionDAG &DAG) {
14231   SDLoc dl(Op);
14232   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14233     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14234   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14235     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14236
14237   // The only fence that needs an instruction is a sequentially-consistent
14238   // cross-thread fence.
14239   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14240     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14241     // no-sse2). There isn't any reason to disable it if the target processor
14242     // supports it.
14243     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14244       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14245
14246     SDValue Chain = Op.getOperand(0);
14247     SDValue Zero = DAG.getConstant(0, MVT::i32);
14248     SDValue Ops[] = {
14249       DAG.getRegister(X86::ESP, MVT::i32), // Base
14250       DAG.getTargetConstant(1, MVT::i8),   // Scale
14251       DAG.getRegister(0, MVT::i32),        // Index
14252       DAG.getTargetConstant(0, MVT::i32),  // Disp
14253       DAG.getRegister(0, MVT::i32),        // Segment.
14254       Zero,
14255       Chain
14256     };
14257     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14258     return SDValue(Res, 0);
14259   }
14260
14261   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14262   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14263 }
14264
14265 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14266                              SelectionDAG &DAG) {
14267   MVT T = Op.getSimpleValueType();
14268   SDLoc DL(Op);
14269   unsigned Reg = 0;
14270   unsigned size = 0;
14271   switch(T.SimpleTy) {
14272   default: llvm_unreachable("Invalid value type!");
14273   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14274   case MVT::i16: Reg = X86::AX;  size = 2; break;
14275   case MVT::i32: Reg = X86::EAX; size = 4; break;
14276   case MVT::i64:
14277     assert(Subtarget->is64Bit() && "Node not type legal!");
14278     Reg = X86::RAX; size = 8;
14279     break;
14280   }
14281   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14282                                     Op.getOperand(2), SDValue());
14283   SDValue Ops[] = { cpIn.getValue(0),
14284                     Op.getOperand(1),
14285                     Op.getOperand(3),
14286                     DAG.getTargetConstant(size, MVT::i8),
14287                     cpIn.getValue(1) };
14288   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14289   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14290   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14291                                            Ops, T, MMO);
14292   SDValue cpOut =
14293     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14294   return cpOut;
14295 }
14296
14297 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14298                             SelectionDAG &DAG) {
14299   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14300   MVT DstVT = Op.getSimpleValueType();
14301
14302   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14303     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14304     if (DstVT != MVT::f64)
14305       // This conversion needs to be expanded.
14306       return SDValue();
14307
14308     SDValue InVec = Op->getOperand(0);
14309     SDLoc dl(Op);
14310     unsigned NumElts = SrcVT.getVectorNumElements();
14311     EVT SVT = SrcVT.getVectorElementType();
14312
14313     // Widen the vector in input in the case of MVT::v2i32.
14314     // Example: from MVT::v2i32 to MVT::v4i32.
14315     SmallVector<SDValue, 16> Elts;
14316     for (unsigned i = 0, e = NumElts; i != e; ++i)
14317       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14318                                  DAG.getIntPtrConstant(i)));
14319
14320     // Explicitly mark the extra elements as Undef.
14321     SDValue Undef = DAG.getUNDEF(SVT);
14322     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14323       Elts.push_back(Undef);
14324
14325     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14326     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14327     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14328     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14329                        DAG.getIntPtrConstant(0));
14330   }
14331
14332   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14333          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14334   assert((DstVT == MVT::i64 ||
14335           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14336          "Unexpected custom BITCAST");
14337   // i64 <=> MMX conversions are Legal.
14338   if (SrcVT==MVT::i64 && DstVT.isVector())
14339     return Op;
14340   if (DstVT==MVT::i64 && SrcVT.isVector())
14341     return Op;
14342   // MMX <=> MMX conversions are Legal.
14343   if (SrcVT.isVector() && DstVT.isVector())
14344     return Op;
14345   // All other conversions need to be expanded.
14346   return SDValue();
14347 }
14348
14349 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14350   SDNode *Node = Op.getNode();
14351   SDLoc dl(Node);
14352   EVT T = Node->getValueType(0);
14353   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14354                               DAG.getConstant(0, T), Node->getOperand(2));
14355   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14356                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14357                        Node->getOperand(0),
14358                        Node->getOperand(1), negOp,
14359                        cast<AtomicSDNode>(Node)->getMemOperand(),
14360                        cast<AtomicSDNode>(Node)->getOrdering(),
14361                        cast<AtomicSDNode>(Node)->getSynchScope());
14362 }
14363
14364 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14365   SDNode *Node = Op.getNode();
14366   SDLoc dl(Node);
14367   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14368
14369   // Convert seq_cst store -> xchg
14370   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14371   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14372   //        (The only way to get a 16-byte store is cmpxchg16b)
14373   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14374   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14375       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14376     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14377                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14378                                  Node->getOperand(0),
14379                                  Node->getOperand(1), Node->getOperand(2),
14380                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14381                                  cast<AtomicSDNode>(Node)->getOrdering(),
14382                                  cast<AtomicSDNode>(Node)->getSynchScope());
14383     return Swap.getValue(1);
14384   }
14385   // Other atomic stores have a simple pattern.
14386   return Op;
14387 }
14388
14389 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14390   EVT VT = Op.getNode()->getSimpleValueType(0);
14391
14392   // Let legalize expand this if it isn't a legal type yet.
14393   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14394     return SDValue();
14395
14396   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14397
14398   unsigned Opc;
14399   bool ExtraOp = false;
14400   switch (Op.getOpcode()) {
14401   default: llvm_unreachable("Invalid code");
14402   case ISD::ADDC: Opc = X86ISD::ADD; break;
14403   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14404   case ISD::SUBC: Opc = X86ISD::SUB; break;
14405   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14406   }
14407
14408   if (!ExtraOp)
14409     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14410                        Op.getOperand(1));
14411   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14412                      Op.getOperand(1), Op.getOperand(2));
14413 }
14414
14415 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14416                             SelectionDAG &DAG) {
14417   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14418
14419   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14420   // which returns the values as { float, float } (in XMM0) or
14421   // { double, double } (which is returned in XMM0, XMM1).
14422   SDLoc dl(Op);
14423   SDValue Arg = Op.getOperand(0);
14424   EVT ArgVT = Arg.getValueType();
14425   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14426
14427   TargetLowering::ArgListTy Args;
14428   TargetLowering::ArgListEntry Entry;
14429
14430   Entry.Node = Arg;
14431   Entry.Ty = ArgTy;
14432   Entry.isSExt = false;
14433   Entry.isZExt = false;
14434   Args.push_back(Entry);
14435
14436   bool isF64 = ArgVT == MVT::f64;
14437   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14438   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14439   // the results are returned via SRet in memory.
14440   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14442   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14443
14444   Type *RetTy = isF64
14445     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14446     : (Type*)VectorType::get(ArgTy, 4);
14447
14448   TargetLowering::CallLoweringInfo CLI(DAG);
14449   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14450     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14451
14452   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14453
14454   if (isF64)
14455     // Returned in xmm0 and xmm1.
14456     return CallResult.first;
14457
14458   // Returned in bits 0:31 and 32:64 xmm0.
14459   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14460                                CallResult.first, DAG.getIntPtrConstant(0));
14461   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14462                                CallResult.first, DAG.getIntPtrConstant(1));
14463   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14464   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14465 }
14466
14467 /// LowerOperation - Provide custom lowering hooks for some operations.
14468 ///
14469 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14470   switch (Op.getOpcode()) {
14471   default: llvm_unreachable("Should not custom lower this!");
14472   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14473   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14474   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14475   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14476   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14477   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14478   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14479   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14480   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14481   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14482   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14483   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14484   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14485   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14486   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14487   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14488   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14489   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14490   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14491   case ISD::SHL_PARTS:
14492   case ISD::SRA_PARTS:
14493   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14494   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14495   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14496   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14497   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14498   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14499   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14500   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14501   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14502   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14503   case ISD::FABS:               return LowerFABS(Op, DAG);
14504   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14505   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14506   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14507   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14508   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14509   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14510   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14511   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14512   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14513   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14514   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14515   case ISD::INTRINSIC_VOID:
14516   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14517   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14518   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14519   case ISD::FRAME_TO_ARGS_OFFSET:
14520                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14521   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14522   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14523   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14524   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14525   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14526   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14527   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14528   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14529   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14530   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14531   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14532   case ISD::UMUL_LOHI:
14533   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14534   case ISD::SRA:
14535   case ISD::SRL:
14536   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14537   case ISD::SADDO:
14538   case ISD::UADDO:
14539   case ISD::SSUBO:
14540   case ISD::USUBO:
14541   case ISD::SMULO:
14542   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14543   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14544   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14545   case ISD::ADDC:
14546   case ISD::ADDE:
14547   case ISD::SUBC:
14548   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14549   case ISD::ADD:                return LowerADD(Op, DAG);
14550   case ISD::SUB:                return LowerSUB(Op, DAG);
14551   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14552   }
14553 }
14554
14555 static void ReplaceATOMIC_LOAD(SDNode *Node,
14556                                   SmallVectorImpl<SDValue> &Results,
14557                                   SelectionDAG &DAG) {
14558   SDLoc dl(Node);
14559   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14560
14561   // Convert wide load -> cmpxchg8b/cmpxchg16b
14562   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14563   //        (The only way to get a 16-byte load is cmpxchg16b)
14564   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14565   SDValue Zero = DAG.getConstant(0, VT);
14566   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14567                                Node->getOperand(0),
14568                                Node->getOperand(1), Zero, Zero,
14569                                cast<AtomicSDNode>(Node)->getMemOperand(),
14570                                cast<AtomicSDNode>(Node)->getOrdering(),
14571                                cast<AtomicSDNode>(Node)->getOrdering(),
14572                                cast<AtomicSDNode>(Node)->getSynchScope());
14573   Results.push_back(Swap.getValue(0));
14574   Results.push_back(Swap.getValue(1));
14575 }
14576
14577 static void
14578 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14579                         SelectionDAG &DAG, unsigned NewOp) {
14580   SDLoc dl(Node);
14581   assert (Node->getValueType(0) == MVT::i64 &&
14582           "Only know how to expand i64 atomics");
14583
14584   SDValue Chain = Node->getOperand(0);
14585   SDValue In1 = Node->getOperand(1);
14586   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14587                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14588   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14589                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14590   SDValue Ops[] = { Chain, In1, In2L, In2H };
14591   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14592   SDValue Result =
14593     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14594                             cast<MemSDNode>(Node)->getMemOperand());
14595   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14596   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14597   Results.push_back(Result.getValue(2));
14598 }
14599
14600 /// ReplaceNodeResults - Replace a node with an illegal result type
14601 /// with a new node built out of custom code.
14602 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14603                                            SmallVectorImpl<SDValue>&Results,
14604                                            SelectionDAG &DAG) const {
14605   SDLoc dl(N);
14606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14607   switch (N->getOpcode()) {
14608   default:
14609     llvm_unreachable("Do not know how to custom type legalize this operation!");
14610   case ISD::SIGN_EXTEND_INREG:
14611   case ISD::ADDC:
14612   case ISD::ADDE:
14613   case ISD::SUBC:
14614   case ISD::SUBE:
14615     // We don't want to expand or promote these.
14616     return;
14617   case ISD::SDIV:
14618   case ISD::UDIV:
14619   case ISD::SREM:
14620   case ISD::UREM:
14621   case ISD::SDIVREM:
14622   case ISD::UDIVREM: {
14623     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14624     Results.push_back(V);
14625     return;
14626   }
14627   case ISD::FP_TO_SINT:
14628   case ISD::FP_TO_UINT: {
14629     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14630
14631     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14632       return;
14633
14634     std::pair<SDValue,SDValue> Vals =
14635         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14636     SDValue FIST = Vals.first, StackSlot = Vals.second;
14637     if (FIST.getNode()) {
14638       EVT VT = N->getValueType(0);
14639       // Return a load from the stack slot.
14640       if (StackSlot.getNode())
14641         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14642                                       MachinePointerInfo(),
14643                                       false, false, false, 0));
14644       else
14645         Results.push_back(FIST);
14646     }
14647     return;
14648   }
14649   case ISD::UINT_TO_FP: {
14650     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14651     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14652         N->getValueType(0) != MVT::v2f32)
14653       return;
14654     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14655                                  N->getOperand(0));
14656     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14657                                      MVT::f64);
14658     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14659     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14660                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14661     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14662     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14663     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14664     return;
14665   }
14666   case ISD::FP_ROUND: {
14667     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14668         return;
14669     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14670     Results.push_back(V);
14671     return;
14672   }
14673   case ISD::INTRINSIC_W_CHAIN: {
14674     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14675     switch (IntNo) {
14676     default : llvm_unreachable("Do not know how to custom type "
14677                                "legalize this intrinsic operation!");
14678     case Intrinsic::x86_rdtsc:
14679       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14680                                      Results);
14681     case Intrinsic::x86_rdtscp:
14682       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14683                                      Results);
14684     }
14685   }
14686   case ISD::READCYCLECOUNTER: {
14687     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14688                                    Results);
14689   }
14690   case ISD::ATOMIC_CMP_SWAP: {
14691     EVT T = N->getValueType(0);
14692     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14693     bool Regs64bit = T == MVT::i128;
14694     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14695     SDValue cpInL, cpInH;
14696     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14697                         DAG.getConstant(0, HalfT));
14698     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14699                         DAG.getConstant(1, HalfT));
14700     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14701                              Regs64bit ? X86::RAX : X86::EAX,
14702                              cpInL, SDValue());
14703     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14704                              Regs64bit ? X86::RDX : X86::EDX,
14705                              cpInH, cpInL.getValue(1));
14706     SDValue swapInL, swapInH;
14707     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14708                           DAG.getConstant(0, HalfT));
14709     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14710                           DAG.getConstant(1, HalfT));
14711     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14712                                Regs64bit ? X86::RBX : X86::EBX,
14713                                swapInL, cpInH.getValue(1));
14714     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14715                                Regs64bit ? X86::RCX : X86::ECX,
14716                                swapInH, swapInL.getValue(1));
14717     SDValue Ops[] = { swapInH.getValue(0),
14718                       N->getOperand(1),
14719                       swapInH.getValue(1) };
14720     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14721     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14722     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14723                                   X86ISD::LCMPXCHG8_DAG;
14724     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14725     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14726                                         Regs64bit ? X86::RAX : X86::EAX,
14727                                         HalfT, Result.getValue(1));
14728     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14729                                         Regs64bit ? X86::RDX : X86::EDX,
14730                                         HalfT, cpOutL.getValue(2));
14731     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14732     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14733     Results.push_back(cpOutH.getValue(1));
14734     return;
14735   }
14736   case ISD::ATOMIC_LOAD_ADD:
14737   case ISD::ATOMIC_LOAD_AND:
14738   case ISD::ATOMIC_LOAD_NAND:
14739   case ISD::ATOMIC_LOAD_OR:
14740   case ISD::ATOMIC_LOAD_SUB:
14741   case ISD::ATOMIC_LOAD_XOR:
14742   case ISD::ATOMIC_LOAD_MAX:
14743   case ISD::ATOMIC_LOAD_MIN:
14744   case ISD::ATOMIC_LOAD_UMAX:
14745   case ISD::ATOMIC_LOAD_UMIN:
14746   case ISD::ATOMIC_SWAP: {
14747     unsigned Opc;
14748     switch (N->getOpcode()) {
14749     default: llvm_unreachable("Unexpected opcode");
14750     case ISD::ATOMIC_LOAD_ADD:
14751       Opc = X86ISD::ATOMADD64_DAG;
14752       break;
14753     case ISD::ATOMIC_LOAD_AND:
14754       Opc = X86ISD::ATOMAND64_DAG;
14755       break;
14756     case ISD::ATOMIC_LOAD_NAND:
14757       Opc = X86ISD::ATOMNAND64_DAG;
14758       break;
14759     case ISD::ATOMIC_LOAD_OR:
14760       Opc = X86ISD::ATOMOR64_DAG;
14761       break;
14762     case ISD::ATOMIC_LOAD_SUB:
14763       Opc = X86ISD::ATOMSUB64_DAG;
14764       break;
14765     case ISD::ATOMIC_LOAD_XOR:
14766       Opc = X86ISD::ATOMXOR64_DAG;
14767       break;
14768     case ISD::ATOMIC_LOAD_MAX:
14769       Opc = X86ISD::ATOMMAX64_DAG;
14770       break;
14771     case ISD::ATOMIC_LOAD_MIN:
14772       Opc = X86ISD::ATOMMIN64_DAG;
14773       break;
14774     case ISD::ATOMIC_LOAD_UMAX:
14775       Opc = X86ISD::ATOMUMAX64_DAG;
14776       break;
14777     case ISD::ATOMIC_LOAD_UMIN:
14778       Opc = X86ISD::ATOMUMIN64_DAG;
14779       break;
14780     case ISD::ATOMIC_SWAP:
14781       Opc = X86ISD::ATOMSWAP64_DAG;
14782       break;
14783     }
14784     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14785     return;
14786   }
14787   case ISD::ATOMIC_LOAD: {
14788     ReplaceATOMIC_LOAD(N, Results, DAG);
14789     return;
14790   }
14791   case ISD::BITCAST: {
14792     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14793     EVT DstVT = N->getValueType(0);
14794     EVT SrcVT = N->getOperand(0)->getValueType(0);
14795
14796     if (SrcVT != MVT::f64 ||
14797         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14798       return;
14799
14800     unsigned NumElts = DstVT.getVectorNumElements();
14801     EVT SVT = DstVT.getVectorElementType();
14802     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14803     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14804                                    MVT::v2f64, N->getOperand(0));
14805     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14806
14807     SmallVector<SDValue, 8> Elts;
14808     for (unsigned i = 0, e = NumElts; i != e; ++i)
14809       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14810                                    ToVecInt, DAG.getIntPtrConstant(i)));
14811
14812     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14813   }
14814   }
14815 }
14816
14817 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14818   switch (Opcode) {
14819   default: return nullptr;
14820   case X86ISD::BSF:                return "X86ISD::BSF";
14821   case X86ISD::BSR:                return "X86ISD::BSR";
14822   case X86ISD::SHLD:               return "X86ISD::SHLD";
14823   case X86ISD::SHRD:               return "X86ISD::SHRD";
14824   case X86ISD::FAND:               return "X86ISD::FAND";
14825   case X86ISD::FANDN:              return "X86ISD::FANDN";
14826   case X86ISD::FOR:                return "X86ISD::FOR";
14827   case X86ISD::FXOR:               return "X86ISD::FXOR";
14828   case X86ISD::FSRL:               return "X86ISD::FSRL";
14829   case X86ISD::FILD:               return "X86ISD::FILD";
14830   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14831   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14832   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14833   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14834   case X86ISD::FLD:                return "X86ISD::FLD";
14835   case X86ISD::FST:                return "X86ISD::FST";
14836   case X86ISD::CALL:               return "X86ISD::CALL";
14837   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14838   case X86ISD::BT:                 return "X86ISD::BT";
14839   case X86ISD::CMP:                return "X86ISD::CMP";
14840   case X86ISD::COMI:               return "X86ISD::COMI";
14841   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14842   case X86ISD::CMPM:               return "X86ISD::CMPM";
14843   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14844   case X86ISD::SETCC:              return "X86ISD::SETCC";
14845   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14846   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14847   case X86ISD::CMOV:               return "X86ISD::CMOV";
14848   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14849   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14850   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14851   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14852   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14853   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14854   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14855   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14856   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14857   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14858   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14859   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14860   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14861   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14862   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14863   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14864   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14865   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14866   case X86ISD::HADD:               return "X86ISD::HADD";
14867   case X86ISD::HSUB:               return "X86ISD::HSUB";
14868   case X86ISD::FHADD:              return "X86ISD::FHADD";
14869   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14870   case X86ISD::UMAX:               return "X86ISD::UMAX";
14871   case X86ISD::UMIN:               return "X86ISD::UMIN";
14872   case X86ISD::SMAX:               return "X86ISD::SMAX";
14873   case X86ISD::SMIN:               return "X86ISD::SMIN";
14874   case X86ISD::FMAX:               return "X86ISD::FMAX";
14875   case X86ISD::FMIN:               return "X86ISD::FMIN";
14876   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14877   case X86ISD::FMINC:              return "X86ISD::FMINC";
14878   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14879   case X86ISD::FRCP:               return "X86ISD::FRCP";
14880   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14881   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14882   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14883   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14884   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14885   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14886   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14887   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14888   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14889   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14890   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14891   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14892   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14893   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14894   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14895   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14896   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14897   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14898   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14899   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14900   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14901   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14902   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14903   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14904   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14905   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14906   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14907   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14908   case X86ISD::VSHL:               return "X86ISD::VSHL";
14909   case X86ISD::VSRL:               return "X86ISD::VSRL";
14910   case X86ISD::VSRA:               return "X86ISD::VSRA";
14911   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14912   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14913   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14914   case X86ISD::CMPP:               return "X86ISD::CMPP";
14915   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14916   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14917   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14918   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14919   case X86ISD::ADD:                return "X86ISD::ADD";
14920   case X86ISD::SUB:                return "X86ISD::SUB";
14921   case X86ISD::ADC:                return "X86ISD::ADC";
14922   case X86ISD::SBB:                return "X86ISD::SBB";
14923   case X86ISD::SMUL:               return "X86ISD::SMUL";
14924   case X86ISD::UMUL:               return "X86ISD::UMUL";
14925   case X86ISD::INC:                return "X86ISD::INC";
14926   case X86ISD::DEC:                return "X86ISD::DEC";
14927   case X86ISD::OR:                 return "X86ISD::OR";
14928   case X86ISD::XOR:                return "X86ISD::XOR";
14929   case X86ISD::AND:                return "X86ISD::AND";
14930   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14931   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14932   case X86ISD::PTEST:              return "X86ISD::PTEST";
14933   case X86ISD::TESTP:              return "X86ISD::TESTP";
14934   case X86ISD::TESTM:              return "X86ISD::TESTM";
14935   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14936   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14937   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14938   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14939   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14940   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14941   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14942   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14943   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14944   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14945   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14946   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14947   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14948   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14949   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14950   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14951   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14952   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14953   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14954   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14955   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14956   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14957   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14958   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14959   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14960   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14961   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14962   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14963   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14964   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14965   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14966   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14967   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14968   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14969   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14970   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14971   case X86ISD::SAHF:               return "X86ISD::SAHF";
14972   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14973   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14974   case X86ISD::FMADD:              return "X86ISD::FMADD";
14975   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14976   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14977   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14978   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14979   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14980   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14981   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14982   case X86ISD::XTEST:              return "X86ISD::XTEST";
14983   }
14984 }
14985
14986 // isLegalAddressingMode - Return true if the addressing mode represented
14987 // by AM is legal for this target, for a load/store of the specified type.
14988 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14989                                               Type *Ty) const {
14990   // X86 supports extremely general addressing modes.
14991   CodeModel::Model M = getTargetMachine().getCodeModel();
14992   Reloc::Model R = getTargetMachine().getRelocationModel();
14993
14994   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14995   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14996     return false;
14997
14998   if (AM.BaseGV) {
14999     unsigned GVFlags =
15000       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15001
15002     // If a reference to this global requires an extra load, we can't fold it.
15003     if (isGlobalStubReference(GVFlags))
15004       return false;
15005
15006     // If BaseGV requires a register for the PIC base, we cannot also have a
15007     // BaseReg specified.
15008     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15009       return false;
15010
15011     // If lower 4G is not available, then we must use rip-relative addressing.
15012     if ((M != CodeModel::Small || R != Reloc::Static) &&
15013         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15014       return false;
15015   }
15016
15017   switch (AM.Scale) {
15018   case 0:
15019   case 1:
15020   case 2:
15021   case 4:
15022   case 8:
15023     // These scales always work.
15024     break;
15025   case 3:
15026   case 5:
15027   case 9:
15028     // These scales are formed with basereg+scalereg.  Only accept if there is
15029     // no basereg yet.
15030     if (AM.HasBaseReg)
15031       return false;
15032     break;
15033   default:  // Other stuff never works.
15034     return false;
15035   }
15036
15037   return true;
15038 }
15039
15040 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15041   unsigned Bits = Ty->getScalarSizeInBits();
15042
15043   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15044   // particularly cheaper than those without.
15045   if (Bits == 8)
15046     return false;
15047
15048   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15049   // variable shifts just as cheap as scalar ones.
15050   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15051     return false;
15052
15053   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15054   // fully general vector.
15055   return true;
15056 }
15057
15058 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15059   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15060     return false;
15061   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15062   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15063   return NumBits1 > NumBits2;
15064 }
15065
15066 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15067   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15068     return false;
15069
15070   if (!isTypeLegal(EVT::getEVT(Ty1)))
15071     return false;
15072
15073   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15074
15075   // Assuming the caller doesn't have a zeroext or signext return parameter,
15076   // truncation all the way down to i1 is valid.
15077   return true;
15078 }
15079
15080 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15081   return isInt<32>(Imm);
15082 }
15083
15084 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15085   // Can also use sub to handle negated immediates.
15086   return isInt<32>(Imm);
15087 }
15088
15089 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15090   if (!VT1.isInteger() || !VT2.isInteger())
15091     return false;
15092   unsigned NumBits1 = VT1.getSizeInBits();
15093   unsigned NumBits2 = VT2.getSizeInBits();
15094   return NumBits1 > NumBits2;
15095 }
15096
15097 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15098   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15099   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15100 }
15101
15102 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15103   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15104   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15105 }
15106
15107 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15108   EVT VT1 = Val.getValueType();
15109   if (isZExtFree(VT1, VT2))
15110     return true;
15111
15112   if (Val.getOpcode() != ISD::LOAD)
15113     return false;
15114
15115   if (!VT1.isSimple() || !VT1.isInteger() ||
15116       !VT2.isSimple() || !VT2.isInteger())
15117     return false;
15118
15119   switch (VT1.getSimpleVT().SimpleTy) {
15120   default: break;
15121   case MVT::i8:
15122   case MVT::i16:
15123   case MVT::i32:
15124     // X86 has 8, 16, and 32-bit zero-extending loads.
15125     return true;
15126   }
15127
15128   return false;
15129 }
15130
15131 bool
15132 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15133   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15134     return false;
15135
15136   VT = VT.getScalarType();
15137
15138   if (!VT.isSimple())
15139     return false;
15140
15141   switch (VT.getSimpleVT().SimpleTy) {
15142   case MVT::f32:
15143   case MVT::f64:
15144     return true;
15145   default:
15146     break;
15147   }
15148
15149   return false;
15150 }
15151
15152 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15153   // i16 instructions are longer (0x66 prefix) and potentially slower.
15154   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15155 }
15156
15157 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15158 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15159 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15160 /// are assumed to be legal.
15161 bool
15162 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15163                                       EVT VT) const {
15164   if (!VT.isSimple())
15165     return false;
15166
15167   MVT SVT = VT.getSimpleVT();
15168
15169   // Very little shuffling can be done for 64-bit vectors right now.
15170   if (VT.getSizeInBits() == 64)
15171     return false;
15172
15173   // If this is a single-input shuffle with no 128 bit lane crossings we can
15174   // lower it into pshufb.
15175   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15176       (SVT.is256BitVector() && Subtarget->hasInt256())) {
15177     bool isLegal = true;
15178     for (unsigned I = 0, E = M.size(); I != E; ++I) {
15179       if (M[I] >= (int)SVT.getVectorNumElements() ||
15180           ShuffleCrosses128bitLane(SVT, I, M[I])) {
15181         isLegal = false;
15182         break;
15183       }
15184     }
15185     if (isLegal)
15186       return true;
15187   }
15188
15189   // FIXME: blends, shifts.
15190   return (SVT.getVectorNumElements() == 2 ||
15191           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15192           isMOVLMask(M, SVT) ||
15193           isSHUFPMask(M, SVT) ||
15194           isPSHUFDMask(M, SVT) ||
15195           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15196           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15197           isPALIGNRMask(M, SVT, Subtarget) ||
15198           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15199           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15200           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15201           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15202           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15203 }
15204
15205 bool
15206 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15207                                           EVT VT) const {
15208   if (!VT.isSimple())
15209     return false;
15210
15211   MVT SVT = VT.getSimpleVT();
15212   unsigned NumElts = SVT.getVectorNumElements();
15213   // FIXME: This collection of masks seems suspect.
15214   if (NumElts == 2)
15215     return true;
15216   if (NumElts == 4 && SVT.is128BitVector()) {
15217     return (isMOVLMask(Mask, SVT)  ||
15218             isCommutedMOVLMask(Mask, SVT, true) ||
15219             isSHUFPMask(Mask, SVT) ||
15220             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15221   }
15222   return false;
15223 }
15224
15225 //===----------------------------------------------------------------------===//
15226 //                           X86 Scheduler Hooks
15227 //===----------------------------------------------------------------------===//
15228
15229 /// Utility function to emit xbegin specifying the start of an RTM region.
15230 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15231                                      const TargetInstrInfo *TII) {
15232   DebugLoc DL = MI->getDebugLoc();
15233
15234   const BasicBlock *BB = MBB->getBasicBlock();
15235   MachineFunction::iterator I = MBB;
15236   ++I;
15237
15238   // For the v = xbegin(), we generate
15239   //
15240   // thisMBB:
15241   //  xbegin sinkMBB
15242   //
15243   // mainMBB:
15244   //  eax = -1
15245   //
15246   // sinkMBB:
15247   //  v = eax
15248
15249   MachineBasicBlock *thisMBB = MBB;
15250   MachineFunction *MF = MBB->getParent();
15251   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15252   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15253   MF->insert(I, mainMBB);
15254   MF->insert(I, sinkMBB);
15255
15256   // Transfer the remainder of BB and its successor edges to sinkMBB.
15257   sinkMBB->splice(sinkMBB->begin(), MBB,
15258                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15259   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15260
15261   // thisMBB:
15262   //  xbegin sinkMBB
15263   //  # fallthrough to mainMBB
15264   //  # abortion to sinkMBB
15265   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15266   thisMBB->addSuccessor(mainMBB);
15267   thisMBB->addSuccessor(sinkMBB);
15268
15269   // mainMBB:
15270   //  EAX = -1
15271   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15272   mainMBB->addSuccessor(sinkMBB);
15273
15274   // sinkMBB:
15275   // EAX is live into the sinkMBB
15276   sinkMBB->addLiveIn(X86::EAX);
15277   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15278           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15279     .addReg(X86::EAX);
15280
15281   MI->eraseFromParent();
15282   return sinkMBB;
15283 }
15284
15285 // Get CMPXCHG opcode for the specified data type.
15286 static unsigned getCmpXChgOpcode(EVT VT) {
15287   switch (VT.getSimpleVT().SimpleTy) {
15288   case MVT::i8:  return X86::LCMPXCHG8;
15289   case MVT::i16: return X86::LCMPXCHG16;
15290   case MVT::i32: return X86::LCMPXCHG32;
15291   case MVT::i64: return X86::LCMPXCHG64;
15292   default:
15293     break;
15294   }
15295   llvm_unreachable("Invalid operand size!");
15296 }
15297
15298 // Get LOAD opcode for the specified data type.
15299 static unsigned getLoadOpcode(EVT VT) {
15300   switch (VT.getSimpleVT().SimpleTy) {
15301   case MVT::i8:  return X86::MOV8rm;
15302   case MVT::i16: return X86::MOV16rm;
15303   case MVT::i32: return X86::MOV32rm;
15304   case MVT::i64: return X86::MOV64rm;
15305   default:
15306     break;
15307   }
15308   llvm_unreachable("Invalid operand size!");
15309 }
15310
15311 // Get opcode of the non-atomic one from the specified atomic instruction.
15312 static unsigned getNonAtomicOpcode(unsigned Opc) {
15313   switch (Opc) {
15314   case X86::ATOMAND8:  return X86::AND8rr;
15315   case X86::ATOMAND16: return X86::AND16rr;
15316   case X86::ATOMAND32: return X86::AND32rr;
15317   case X86::ATOMAND64: return X86::AND64rr;
15318   case X86::ATOMOR8:   return X86::OR8rr;
15319   case X86::ATOMOR16:  return X86::OR16rr;
15320   case X86::ATOMOR32:  return X86::OR32rr;
15321   case X86::ATOMOR64:  return X86::OR64rr;
15322   case X86::ATOMXOR8:  return X86::XOR8rr;
15323   case X86::ATOMXOR16: return X86::XOR16rr;
15324   case X86::ATOMXOR32: return X86::XOR32rr;
15325   case X86::ATOMXOR64: return X86::XOR64rr;
15326   }
15327   llvm_unreachable("Unhandled atomic-load-op opcode!");
15328 }
15329
15330 // Get opcode of the non-atomic one from the specified atomic instruction with
15331 // extra opcode.
15332 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15333                                                unsigned &ExtraOpc) {
15334   switch (Opc) {
15335   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15336   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15337   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15338   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15339   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15340   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15341   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15342   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15343   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15344   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15345   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15346   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15347   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15348   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15349   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15350   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15351   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15352   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15353   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15354   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15355   }
15356   llvm_unreachable("Unhandled atomic-load-op opcode!");
15357 }
15358
15359 // Get opcode of the non-atomic one from the specified atomic instruction for
15360 // 64-bit data type on 32-bit target.
15361 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15362   switch (Opc) {
15363   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15364   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15365   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15366   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15367   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15368   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15369   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15370   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15371   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15372   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15373   }
15374   llvm_unreachable("Unhandled atomic-load-op opcode!");
15375 }
15376
15377 // Get opcode of the non-atomic one from the specified atomic instruction for
15378 // 64-bit data type on 32-bit target with extra opcode.
15379 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15380                                                    unsigned &HiOpc,
15381                                                    unsigned &ExtraOpc) {
15382   switch (Opc) {
15383   case X86::ATOMNAND6432:
15384     ExtraOpc = X86::NOT32r;
15385     HiOpc = X86::AND32rr;
15386     return X86::AND32rr;
15387   }
15388   llvm_unreachable("Unhandled atomic-load-op opcode!");
15389 }
15390
15391 // Get pseudo CMOV opcode from the specified data type.
15392 static unsigned getPseudoCMOVOpc(EVT VT) {
15393   switch (VT.getSimpleVT().SimpleTy) {
15394   case MVT::i8:  return X86::CMOV_GR8;
15395   case MVT::i16: return X86::CMOV_GR16;
15396   case MVT::i32: return X86::CMOV_GR32;
15397   default:
15398     break;
15399   }
15400   llvm_unreachable("Unknown CMOV opcode!");
15401 }
15402
15403 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15404 // They will be translated into a spin-loop or compare-exchange loop from
15405 //
15406 //    ...
15407 //    dst = atomic-fetch-op MI.addr, MI.val
15408 //    ...
15409 //
15410 // to
15411 //
15412 //    ...
15413 //    t1 = LOAD MI.addr
15414 // loop:
15415 //    t4 = phi(t1, t3 / loop)
15416 //    t2 = OP MI.val, t4
15417 //    EAX = t4
15418 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15419 //    t3 = EAX
15420 //    JNE loop
15421 // sink:
15422 //    dst = t3
15423 //    ...
15424 MachineBasicBlock *
15425 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15426                                        MachineBasicBlock *MBB) const {
15427   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15428   DebugLoc DL = MI->getDebugLoc();
15429
15430   MachineFunction *MF = MBB->getParent();
15431   MachineRegisterInfo &MRI = MF->getRegInfo();
15432
15433   const BasicBlock *BB = MBB->getBasicBlock();
15434   MachineFunction::iterator I = MBB;
15435   ++I;
15436
15437   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15438          "Unexpected number of operands");
15439
15440   assert(MI->hasOneMemOperand() &&
15441          "Expected atomic-load-op to have one memoperand");
15442
15443   // Memory Reference
15444   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15445   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15446
15447   unsigned DstReg, SrcReg;
15448   unsigned MemOpndSlot;
15449
15450   unsigned CurOp = 0;
15451
15452   DstReg = MI->getOperand(CurOp++).getReg();
15453   MemOpndSlot = CurOp;
15454   CurOp += X86::AddrNumOperands;
15455   SrcReg = MI->getOperand(CurOp++).getReg();
15456
15457   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15458   MVT::SimpleValueType VT = *RC->vt_begin();
15459   unsigned t1 = MRI.createVirtualRegister(RC);
15460   unsigned t2 = MRI.createVirtualRegister(RC);
15461   unsigned t3 = MRI.createVirtualRegister(RC);
15462   unsigned t4 = MRI.createVirtualRegister(RC);
15463   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15464
15465   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15466   unsigned LOADOpc = getLoadOpcode(VT);
15467
15468   // For the atomic load-arith operator, we generate
15469   //
15470   //  thisMBB:
15471   //    t1 = LOAD [MI.addr]
15472   //  mainMBB:
15473   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15474   //    t1 = OP MI.val, EAX
15475   //    EAX = t4
15476   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15477   //    t3 = EAX
15478   //    JNE mainMBB
15479   //  sinkMBB:
15480   //    dst = t3
15481
15482   MachineBasicBlock *thisMBB = MBB;
15483   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15484   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15485   MF->insert(I, mainMBB);
15486   MF->insert(I, sinkMBB);
15487
15488   MachineInstrBuilder MIB;
15489
15490   // Transfer the remainder of BB and its successor edges to sinkMBB.
15491   sinkMBB->splice(sinkMBB->begin(), MBB,
15492                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15493   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15494
15495   // thisMBB:
15496   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15497   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15498     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15499     if (NewMO.isReg())
15500       NewMO.setIsKill(false);
15501     MIB.addOperand(NewMO);
15502   }
15503   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15504     unsigned flags = (*MMOI)->getFlags();
15505     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15506     MachineMemOperand *MMO =
15507       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15508                                (*MMOI)->getSize(),
15509                                (*MMOI)->getBaseAlignment(),
15510                                (*MMOI)->getTBAAInfo(),
15511                                (*MMOI)->getRanges());
15512     MIB.addMemOperand(MMO);
15513   }
15514
15515   thisMBB->addSuccessor(mainMBB);
15516
15517   // mainMBB:
15518   MachineBasicBlock *origMainMBB = mainMBB;
15519
15520   // Add a PHI.
15521   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15522                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15523
15524   unsigned Opc = MI->getOpcode();
15525   switch (Opc) {
15526   default:
15527     llvm_unreachable("Unhandled atomic-load-op opcode!");
15528   case X86::ATOMAND8:
15529   case X86::ATOMAND16:
15530   case X86::ATOMAND32:
15531   case X86::ATOMAND64:
15532   case X86::ATOMOR8:
15533   case X86::ATOMOR16:
15534   case X86::ATOMOR32:
15535   case X86::ATOMOR64:
15536   case X86::ATOMXOR8:
15537   case X86::ATOMXOR16:
15538   case X86::ATOMXOR32:
15539   case X86::ATOMXOR64: {
15540     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15541     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15542       .addReg(t4);
15543     break;
15544   }
15545   case X86::ATOMNAND8:
15546   case X86::ATOMNAND16:
15547   case X86::ATOMNAND32:
15548   case X86::ATOMNAND64: {
15549     unsigned Tmp = MRI.createVirtualRegister(RC);
15550     unsigned NOTOpc;
15551     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15552     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15553       .addReg(t4);
15554     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15555     break;
15556   }
15557   case X86::ATOMMAX8:
15558   case X86::ATOMMAX16:
15559   case X86::ATOMMAX32:
15560   case X86::ATOMMAX64:
15561   case X86::ATOMMIN8:
15562   case X86::ATOMMIN16:
15563   case X86::ATOMMIN32:
15564   case X86::ATOMMIN64:
15565   case X86::ATOMUMAX8:
15566   case X86::ATOMUMAX16:
15567   case X86::ATOMUMAX32:
15568   case X86::ATOMUMAX64:
15569   case X86::ATOMUMIN8:
15570   case X86::ATOMUMIN16:
15571   case X86::ATOMUMIN32:
15572   case X86::ATOMUMIN64: {
15573     unsigned CMPOpc;
15574     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15575
15576     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15577       .addReg(SrcReg)
15578       .addReg(t4);
15579
15580     if (Subtarget->hasCMov()) {
15581       if (VT != MVT::i8) {
15582         // Native support
15583         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15584           .addReg(SrcReg)
15585           .addReg(t4);
15586       } else {
15587         // Promote i8 to i32 to use CMOV32
15588         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15589         const TargetRegisterClass *RC32 =
15590           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15591         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15592         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15593         unsigned Tmp = MRI.createVirtualRegister(RC32);
15594
15595         unsigned Undef = MRI.createVirtualRegister(RC32);
15596         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15597
15598         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15599           .addReg(Undef)
15600           .addReg(SrcReg)
15601           .addImm(X86::sub_8bit);
15602         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15603           .addReg(Undef)
15604           .addReg(t4)
15605           .addImm(X86::sub_8bit);
15606
15607         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15608           .addReg(SrcReg32)
15609           .addReg(AccReg32);
15610
15611         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15612           .addReg(Tmp, 0, X86::sub_8bit);
15613       }
15614     } else {
15615       // Use pseudo select and lower them.
15616       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15617              "Invalid atomic-load-op transformation!");
15618       unsigned SelOpc = getPseudoCMOVOpc(VT);
15619       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15620       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15621       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15622               .addReg(SrcReg).addReg(t4)
15623               .addImm(CC);
15624       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15625       // Replace the original PHI node as mainMBB is changed after CMOV
15626       // lowering.
15627       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15628         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15629       Phi->eraseFromParent();
15630     }
15631     break;
15632   }
15633   }
15634
15635   // Copy PhyReg back from virtual register.
15636   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15637     .addReg(t4);
15638
15639   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15640   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15641     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15642     if (NewMO.isReg())
15643       NewMO.setIsKill(false);
15644     MIB.addOperand(NewMO);
15645   }
15646   MIB.addReg(t2);
15647   MIB.setMemRefs(MMOBegin, MMOEnd);
15648
15649   // Copy PhyReg back to virtual register.
15650   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15651     .addReg(PhyReg);
15652
15653   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15654
15655   mainMBB->addSuccessor(origMainMBB);
15656   mainMBB->addSuccessor(sinkMBB);
15657
15658   // sinkMBB:
15659   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15660           TII->get(TargetOpcode::COPY), DstReg)
15661     .addReg(t3);
15662
15663   MI->eraseFromParent();
15664   return sinkMBB;
15665 }
15666
15667 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15668 // instructions. They will be translated into a spin-loop or compare-exchange
15669 // loop from
15670 //
15671 //    ...
15672 //    dst = atomic-fetch-op MI.addr, MI.val
15673 //    ...
15674 //
15675 // to
15676 //
15677 //    ...
15678 //    t1L = LOAD [MI.addr + 0]
15679 //    t1H = LOAD [MI.addr + 4]
15680 // loop:
15681 //    t4L = phi(t1L, t3L / loop)
15682 //    t4H = phi(t1H, t3H / loop)
15683 //    t2L = OP MI.val.lo, t4L
15684 //    t2H = OP MI.val.hi, t4H
15685 //    EAX = t4L
15686 //    EDX = t4H
15687 //    EBX = t2L
15688 //    ECX = t2H
15689 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15690 //    t3L = EAX
15691 //    t3H = EDX
15692 //    JNE loop
15693 // sink:
15694 //    dstL = t3L
15695 //    dstH = t3H
15696 //    ...
15697 MachineBasicBlock *
15698 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15699                                            MachineBasicBlock *MBB) const {
15700   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15701   DebugLoc DL = MI->getDebugLoc();
15702
15703   MachineFunction *MF = MBB->getParent();
15704   MachineRegisterInfo &MRI = MF->getRegInfo();
15705
15706   const BasicBlock *BB = MBB->getBasicBlock();
15707   MachineFunction::iterator I = MBB;
15708   ++I;
15709
15710   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15711          "Unexpected number of operands");
15712
15713   assert(MI->hasOneMemOperand() &&
15714          "Expected atomic-load-op32 to have one memoperand");
15715
15716   // Memory Reference
15717   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15718   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15719
15720   unsigned DstLoReg, DstHiReg;
15721   unsigned SrcLoReg, SrcHiReg;
15722   unsigned MemOpndSlot;
15723
15724   unsigned CurOp = 0;
15725
15726   DstLoReg = MI->getOperand(CurOp++).getReg();
15727   DstHiReg = MI->getOperand(CurOp++).getReg();
15728   MemOpndSlot = CurOp;
15729   CurOp += X86::AddrNumOperands;
15730   SrcLoReg = MI->getOperand(CurOp++).getReg();
15731   SrcHiReg = MI->getOperand(CurOp++).getReg();
15732
15733   const TargetRegisterClass *RC = &X86::GR32RegClass;
15734   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15735
15736   unsigned t1L = MRI.createVirtualRegister(RC);
15737   unsigned t1H = MRI.createVirtualRegister(RC);
15738   unsigned t2L = MRI.createVirtualRegister(RC);
15739   unsigned t2H = MRI.createVirtualRegister(RC);
15740   unsigned t3L = MRI.createVirtualRegister(RC);
15741   unsigned t3H = MRI.createVirtualRegister(RC);
15742   unsigned t4L = MRI.createVirtualRegister(RC);
15743   unsigned t4H = MRI.createVirtualRegister(RC);
15744
15745   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15746   unsigned LOADOpc = X86::MOV32rm;
15747
15748   // For the atomic load-arith operator, we generate
15749   //
15750   //  thisMBB:
15751   //    t1L = LOAD [MI.addr + 0]
15752   //    t1H = LOAD [MI.addr + 4]
15753   //  mainMBB:
15754   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15755   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15756   //    t2L = OP MI.val.lo, t4L
15757   //    t2H = OP MI.val.hi, t4H
15758   //    EBX = t2L
15759   //    ECX = t2H
15760   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15761   //    t3L = EAX
15762   //    t3H = EDX
15763   //    JNE loop
15764   //  sinkMBB:
15765   //    dstL = t3L
15766   //    dstH = t3H
15767
15768   MachineBasicBlock *thisMBB = MBB;
15769   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15770   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15771   MF->insert(I, mainMBB);
15772   MF->insert(I, sinkMBB);
15773
15774   MachineInstrBuilder MIB;
15775
15776   // Transfer the remainder of BB and its successor edges to sinkMBB.
15777   sinkMBB->splice(sinkMBB->begin(), MBB,
15778                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15779   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15780
15781   // thisMBB:
15782   // Lo
15783   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15784   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15785     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15786     if (NewMO.isReg())
15787       NewMO.setIsKill(false);
15788     MIB.addOperand(NewMO);
15789   }
15790   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15791     unsigned flags = (*MMOI)->getFlags();
15792     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15793     MachineMemOperand *MMO =
15794       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15795                                (*MMOI)->getSize(),
15796                                (*MMOI)->getBaseAlignment(),
15797                                (*MMOI)->getTBAAInfo(),
15798                                (*MMOI)->getRanges());
15799     MIB.addMemOperand(MMO);
15800   };
15801   MachineInstr *LowMI = MIB;
15802
15803   // Hi
15804   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15805   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15806     if (i == X86::AddrDisp) {
15807       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15808     } else {
15809       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15810       if (NewMO.isReg())
15811         NewMO.setIsKill(false);
15812       MIB.addOperand(NewMO);
15813     }
15814   }
15815   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15816
15817   thisMBB->addSuccessor(mainMBB);
15818
15819   // mainMBB:
15820   MachineBasicBlock *origMainMBB = mainMBB;
15821
15822   // Add PHIs.
15823   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15824                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15825   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15826                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15827
15828   unsigned Opc = MI->getOpcode();
15829   switch (Opc) {
15830   default:
15831     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15832   case X86::ATOMAND6432:
15833   case X86::ATOMOR6432:
15834   case X86::ATOMXOR6432:
15835   case X86::ATOMADD6432:
15836   case X86::ATOMSUB6432: {
15837     unsigned HiOpc;
15838     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15839     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15840       .addReg(SrcLoReg);
15841     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15842       .addReg(SrcHiReg);
15843     break;
15844   }
15845   case X86::ATOMNAND6432: {
15846     unsigned HiOpc, NOTOpc;
15847     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15848     unsigned TmpL = MRI.createVirtualRegister(RC);
15849     unsigned TmpH = MRI.createVirtualRegister(RC);
15850     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15851       .addReg(t4L);
15852     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15853       .addReg(t4H);
15854     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15855     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15856     break;
15857   }
15858   case X86::ATOMMAX6432:
15859   case X86::ATOMMIN6432:
15860   case X86::ATOMUMAX6432:
15861   case X86::ATOMUMIN6432: {
15862     unsigned HiOpc;
15863     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15864     unsigned cL = MRI.createVirtualRegister(RC8);
15865     unsigned cH = MRI.createVirtualRegister(RC8);
15866     unsigned cL32 = MRI.createVirtualRegister(RC);
15867     unsigned cH32 = MRI.createVirtualRegister(RC);
15868     unsigned cc = MRI.createVirtualRegister(RC);
15869     // cl := cmp src_lo, lo
15870     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15871       .addReg(SrcLoReg).addReg(t4L);
15872     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15873     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15874     // ch := cmp src_hi, hi
15875     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15876       .addReg(SrcHiReg).addReg(t4H);
15877     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15878     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15879     // cc := if (src_hi == hi) ? cl : ch;
15880     if (Subtarget->hasCMov()) {
15881       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15882         .addReg(cH32).addReg(cL32);
15883     } else {
15884       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15885               .addReg(cH32).addReg(cL32)
15886               .addImm(X86::COND_E);
15887       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15888     }
15889     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15890     if (Subtarget->hasCMov()) {
15891       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15892         .addReg(SrcLoReg).addReg(t4L);
15893       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15894         .addReg(SrcHiReg).addReg(t4H);
15895     } else {
15896       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15897               .addReg(SrcLoReg).addReg(t4L)
15898               .addImm(X86::COND_NE);
15899       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15900       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15901       // 2nd CMOV lowering.
15902       mainMBB->addLiveIn(X86::EFLAGS);
15903       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15904               .addReg(SrcHiReg).addReg(t4H)
15905               .addImm(X86::COND_NE);
15906       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15907       // Replace the original PHI node as mainMBB is changed after CMOV
15908       // lowering.
15909       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15910         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15911       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15912         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15913       PhiL->eraseFromParent();
15914       PhiH->eraseFromParent();
15915     }
15916     break;
15917   }
15918   case X86::ATOMSWAP6432: {
15919     unsigned HiOpc;
15920     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15921     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15922     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15923     break;
15924   }
15925   }
15926
15927   // Copy EDX:EAX back from HiReg:LoReg
15928   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15929   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15930   // Copy ECX:EBX from t1H:t1L
15931   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15932   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15933
15934   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15935   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15936     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15937     if (NewMO.isReg())
15938       NewMO.setIsKill(false);
15939     MIB.addOperand(NewMO);
15940   }
15941   MIB.setMemRefs(MMOBegin, MMOEnd);
15942
15943   // Copy EDX:EAX back to t3H:t3L
15944   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15945   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15946
15947   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15948
15949   mainMBB->addSuccessor(origMainMBB);
15950   mainMBB->addSuccessor(sinkMBB);
15951
15952   // sinkMBB:
15953   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15954           TII->get(TargetOpcode::COPY), DstLoReg)
15955     .addReg(t3L);
15956   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15957           TII->get(TargetOpcode::COPY), DstHiReg)
15958     .addReg(t3H);
15959
15960   MI->eraseFromParent();
15961   return sinkMBB;
15962 }
15963
15964 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15965 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15966 // in the .td file.
15967 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15968                                        const TargetInstrInfo *TII) {
15969   unsigned Opc;
15970   switch (MI->getOpcode()) {
15971   default: llvm_unreachable("illegal opcode!");
15972   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15973   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15974   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15975   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15976   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15977   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15978   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15979   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15980   }
15981
15982   DebugLoc dl = MI->getDebugLoc();
15983   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15984
15985   unsigned NumArgs = MI->getNumOperands();
15986   for (unsigned i = 1; i < NumArgs; ++i) {
15987     MachineOperand &Op = MI->getOperand(i);
15988     if (!(Op.isReg() && Op.isImplicit()))
15989       MIB.addOperand(Op);
15990   }
15991   if (MI->hasOneMemOperand())
15992     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15993
15994   BuildMI(*BB, MI, dl,
15995     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15996     .addReg(X86::XMM0);
15997
15998   MI->eraseFromParent();
15999   return BB;
16000 }
16001
16002 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16003 // defs in an instruction pattern
16004 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16005                                        const TargetInstrInfo *TII) {
16006   unsigned Opc;
16007   switch (MI->getOpcode()) {
16008   default: llvm_unreachable("illegal opcode!");
16009   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16010   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16011   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16012   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16013   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16014   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16015   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16016   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16017   }
16018
16019   DebugLoc dl = MI->getDebugLoc();
16020   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16021
16022   unsigned NumArgs = MI->getNumOperands(); // remove the results
16023   for (unsigned i = 1; i < NumArgs; ++i) {
16024     MachineOperand &Op = MI->getOperand(i);
16025     if (!(Op.isReg() && Op.isImplicit()))
16026       MIB.addOperand(Op);
16027   }
16028   if (MI->hasOneMemOperand())
16029     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16030
16031   BuildMI(*BB, MI, dl,
16032     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16033     .addReg(X86::ECX);
16034
16035   MI->eraseFromParent();
16036   return BB;
16037 }
16038
16039 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16040                                        const TargetInstrInfo *TII,
16041                                        const X86Subtarget* Subtarget) {
16042   DebugLoc dl = MI->getDebugLoc();
16043
16044   // Address into RAX/EAX, other two args into ECX, EDX.
16045   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16046   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16047   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16048   for (int i = 0; i < X86::AddrNumOperands; ++i)
16049     MIB.addOperand(MI->getOperand(i));
16050
16051   unsigned ValOps = X86::AddrNumOperands;
16052   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16053     .addReg(MI->getOperand(ValOps).getReg());
16054   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16055     .addReg(MI->getOperand(ValOps+1).getReg());
16056
16057   // The instruction doesn't actually take any operands though.
16058   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16059
16060   MI->eraseFromParent(); // The pseudo is gone now.
16061   return BB;
16062 }
16063
16064 MachineBasicBlock *
16065 X86TargetLowering::EmitVAARG64WithCustomInserter(
16066                    MachineInstr *MI,
16067                    MachineBasicBlock *MBB) const {
16068   // Emit va_arg instruction on X86-64.
16069
16070   // Operands to this pseudo-instruction:
16071   // 0  ) Output        : destination address (reg)
16072   // 1-5) Input         : va_list address (addr, i64mem)
16073   // 6  ) ArgSize       : Size (in bytes) of vararg type
16074   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16075   // 8  ) Align         : Alignment of type
16076   // 9  ) EFLAGS (implicit-def)
16077
16078   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16079   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16080
16081   unsigned DestReg = MI->getOperand(0).getReg();
16082   MachineOperand &Base = MI->getOperand(1);
16083   MachineOperand &Scale = MI->getOperand(2);
16084   MachineOperand &Index = MI->getOperand(3);
16085   MachineOperand &Disp = MI->getOperand(4);
16086   MachineOperand &Segment = MI->getOperand(5);
16087   unsigned ArgSize = MI->getOperand(6).getImm();
16088   unsigned ArgMode = MI->getOperand(7).getImm();
16089   unsigned Align = MI->getOperand(8).getImm();
16090
16091   // Memory Reference
16092   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16093   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16094   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16095
16096   // Machine Information
16097   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16098   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16099   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16100   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16101   DebugLoc DL = MI->getDebugLoc();
16102
16103   // struct va_list {
16104   //   i32   gp_offset
16105   //   i32   fp_offset
16106   //   i64   overflow_area (address)
16107   //   i64   reg_save_area (address)
16108   // }
16109   // sizeof(va_list) = 24
16110   // alignment(va_list) = 8
16111
16112   unsigned TotalNumIntRegs = 6;
16113   unsigned TotalNumXMMRegs = 8;
16114   bool UseGPOffset = (ArgMode == 1);
16115   bool UseFPOffset = (ArgMode == 2);
16116   unsigned MaxOffset = TotalNumIntRegs * 8 +
16117                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16118
16119   /* Align ArgSize to a multiple of 8 */
16120   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16121   bool NeedsAlign = (Align > 8);
16122
16123   MachineBasicBlock *thisMBB = MBB;
16124   MachineBasicBlock *overflowMBB;
16125   MachineBasicBlock *offsetMBB;
16126   MachineBasicBlock *endMBB;
16127
16128   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16129   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16130   unsigned OffsetReg = 0;
16131
16132   if (!UseGPOffset && !UseFPOffset) {
16133     // If we only pull from the overflow region, we don't create a branch.
16134     // We don't need to alter control flow.
16135     OffsetDestReg = 0; // unused
16136     OverflowDestReg = DestReg;
16137
16138     offsetMBB = nullptr;
16139     overflowMBB = thisMBB;
16140     endMBB = thisMBB;
16141   } else {
16142     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16143     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16144     // If not, pull from overflow_area. (branch to overflowMBB)
16145     //
16146     //       thisMBB
16147     //         |     .
16148     //         |        .
16149     //     offsetMBB   overflowMBB
16150     //         |        .
16151     //         |     .
16152     //        endMBB
16153
16154     // Registers for the PHI in endMBB
16155     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16156     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16157
16158     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16159     MachineFunction *MF = MBB->getParent();
16160     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16161     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16162     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16163
16164     MachineFunction::iterator MBBIter = MBB;
16165     ++MBBIter;
16166
16167     // Insert the new basic blocks
16168     MF->insert(MBBIter, offsetMBB);
16169     MF->insert(MBBIter, overflowMBB);
16170     MF->insert(MBBIter, endMBB);
16171
16172     // Transfer the remainder of MBB and its successor edges to endMBB.
16173     endMBB->splice(endMBB->begin(), thisMBB,
16174                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16175     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16176
16177     // Make offsetMBB and overflowMBB successors of thisMBB
16178     thisMBB->addSuccessor(offsetMBB);
16179     thisMBB->addSuccessor(overflowMBB);
16180
16181     // endMBB is a successor of both offsetMBB and overflowMBB
16182     offsetMBB->addSuccessor(endMBB);
16183     overflowMBB->addSuccessor(endMBB);
16184
16185     // Load the offset value into a register
16186     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16187     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16188       .addOperand(Base)
16189       .addOperand(Scale)
16190       .addOperand(Index)
16191       .addDisp(Disp, UseFPOffset ? 4 : 0)
16192       .addOperand(Segment)
16193       .setMemRefs(MMOBegin, MMOEnd);
16194
16195     // Check if there is enough room left to pull this argument.
16196     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16197       .addReg(OffsetReg)
16198       .addImm(MaxOffset + 8 - ArgSizeA8);
16199
16200     // Branch to "overflowMBB" if offset >= max
16201     // Fall through to "offsetMBB" otherwise
16202     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16203       .addMBB(overflowMBB);
16204   }
16205
16206   // In offsetMBB, emit code to use the reg_save_area.
16207   if (offsetMBB) {
16208     assert(OffsetReg != 0);
16209
16210     // Read the reg_save_area address.
16211     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16212     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16213       .addOperand(Base)
16214       .addOperand(Scale)
16215       .addOperand(Index)
16216       .addDisp(Disp, 16)
16217       .addOperand(Segment)
16218       .setMemRefs(MMOBegin, MMOEnd);
16219
16220     // Zero-extend the offset
16221     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16222       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16223         .addImm(0)
16224         .addReg(OffsetReg)
16225         .addImm(X86::sub_32bit);
16226
16227     // Add the offset to the reg_save_area to get the final address.
16228     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16229       .addReg(OffsetReg64)
16230       .addReg(RegSaveReg);
16231
16232     // Compute the offset for the next argument
16233     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16234     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16235       .addReg(OffsetReg)
16236       .addImm(UseFPOffset ? 16 : 8);
16237
16238     // Store it back into the va_list.
16239     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16240       .addOperand(Base)
16241       .addOperand(Scale)
16242       .addOperand(Index)
16243       .addDisp(Disp, UseFPOffset ? 4 : 0)
16244       .addOperand(Segment)
16245       .addReg(NextOffsetReg)
16246       .setMemRefs(MMOBegin, MMOEnd);
16247
16248     // Jump to endMBB
16249     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16250       .addMBB(endMBB);
16251   }
16252
16253   //
16254   // Emit code to use overflow area
16255   //
16256
16257   // Load the overflow_area address into a register.
16258   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16259   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16260     .addOperand(Base)
16261     .addOperand(Scale)
16262     .addOperand(Index)
16263     .addDisp(Disp, 8)
16264     .addOperand(Segment)
16265     .setMemRefs(MMOBegin, MMOEnd);
16266
16267   // If we need to align it, do so. Otherwise, just copy the address
16268   // to OverflowDestReg.
16269   if (NeedsAlign) {
16270     // Align the overflow address
16271     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16272     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16273
16274     // aligned_addr = (addr + (align-1)) & ~(align-1)
16275     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16276       .addReg(OverflowAddrReg)
16277       .addImm(Align-1);
16278
16279     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16280       .addReg(TmpReg)
16281       .addImm(~(uint64_t)(Align-1));
16282   } else {
16283     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16284       .addReg(OverflowAddrReg);
16285   }
16286
16287   // Compute the next overflow address after this argument.
16288   // (the overflow address should be kept 8-byte aligned)
16289   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16290   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16291     .addReg(OverflowDestReg)
16292     .addImm(ArgSizeA8);
16293
16294   // Store the new overflow address.
16295   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16296     .addOperand(Base)
16297     .addOperand(Scale)
16298     .addOperand(Index)
16299     .addDisp(Disp, 8)
16300     .addOperand(Segment)
16301     .addReg(NextAddrReg)
16302     .setMemRefs(MMOBegin, MMOEnd);
16303
16304   // If we branched, emit the PHI to the front of endMBB.
16305   if (offsetMBB) {
16306     BuildMI(*endMBB, endMBB->begin(), DL,
16307             TII->get(X86::PHI), DestReg)
16308       .addReg(OffsetDestReg).addMBB(offsetMBB)
16309       .addReg(OverflowDestReg).addMBB(overflowMBB);
16310   }
16311
16312   // Erase the pseudo instruction
16313   MI->eraseFromParent();
16314
16315   return endMBB;
16316 }
16317
16318 MachineBasicBlock *
16319 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16320                                                  MachineInstr *MI,
16321                                                  MachineBasicBlock *MBB) const {
16322   // Emit code to save XMM registers to the stack. The ABI says that the
16323   // number of registers to save is given in %al, so it's theoretically
16324   // possible to do an indirect jump trick to avoid saving all of them,
16325   // however this code takes a simpler approach and just executes all
16326   // of the stores if %al is non-zero. It's less code, and it's probably
16327   // easier on the hardware branch predictor, and stores aren't all that
16328   // expensive anyway.
16329
16330   // Create the new basic blocks. One block contains all the XMM stores,
16331   // and one block is the final destination regardless of whether any
16332   // stores were performed.
16333   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16334   MachineFunction *F = MBB->getParent();
16335   MachineFunction::iterator MBBIter = MBB;
16336   ++MBBIter;
16337   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16338   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16339   F->insert(MBBIter, XMMSaveMBB);
16340   F->insert(MBBIter, EndMBB);
16341
16342   // Transfer the remainder of MBB and its successor edges to EndMBB.
16343   EndMBB->splice(EndMBB->begin(), MBB,
16344                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16345   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16346
16347   // The original block will now fall through to the XMM save block.
16348   MBB->addSuccessor(XMMSaveMBB);
16349   // The XMMSaveMBB will fall through to the end block.
16350   XMMSaveMBB->addSuccessor(EndMBB);
16351
16352   // Now add the instructions.
16353   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16354   DebugLoc DL = MI->getDebugLoc();
16355
16356   unsigned CountReg = MI->getOperand(0).getReg();
16357   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16358   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16359
16360   if (!Subtarget->isTargetWin64()) {
16361     // If %al is 0, branch around the XMM save block.
16362     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16363     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16364     MBB->addSuccessor(EndMBB);
16365   }
16366
16367   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16368   // that was just emitted, but clearly shouldn't be "saved".
16369   assert((MI->getNumOperands() <= 3 ||
16370           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16371           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16372          && "Expected last argument to be EFLAGS");
16373   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16374   // In the XMM save block, save all the XMM argument registers.
16375   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16376     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16377     MachineMemOperand *MMO =
16378       F->getMachineMemOperand(
16379           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16380         MachineMemOperand::MOStore,
16381         /*Size=*/16, /*Align=*/16);
16382     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16383       .addFrameIndex(RegSaveFrameIndex)
16384       .addImm(/*Scale=*/1)
16385       .addReg(/*IndexReg=*/0)
16386       .addImm(/*Disp=*/Offset)
16387       .addReg(/*Segment=*/0)
16388       .addReg(MI->getOperand(i).getReg())
16389       .addMemOperand(MMO);
16390   }
16391
16392   MI->eraseFromParent();   // The pseudo instruction is gone now.
16393
16394   return EndMBB;
16395 }
16396
16397 // The EFLAGS operand of SelectItr might be missing a kill marker
16398 // because there were multiple uses of EFLAGS, and ISel didn't know
16399 // which to mark. Figure out whether SelectItr should have had a
16400 // kill marker, and set it if it should. Returns the correct kill
16401 // marker value.
16402 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16403                                      MachineBasicBlock* BB,
16404                                      const TargetRegisterInfo* TRI) {
16405   // Scan forward through BB for a use/def of EFLAGS.
16406   MachineBasicBlock::iterator miI(std::next(SelectItr));
16407   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16408     const MachineInstr& mi = *miI;
16409     if (mi.readsRegister(X86::EFLAGS))
16410       return false;
16411     if (mi.definesRegister(X86::EFLAGS))
16412       break; // Should have kill-flag - update below.
16413   }
16414
16415   // If we hit the end of the block, check whether EFLAGS is live into a
16416   // successor.
16417   if (miI == BB->end()) {
16418     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16419                                           sEnd = BB->succ_end();
16420          sItr != sEnd; ++sItr) {
16421       MachineBasicBlock* succ = *sItr;
16422       if (succ->isLiveIn(X86::EFLAGS))
16423         return false;
16424     }
16425   }
16426
16427   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16428   // out. SelectMI should have a kill flag on EFLAGS.
16429   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16430   return true;
16431 }
16432
16433 MachineBasicBlock *
16434 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16435                                      MachineBasicBlock *BB) const {
16436   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16437   DebugLoc DL = MI->getDebugLoc();
16438
16439   // To "insert" a SELECT_CC instruction, we actually have to insert the
16440   // diamond control-flow pattern.  The incoming instruction knows the
16441   // destination vreg to set, the condition code register to branch on, the
16442   // true/false values to select between, and a branch opcode to use.
16443   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16444   MachineFunction::iterator It = BB;
16445   ++It;
16446
16447   //  thisMBB:
16448   //  ...
16449   //   TrueVal = ...
16450   //   cmpTY ccX, r1, r2
16451   //   bCC copy1MBB
16452   //   fallthrough --> copy0MBB
16453   MachineBasicBlock *thisMBB = BB;
16454   MachineFunction *F = BB->getParent();
16455   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16456   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16457   F->insert(It, copy0MBB);
16458   F->insert(It, sinkMBB);
16459
16460   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16461   // live into the sink and copy blocks.
16462   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16463   if (!MI->killsRegister(X86::EFLAGS) &&
16464       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16465     copy0MBB->addLiveIn(X86::EFLAGS);
16466     sinkMBB->addLiveIn(X86::EFLAGS);
16467   }
16468
16469   // Transfer the remainder of BB and its successor edges to sinkMBB.
16470   sinkMBB->splice(sinkMBB->begin(), BB,
16471                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16472   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16473
16474   // Add the true and fallthrough blocks as its successors.
16475   BB->addSuccessor(copy0MBB);
16476   BB->addSuccessor(sinkMBB);
16477
16478   // Create the conditional branch instruction.
16479   unsigned Opc =
16480     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16481   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16482
16483   //  copy0MBB:
16484   //   %FalseValue = ...
16485   //   # fallthrough to sinkMBB
16486   copy0MBB->addSuccessor(sinkMBB);
16487
16488   //  sinkMBB:
16489   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16490   //  ...
16491   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16492           TII->get(X86::PHI), MI->getOperand(0).getReg())
16493     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16494     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16495
16496   MI->eraseFromParent();   // The pseudo instruction is gone now.
16497   return sinkMBB;
16498 }
16499
16500 MachineBasicBlock *
16501 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16502                                         bool Is64Bit) const {
16503   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16504   DebugLoc DL = MI->getDebugLoc();
16505   MachineFunction *MF = BB->getParent();
16506   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16507
16508   assert(MF->shouldSplitStack());
16509
16510   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16511   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16512
16513   // BB:
16514   //  ... [Till the alloca]
16515   // If stacklet is not large enough, jump to mallocMBB
16516   //
16517   // bumpMBB:
16518   //  Allocate by subtracting from RSP
16519   //  Jump to continueMBB
16520   //
16521   // mallocMBB:
16522   //  Allocate by call to runtime
16523   //
16524   // continueMBB:
16525   //  ...
16526   //  [rest of original BB]
16527   //
16528
16529   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16530   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16531   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16532
16533   MachineRegisterInfo &MRI = MF->getRegInfo();
16534   const TargetRegisterClass *AddrRegClass =
16535     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16536
16537   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16538     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16539     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16540     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16541     sizeVReg = MI->getOperand(1).getReg(),
16542     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16543
16544   MachineFunction::iterator MBBIter = BB;
16545   ++MBBIter;
16546
16547   MF->insert(MBBIter, bumpMBB);
16548   MF->insert(MBBIter, mallocMBB);
16549   MF->insert(MBBIter, continueMBB);
16550
16551   continueMBB->splice(continueMBB->begin(), BB,
16552                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16553   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16554
16555   // Add code to the main basic block to check if the stack limit has been hit,
16556   // and if so, jump to mallocMBB otherwise to bumpMBB.
16557   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16558   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16559     .addReg(tmpSPVReg).addReg(sizeVReg);
16560   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16561     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16562     .addReg(SPLimitVReg);
16563   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16564
16565   // bumpMBB simply decreases the stack pointer, since we know the current
16566   // stacklet has enough space.
16567   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16568     .addReg(SPLimitVReg);
16569   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16570     .addReg(SPLimitVReg);
16571   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16572
16573   // Calls into a routine in libgcc to allocate more space from the heap.
16574   const uint32_t *RegMask =
16575     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16576   if (Is64Bit) {
16577     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16578       .addReg(sizeVReg);
16579     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16580       .addExternalSymbol("__morestack_allocate_stack_space")
16581       .addRegMask(RegMask)
16582       .addReg(X86::RDI, RegState::Implicit)
16583       .addReg(X86::RAX, RegState::ImplicitDefine);
16584   } else {
16585     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16586       .addImm(12);
16587     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16588     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16589       .addExternalSymbol("__morestack_allocate_stack_space")
16590       .addRegMask(RegMask)
16591       .addReg(X86::EAX, RegState::ImplicitDefine);
16592   }
16593
16594   if (!Is64Bit)
16595     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16596       .addImm(16);
16597
16598   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16599     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16600   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16601
16602   // Set up the CFG correctly.
16603   BB->addSuccessor(bumpMBB);
16604   BB->addSuccessor(mallocMBB);
16605   mallocMBB->addSuccessor(continueMBB);
16606   bumpMBB->addSuccessor(continueMBB);
16607
16608   // Take care of the PHI nodes.
16609   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16610           MI->getOperand(0).getReg())
16611     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16612     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16613
16614   // Delete the original pseudo instruction.
16615   MI->eraseFromParent();
16616
16617   // And we're done.
16618   return continueMBB;
16619 }
16620
16621 MachineBasicBlock *
16622 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16623                                           MachineBasicBlock *BB) const {
16624   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16625   DebugLoc DL = MI->getDebugLoc();
16626
16627   assert(!Subtarget->isTargetMacho());
16628
16629   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16630   // non-trivial part is impdef of ESP.
16631
16632   if (Subtarget->isTargetWin64()) {
16633     if (Subtarget->isTargetCygMing()) {
16634       // ___chkstk(Mingw64):
16635       // Clobbers R10, R11, RAX and EFLAGS.
16636       // Updates RSP.
16637       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16638         .addExternalSymbol("___chkstk")
16639         .addReg(X86::RAX, RegState::Implicit)
16640         .addReg(X86::RSP, RegState::Implicit)
16641         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16642         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16643         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16644     } else {
16645       // __chkstk(MSVCRT): does not update stack pointer.
16646       // Clobbers R10, R11 and EFLAGS.
16647       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16648         .addExternalSymbol("__chkstk")
16649         .addReg(X86::RAX, RegState::Implicit)
16650         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16651       // RAX has the offset to be subtracted from RSP.
16652       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16653         .addReg(X86::RSP)
16654         .addReg(X86::RAX);
16655     }
16656   } else {
16657     const char *StackProbeSymbol =
16658       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16659
16660     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16661       .addExternalSymbol(StackProbeSymbol)
16662       .addReg(X86::EAX, RegState::Implicit)
16663       .addReg(X86::ESP, RegState::Implicit)
16664       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16665       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16666       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16667   }
16668
16669   MI->eraseFromParent();   // The pseudo instruction is gone now.
16670   return BB;
16671 }
16672
16673 MachineBasicBlock *
16674 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16675                                       MachineBasicBlock *BB) const {
16676   // This is pretty easy.  We're taking the value that we received from
16677   // our load from the relocation, sticking it in either RDI (x86-64)
16678   // or EAX and doing an indirect call.  The return value will then
16679   // be in the normal return register.
16680   const X86InstrInfo *TII
16681     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16682   DebugLoc DL = MI->getDebugLoc();
16683   MachineFunction *F = BB->getParent();
16684
16685   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16686   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16687
16688   // Get a register mask for the lowered call.
16689   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16690   // proper register mask.
16691   const uint32_t *RegMask =
16692     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16693   if (Subtarget->is64Bit()) {
16694     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16695                                       TII->get(X86::MOV64rm), X86::RDI)
16696     .addReg(X86::RIP)
16697     .addImm(0).addReg(0)
16698     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16699                       MI->getOperand(3).getTargetFlags())
16700     .addReg(0);
16701     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16702     addDirectMem(MIB, X86::RDI);
16703     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16704   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16705     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16706                                       TII->get(X86::MOV32rm), X86::EAX)
16707     .addReg(0)
16708     .addImm(0).addReg(0)
16709     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16710                       MI->getOperand(3).getTargetFlags())
16711     .addReg(0);
16712     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16713     addDirectMem(MIB, X86::EAX);
16714     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16715   } else {
16716     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16717                                       TII->get(X86::MOV32rm), X86::EAX)
16718     .addReg(TII->getGlobalBaseReg(F))
16719     .addImm(0).addReg(0)
16720     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16721                       MI->getOperand(3).getTargetFlags())
16722     .addReg(0);
16723     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16724     addDirectMem(MIB, X86::EAX);
16725     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16726   }
16727
16728   MI->eraseFromParent(); // The pseudo instruction is gone now.
16729   return BB;
16730 }
16731
16732 MachineBasicBlock *
16733 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16734                                     MachineBasicBlock *MBB) const {
16735   DebugLoc DL = MI->getDebugLoc();
16736   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16737
16738   MachineFunction *MF = MBB->getParent();
16739   MachineRegisterInfo &MRI = MF->getRegInfo();
16740
16741   const BasicBlock *BB = MBB->getBasicBlock();
16742   MachineFunction::iterator I = MBB;
16743   ++I;
16744
16745   // Memory Reference
16746   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16747   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16748
16749   unsigned DstReg;
16750   unsigned MemOpndSlot = 0;
16751
16752   unsigned CurOp = 0;
16753
16754   DstReg = MI->getOperand(CurOp++).getReg();
16755   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16756   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16757   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16758   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16759
16760   MemOpndSlot = CurOp;
16761
16762   MVT PVT = getPointerTy();
16763   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16764          "Invalid Pointer Size!");
16765
16766   // For v = setjmp(buf), we generate
16767   //
16768   // thisMBB:
16769   //  buf[LabelOffset] = restoreMBB
16770   //  SjLjSetup restoreMBB
16771   //
16772   // mainMBB:
16773   //  v_main = 0
16774   //
16775   // sinkMBB:
16776   //  v = phi(main, restore)
16777   //
16778   // restoreMBB:
16779   //  v_restore = 1
16780
16781   MachineBasicBlock *thisMBB = MBB;
16782   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16783   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16784   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16785   MF->insert(I, mainMBB);
16786   MF->insert(I, sinkMBB);
16787   MF->push_back(restoreMBB);
16788
16789   MachineInstrBuilder MIB;
16790
16791   // Transfer the remainder of BB and its successor edges to sinkMBB.
16792   sinkMBB->splice(sinkMBB->begin(), MBB,
16793                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16794   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16795
16796   // thisMBB:
16797   unsigned PtrStoreOpc = 0;
16798   unsigned LabelReg = 0;
16799   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16800   Reloc::Model RM = getTargetMachine().getRelocationModel();
16801   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16802                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16803
16804   // Prepare IP either in reg or imm.
16805   if (!UseImmLabel) {
16806     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16807     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16808     LabelReg = MRI.createVirtualRegister(PtrRC);
16809     if (Subtarget->is64Bit()) {
16810       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16811               .addReg(X86::RIP)
16812               .addImm(0)
16813               .addReg(0)
16814               .addMBB(restoreMBB)
16815               .addReg(0);
16816     } else {
16817       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16818       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16819               .addReg(XII->getGlobalBaseReg(MF))
16820               .addImm(0)
16821               .addReg(0)
16822               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16823               .addReg(0);
16824     }
16825   } else
16826     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16827   // Store IP
16828   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16829   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16830     if (i == X86::AddrDisp)
16831       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16832     else
16833       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16834   }
16835   if (!UseImmLabel)
16836     MIB.addReg(LabelReg);
16837   else
16838     MIB.addMBB(restoreMBB);
16839   MIB.setMemRefs(MMOBegin, MMOEnd);
16840   // Setup
16841   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16842           .addMBB(restoreMBB);
16843
16844   const X86RegisterInfo *RegInfo =
16845     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16846   MIB.addRegMask(RegInfo->getNoPreservedMask());
16847   thisMBB->addSuccessor(mainMBB);
16848   thisMBB->addSuccessor(restoreMBB);
16849
16850   // mainMBB:
16851   //  EAX = 0
16852   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16853   mainMBB->addSuccessor(sinkMBB);
16854
16855   // sinkMBB:
16856   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16857           TII->get(X86::PHI), DstReg)
16858     .addReg(mainDstReg).addMBB(mainMBB)
16859     .addReg(restoreDstReg).addMBB(restoreMBB);
16860
16861   // restoreMBB:
16862   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16863   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16864   restoreMBB->addSuccessor(sinkMBB);
16865
16866   MI->eraseFromParent();
16867   return sinkMBB;
16868 }
16869
16870 MachineBasicBlock *
16871 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16872                                      MachineBasicBlock *MBB) const {
16873   DebugLoc DL = MI->getDebugLoc();
16874   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16875
16876   MachineFunction *MF = MBB->getParent();
16877   MachineRegisterInfo &MRI = MF->getRegInfo();
16878
16879   // Memory Reference
16880   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16881   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16882
16883   MVT PVT = getPointerTy();
16884   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16885          "Invalid Pointer Size!");
16886
16887   const TargetRegisterClass *RC =
16888     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16889   unsigned Tmp = MRI.createVirtualRegister(RC);
16890   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16891   const X86RegisterInfo *RegInfo =
16892     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16893   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16894   unsigned SP = RegInfo->getStackRegister();
16895
16896   MachineInstrBuilder MIB;
16897
16898   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16899   const int64_t SPOffset = 2 * PVT.getStoreSize();
16900
16901   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16902   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16903
16904   // Reload FP
16905   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16906   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16907     MIB.addOperand(MI->getOperand(i));
16908   MIB.setMemRefs(MMOBegin, MMOEnd);
16909   // Reload IP
16910   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16911   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16912     if (i == X86::AddrDisp)
16913       MIB.addDisp(MI->getOperand(i), LabelOffset);
16914     else
16915       MIB.addOperand(MI->getOperand(i));
16916   }
16917   MIB.setMemRefs(MMOBegin, MMOEnd);
16918   // Reload SP
16919   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16920   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16921     if (i == X86::AddrDisp)
16922       MIB.addDisp(MI->getOperand(i), SPOffset);
16923     else
16924       MIB.addOperand(MI->getOperand(i));
16925   }
16926   MIB.setMemRefs(MMOBegin, MMOEnd);
16927   // Jump
16928   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16929
16930   MI->eraseFromParent();
16931   return MBB;
16932 }
16933
16934 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16935 // accumulator loops. Writing back to the accumulator allows the coalescer
16936 // to remove extra copies in the loop.   
16937 MachineBasicBlock *
16938 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16939                                  MachineBasicBlock *MBB) const {
16940   MachineOperand &AddendOp = MI->getOperand(3);
16941
16942   // Bail out early if the addend isn't a register - we can't switch these.
16943   if (!AddendOp.isReg())
16944     return MBB;
16945
16946   MachineFunction &MF = *MBB->getParent();
16947   MachineRegisterInfo &MRI = MF.getRegInfo();
16948
16949   // Check whether the addend is defined by a PHI:
16950   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16951   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16952   if (!AddendDef.isPHI())
16953     return MBB;
16954
16955   // Look for the following pattern:
16956   // loop:
16957   //   %addend = phi [%entry, 0], [%loop, %result]
16958   //   ...
16959   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16960
16961   // Replace with:
16962   //   loop:
16963   //   %addend = phi [%entry, 0], [%loop, %result]
16964   //   ...
16965   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16966
16967   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16968     assert(AddendDef.getOperand(i).isReg());
16969     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16970     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16971     if (&PHISrcInst == MI) {
16972       // Found a matching instruction.
16973       unsigned NewFMAOpc = 0;
16974       switch (MI->getOpcode()) {
16975         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16976         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16977         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16978         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16979         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16980         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16981         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16982         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16983         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16984         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16985         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16986         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16987         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16988         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16989         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16990         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16991         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16992         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16993         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16994         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16995         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16996         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16997         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16998         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16999         default: llvm_unreachable("Unrecognized FMA variant.");
17000       }
17001
17002       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17003       MachineInstrBuilder MIB =
17004         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17005         .addOperand(MI->getOperand(0))
17006         .addOperand(MI->getOperand(3))
17007         .addOperand(MI->getOperand(2))
17008         .addOperand(MI->getOperand(1));
17009       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17010       MI->eraseFromParent();
17011     }
17012   }
17013
17014   return MBB;
17015 }
17016
17017 MachineBasicBlock *
17018 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17019                                                MachineBasicBlock *BB) const {
17020   switch (MI->getOpcode()) {
17021   default: llvm_unreachable("Unexpected instr type to insert");
17022   case X86::TAILJMPd64:
17023   case X86::TAILJMPr64:
17024   case X86::TAILJMPm64:
17025     llvm_unreachable("TAILJMP64 would not be touched here.");
17026   case X86::TCRETURNdi64:
17027   case X86::TCRETURNri64:
17028   case X86::TCRETURNmi64:
17029     return BB;
17030   case X86::WIN_ALLOCA:
17031     return EmitLoweredWinAlloca(MI, BB);
17032   case X86::SEG_ALLOCA_32:
17033     return EmitLoweredSegAlloca(MI, BB, false);
17034   case X86::SEG_ALLOCA_64:
17035     return EmitLoweredSegAlloca(MI, BB, true);
17036   case X86::TLSCall_32:
17037   case X86::TLSCall_64:
17038     return EmitLoweredTLSCall(MI, BB);
17039   case X86::CMOV_GR8:
17040   case X86::CMOV_FR32:
17041   case X86::CMOV_FR64:
17042   case X86::CMOV_V4F32:
17043   case X86::CMOV_V2F64:
17044   case X86::CMOV_V2I64:
17045   case X86::CMOV_V8F32:
17046   case X86::CMOV_V4F64:
17047   case X86::CMOV_V4I64:
17048   case X86::CMOV_V16F32:
17049   case X86::CMOV_V8F64:
17050   case X86::CMOV_V8I64:
17051   case X86::CMOV_GR16:
17052   case X86::CMOV_GR32:
17053   case X86::CMOV_RFP32:
17054   case X86::CMOV_RFP64:
17055   case X86::CMOV_RFP80:
17056     return EmitLoweredSelect(MI, BB);
17057
17058   case X86::FP32_TO_INT16_IN_MEM:
17059   case X86::FP32_TO_INT32_IN_MEM:
17060   case X86::FP32_TO_INT64_IN_MEM:
17061   case X86::FP64_TO_INT16_IN_MEM:
17062   case X86::FP64_TO_INT32_IN_MEM:
17063   case X86::FP64_TO_INT64_IN_MEM:
17064   case X86::FP80_TO_INT16_IN_MEM:
17065   case X86::FP80_TO_INT32_IN_MEM:
17066   case X86::FP80_TO_INT64_IN_MEM: {
17067     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17068     DebugLoc DL = MI->getDebugLoc();
17069
17070     // Change the floating point control register to use "round towards zero"
17071     // mode when truncating to an integer value.
17072     MachineFunction *F = BB->getParent();
17073     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17074     addFrameReference(BuildMI(*BB, MI, DL,
17075                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17076
17077     // Load the old value of the high byte of the control word...
17078     unsigned OldCW =
17079       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17080     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17081                       CWFrameIdx);
17082
17083     // Set the high part to be round to zero...
17084     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17085       .addImm(0xC7F);
17086
17087     // Reload the modified control word now...
17088     addFrameReference(BuildMI(*BB, MI, DL,
17089                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17090
17091     // Restore the memory image of control word to original value
17092     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17093       .addReg(OldCW);
17094
17095     // Get the X86 opcode to use.
17096     unsigned Opc;
17097     switch (MI->getOpcode()) {
17098     default: llvm_unreachable("illegal opcode!");
17099     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17100     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17101     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17102     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17103     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17104     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17105     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17106     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17107     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17108     }
17109
17110     X86AddressMode AM;
17111     MachineOperand &Op = MI->getOperand(0);
17112     if (Op.isReg()) {
17113       AM.BaseType = X86AddressMode::RegBase;
17114       AM.Base.Reg = Op.getReg();
17115     } else {
17116       AM.BaseType = X86AddressMode::FrameIndexBase;
17117       AM.Base.FrameIndex = Op.getIndex();
17118     }
17119     Op = MI->getOperand(1);
17120     if (Op.isImm())
17121       AM.Scale = Op.getImm();
17122     Op = MI->getOperand(2);
17123     if (Op.isImm())
17124       AM.IndexReg = Op.getImm();
17125     Op = MI->getOperand(3);
17126     if (Op.isGlobal()) {
17127       AM.GV = Op.getGlobal();
17128     } else {
17129       AM.Disp = Op.getImm();
17130     }
17131     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17132                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17133
17134     // Reload the original control word now.
17135     addFrameReference(BuildMI(*BB, MI, DL,
17136                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17137
17138     MI->eraseFromParent();   // The pseudo instruction is gone now.
17139     return BB;
17140   }
17141     // String/text processing lowering.
17142   case X86::PCMPISTRM128REG:
17143   case X86::VPCMPISTRM128REG:
17144   case X86::PCMPISTRM128MEM:
17145   case X86::VPCMPISTRM128MEM:
17146   case X86::PCMPESTRM128REG:
17147   case X86::VPCMPESTRM128REG:
17148   case X86::PCMPESTRM128MEM:
17149   case X86::VPCMPESTRM128MEM:
17150     assert(Subtarget->hasSSE42() &&
17151            "Target must have SSE4.2 or AVX features enabled");
17152     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17153
17154   // String/text processing lowering.
17155   case X86::PCMPISTRIREG:
17156   case X86::VPCMPISTRIREG:
17157   case X86::PCMPISTRIMEM:
17158   case X86::VPCMPISTRIMEM:
17159   case X86::PCMPESTRIREG:
17160   case X86::VPCMPESTRIREG:
17161   case X86::PCMPESTRIMEM:
17162   case X86::VPCMPESTRIMEM:
17163     assert(Subtarget->hasSSE42() &&
17164            "Target must have SSE4.2 or AVX features enabled");
17165     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17166
17167   // Thread synchronization.
17168   case X86::MONITOR:
17169     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17170
17171   // xbegin
17172   case X86::XBEGIN:
17173     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17174
17175   // Atomic Lowering.
17176   case X86::ATOMAND8:
17177   case X86::ATOMAND16:
17178   case X86::ATOMAND32:
17179   case X86::ATOMAND64:
17180     // Fall through
17181   case X86::ATOMOR8:
17182   case X86::ATOMOR16:
17183   case X86::ATOMOR32:
17184   case X86::ATOMOR64:
17185     // Fall through
17186   case X86::ATOMXOR16:
17187   case X86::ATOMXOR8:
17188   case X86::ATOMXOR32:
17189   case X86::ATOMXOR64:
17190     // Fall through
17191   case X86::ATOMNAND8:
17192   case X86::ATOMNAND16:
17193   case X86::ATOMNAND32:
17194   case X86::ATOMNAND64:
17195     // Fall through
17196   case X86::ATOMMAX8:
17197   case X86::ATOMMAX16:
17198   case X86::ATOMMAX32:
17199   case X86::ATOMMAX64:
17200     // Fall through
17201   case X86::ATOMMIN8:
17202   case X86::ATOMMIN16:
17203   case X86::ATOMMIN32:
17204   case X86::ATOMMIN64:
17205     // Fall through
17206   case X86::ATOMUMAX8:
17207   case X86::ATOMUMAX16:
17208   case X86::ATOMUMAX32:
17209   case X86::ATOMUMAX64:
17210     // Fall through
17211   case X86::ATOMUMIN8:
17212   case X86::ATOMUMIN16:
17213   case X86::ATOMUMIN32:
17214   case X86::ATOMUMIN64:
17215     return EmitAtomicLoadArith(MI, BB);
17216
17217   // This group does 64-bit operations on a 32-bit host.
17218   case X86::ATOMAND6432:
17219   case X86::ATOMOR6432:
17220   case X86::ATOMXOR6432:
17221   case X86::ATOMNAND6432:
17222   case X86::ATOMADD6432:
17223   case X86::ATOMSUB6432:
17224   case X86::ATOMMAX6432:
17225   case X86::ATOMMIN6432:
17226   case X86::ATOMUMAX6432:
17227   case X86::ATOMUMIN6432:
17228   case X86::ATOMSWAP6432:
17229     return EmitAtomicLoadArith6432(MI, BB);
17230
17231   case X86::VASTART_SAVE_XMM_REGS:
17232     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17233
17234   case X86::VAARG_64:
17235     return EmitVAARG64WithCustomInserter(MI, BB);
17236
17237   case X86::EH_SjLj_SetJmp32:
17238   case X86::EH_SjLj_SetJmp64:
17239     return emitEHSjLjSetJmp(MI, BB);
17240
17241   case X86::EH_SjLj_LongJmp32:
17242   case X86::EH_SjLj_LongJmp64:
17243     return emitEHSjLjLongJmp(MI, BB);
17244
17245   case TargetOpcode::STACKMAP:
17246   case TargetOpcode::PATCHPOINT:
17247     return emitPatchPoint(MI, BB);
17248
17249   case X86::VFMADDPDr213r:
17250   case X86::VFMADDPSr213r:
17251   case X86::VFMADDSDr213r:
17252   case X86::VFMADDSSr213r:
17253   case X86::VFMSUBPDr213r:
17254   case X86::VFMSUBPSr213r:
17255   case X86::VFMSUBSDr213r:
17256   case X86::VFMSUBSSr213r:
17257   case X86::VFNMADDPDr213r:
17258   case X86::VFNMADDPSr213r:
17259   case X86::VFNMADDSDr213r:
17260   case X86::VFNMADDSSr213r:
17261   case X86::VFNMSUBPDr213r:
17262   case X86::VFNMSUBPSr213r:
17263   case X86::VFNMSUBSDr213r:
17264   case X86::VFNMSUBSSr213r:
17265   case X86::VFMADDPDr213rY:
17266   case X86::VFMADDPSr213rY:
17267   case X86::VFMSUBPDr213rY:
17268   case X86::VFMSUBPSr213rY:
17269   case X86::VFNMADDPDr213rY:
17270   case X86::VFNMADDPSr213rY:
17271   case X86::VFNMSUBPDr213rY:
17272   case X86::VFNMSUBPSr213rY:
17273     return emitFMA3Instr(MI, BB);
17274   }
17275 }
17276
17277 //===----------------------------------------------------------------------===//
17278 //                           X86 Optimization Hooks
17279 //===----------------------------------------------------------------------===//
17280
17281 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17282                                                       APInt &KnownZero,
17283                                                       APInt &KnownOne,
17284                                                       const SelectionDAG &DAG,
17285                                                       unsigned Depth) const {
17286   unsigned BitWidth = KnownZero.getBitWidth();
17287   unsigned Opc = Op.getOpcode();
17288   assert((Opc >= ISD::BUILTIN_OP_END ||
17289           Opc == ISD::INTRINSIC_WO_CHAIN ||
17290           Opc == ISD::INTRINSIC_W_CHAIN ||
17291           Opc == ISD::INTRINSIC_VOID) &&
17292          "Should use MaskedValueIsZero if you don't know whether Op"
17293          " is a target node!");
17294
17295   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17296   switch (Opc) {
17297   default: break;
17298   case X86ISD::ADD:
17299   case X86ISD::SUB:
17300   case X86ISD::ADC:
17301   case X86ISD::SBB:
17302   case X86ISD::SMUL:
17303   case X86ISD::UMUL:
17304   case X86ISD::INC:
17305   case X86ISD::DEC:
17306   case X86ISD::OR:
17307   case X86ISD::XOR:
17308   case X86ISD::AND:
17309     // These nodes' second result is a boolean.
17310     if (Op.getResNo() == 0)
17311       break;
17312     // Fallthrough
17313   case X86ISD::SETCC:
17314     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17315     break;
17316   case ISD::INTRINSIC_WO_CHAIN: {
17317     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17318     unsigned NumLoBits = 0;
17319     switch (IntId) {
17320     default: break;
17321     case Intrinsic::x86_sse_movmsk_ps:
17322     case Intrinsic::x86_avx_movmsk_ps_256:
17323     case Intrinsic::x86_sse2_movmsk_pd:
17324     case Intrinsic::x86_avx_movmsk_pd_256:
17325     case Intrinsic::x86_mmx_pmovmskb:
17326     case Intrinsic::x86_sse2_pmovmskb_128:
17327     case Intrinsic::x86_avx2_pmovmskb: {
17328       // High bits of movmskp{s|d}, pmovmskb are known zero.
17329       switch (IntId) {
17330         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17331         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17332         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17333         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17334         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17335         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17336         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17337         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17338       }
17339       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17340       break;
17341     }
17342     }
17343     break;
17344   }
17345   }
17346 }
17347
17348 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17349   SDValue Op,
17350   const SelectionDAG &,
17351   unsigned Depth) const {
17352   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17353   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17354     return Op.getValueType().getScalarType().getSizeInBits();
17355
17356   // Fallback case.
17357   return 1;
17358 }
17359
17360 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17361 /// node is a GlobalAddress + offset.
17362 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17363                                        const GlobalValue* &GA,
17364                                        int64_t &Offset) const {
17365   if (N->getOpcode() == X86ISD::Wrapper) {
17366     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17367       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17368       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17369       return true;
17370     }
17371   }
17372   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17373 }
17374
17375 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17376 /// same as extracting the high 128-bit part of 256-bit vector and then
17377 /// inserting the result into the low part of a new 256-bit vector
17378 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17379   EVT VT = SVOp->getValueType(0);
17380   unsigned NumElems = VT.getVectorNumElements();
17381
17382   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17383   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17384     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17385         SVOp->getMaskElt(j) >= 0)
17386       return false;
17387
17388   return true;
17389 }
17390
17391 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17392 /// same as extracting the low 128-bit part of 256-bit vector and then
17393 /// inserting the result into the high part of a new 256-bit vector
17394 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17395   EVT VT = SVOp->getValueType(0);
17396   unsigned NumElems = VT.getVectorNumElements();
17397
17398   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17399   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17400     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17401         SVOp->getMaskElt(j) >= 0)
17402       return false;
17403
17404   return true;
17405 }
17406
17407 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17408 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17409                                         TargetLowering::DAGCombinerInfo &DCI,
17410                                         const X86Subtarget* Subtarget) {
17411   SDLoc dl(N);
17412   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17413   SDValue V1 = SVOp->getOperand(0);
17414   SDValue V2 = SVOp->getOperand(1);
17415   EVT VT = SVOp->getValueType(0);
17416   unsigned NumElems = VT.getVectorNumElements();
17417
17418   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17419       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17420     //
17421     //                   0,0,0,...
17422     //                      |
17423     //    V      UNDEF    BUILD_VECTOR    UNDEF
17424     //     \      /           \           /
17425     //  CONCAT_VECTOR         CONCAT_VECTOR
17426     //         \                  /
17427     //          \                /
17428     //          RESULT: V + zero extended
17429     //
17430     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17431         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17432         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17433       return SDValue();
17434
17435     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17436       return SDValue();
17437
17438     // To match the shuffle mask, the first half of the mask should
17439     // be exactly the first vector, and all the rest a splat with the
17440     // first element of the second one.
17441     for (unsigned i = 0; i != NumElems/2; ++i)
17442       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17443           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17444         return SDValue();
17445
17446     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17447     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17448       if (Ld->hasNUsesOfValue(1, 0)) {
17449         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17450         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17451         SDValue ResNode =
17452           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17453                                   Ld->getMemoryVT(),
17454                                   Ld->getPointerInfo(),
17455                                   Ld->getAlignment(),
17456                                   false/*isVolatile*/, true/*ReadMem*/,
17457                                   false/*WriteMem*/);
17458
17459         // Make sure the newly-created LOAD is in the same position as Ld in
17460         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17461         // and update uses of Ld's output chain to use the TokenFactor.
17462         if (Ld->hasAnyUseOfValue(1)) {
17463           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17464                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17465           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17466           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17467                                  SDValue(ResNode.getNode(), 1));
17468         }
17469
17470         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17471       }
17472     }
17473
17474     // Emit a zeroed vector and insert the desired subvector on its
17475     // first half.
17476     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17477     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17478     return DCI.CombineTo(N, InsV);
17479   }
17480
17481   //===--------------------------------------------------------------------===//
17482   // Combine some shuffles into subvector extracts and inserts:
17483   //
17484
17485   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17486   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17487     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17488     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17489     return DCI.CombineTo(N, InsV);
17490   }
17491
17492   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17493   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17494     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17495     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17496     return DCI.CombineTo(N, InsV);
17497   }
17498
17499   return SDValue();
17500 }
17501
17502 /// PerformShuffleCombine - Performs several different shuffle combines.
17503 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17504                                      TargetLowering::DAGCombinerInfo &DCI,
17505                                      const X86Subtarget *Subtarget) {
17506   SDLoc dl(N);
17507   SDValue N0 = N->getOperand(0);
17508   SDValue N1 = N->getOperand(1);
17509   EVT VT = N->getValueType(0);
17510
17511   // Don't create instructions with illegal types after legalize types has run.
17512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17513   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17514     return SDValue();
17515
17516   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17517   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17518       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17519     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17520
17521   // During Type Legalization, when promoting illegal vector types,
17522   // the backend might introduce new shuffle dag nodes and bitcasts.
17523   //
17524   // This code performs the following transformation:
17525   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17526   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17527   //
17528   // We do this only if both the bitcast and the BINOP dag nodes have
17529   // one use. Also, perform this transformation only if the new binary
17530   // operation is legal. This is to avoid introducing dag nodes that
17531   // potentially need to be further expanded (or custom lowered) into a
17532   // less optimal sequence of dag nodes.
17533   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17534       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17535       N0.getOpcode() == ISD::BITCAST) {
17536     SDValue BC0 = N0.getOperand(0);
17537     EVT SVT = BC0.getValueType();
17538     unsigned Opcode = BC0.getOpcode();
17539     unsigned NumElts = VT.getVectorNumElements();
17540     
17541     if (BC0.hasOneUse() && SVT.isVector() &&
17542         SVT.getVectorNumElements() * 2 == NumElts &&
17543         TLI.isOperationLegal(Opcode, VT)) {
17544       bool CanFold = false;
17545       switch (Opcode) {
17546       default : break;
17547       case ISD::ADD :
17548       case ISD::FADD :
17549       case ISD::SUB :
17550       case ISD::FSUB :
17551       case ISD::MUL :
17552       case ISD::FMUL :
17553         CanFold = true;
17554       }
17555
17556       unsigned SVTNumElts = SVT.getVectorNumElements();
17557       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17558       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17559         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17560       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17561         CanFold = SVOp->getMaskElt(i) < 0;
17562
17563       if (CanFold) {
17564         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17565         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17566         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17567         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17568       }
17569     }
17570   }
17571
17572   // Only handle 128 wide vector from here on.
17573   if (!VT.is128BitVector())
17574     return SDValue();
17575
17576   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17577   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17578   // consecutive, non-overlapping, and in the right order.
17579   SmallVector<SDValue, 16> Elts;
17580   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17581     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17582
17583   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17584 }
17585
17586 /// PerformTruncateCombine - Converts truncate operation to
17587 /// a sequence of vector shuffle operations.
17588 /// It is possible when we truncate 256-bit vector to 128-bit vector
17589 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17590                                       TargetLowering::DAGCombinerInfo &DCI,
17591                                       const X86Subtarget *Subtarget)  {
17592   return SDValue();
17593 }
17594
17595 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17596 /// specific shuffle of a load can be folded into a single element load.
17597 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17598 /// shuffles have been customed lowered so we need to handle those here.
17599 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17600                                          TargetLowering::DAGCombinerInfo &DCI) {
17601   if (DCI.isBeforeLegalizeOps())
17602     return SDValue();
17603
17604   SDValue InVec = N->getOperand(0);
17605   SDValue EltNo = N->getOperand(1);
17606
17607   if (!isa<ConstantSDNode>(EltNo))
17608     return SDValue();
17609
17610   EVT VT = InVec.getValueType();
17611
17612   bool HasShuffleIntoBitcast = false;
17613   if (InVec.getOpcode() == ISD::BITCAST) {
17614     // Don't duplicate a load with other uses.
17615     if (!InVec.hasOneUse())
17616       return SDValue();
17617     EVT BCVT = InVec.getOperand(0).getValueType();
17618     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17619       return SDValue();
17620     InVec = InVec.getOperand(0);
17621     HasShuffleIntoBitcast = true;
17622   }
17623
17624   if (!isTargetShuffle(InVec.getOpcode()))
17625     return SDValue();
17626
17627   // Don't duplicate a load with other uses.
17628   if (!InVec.hasOneUse())
17629     return SDValue();
17630
17631   SmallVector<int, 16> ShuffleMask;
17632   bool UnaryShuffle;
17633   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17634                             UnaryShuffle))
17635     return SDValue();
17636
17637   // Select the input vector, guarding against out of range extract vector.
17638   unsigned NumElems = VT.getVectorNumElements();
17639   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17640   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17641   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17642                                          : InVec.getOperand(1);
17643
17644   // If inputs to shuffle are the same for both ops, then allow 2 uses
17645   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17646
17647   if (LdNode.getOpcode() == ISD::BITCAST) {
17648     // Don't duplicate a load with other uses.
17649     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17650       return SDValue();
17651
17652     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17653     LdNode = LdNode.getOperand(0);
17654   }
17655
17656   if (!ISD::isNormalLoad(LdNode.getNode()))
17657     return SDValue();
17658
17659   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17660
17661   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17662     return SDValue();
17663
17664   if (HasShuffleIntoBitcast) {
17665     // If there's a bitcast before the shuffle, check if the load type and
17666     // alignment is valid.
17667     unsigned Align = LN0->getAlignment();
17668     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17669     unsigned NewAlign = TLI.getDataLayout()->
17670       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17671
17672     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17673       return SDValue();
17674   }
17675
17676   // All checks match so transform back to vector_shuffle so that DAG combiner
17677   // can finish the job
17678   SDLoc dl(N);
17679
17680   // Create shuffle node taking into account the case that its a unary shuffle
17681   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17682   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17683                                  InVec.getOperand(0), Shuffle,
17684                                  &ShuffleMask[0]);
17685   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17686   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17687                      EltNo);
17688 }
17689
17690 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17691 /// generation and convert it from being a bunch of shuffles and extracts
17692 /// to a simple store and scalar loads to extract the elements.
17693 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17694                                          TargetLowering::DAGCombinerInfo &DCI) {
17695   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17696   if (NewOp.getNode())
17697     return NewOp;
17698
17699   SDValue InputVector = N->getOperand(0);
17700
17701   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17702   // from mmx to v2i32 has a single usage.
17703   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17704       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17705       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17706     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17707                        N->getValueType(0),
17708                        InputVector.getNode()->getOperand(0));
17709
17710   // Only operate on vectors of 4 elements, where the alternative shuffling
17711   // gets to be more expensive.
17712   if (InputVector.getValueType() != MVT::v4i32)
17713     return SDValue();
17714
17715   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17716   // single use which is a sign-extend or zero-extend, and all elements are
17717   // used.
17718   SmallVector<SDNode *, 4> Uses;
17719   unsigned ExtractedElements = 0;
17720   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17721        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17722     if (UI.getUse().getResNo() != InputVector.getResNo())
17723       return SDValue();
17724
17725     SDNode *Extract = *UI;
17726     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17727       return SDValue();
17728
17729     if (Extract->getValueType(0) != MVT::i32)
17730       return SDValue();
17731     if (!Extract->hasOneUse())
17732       return SDValue();
17733     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17734         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17735       return SDValue();
17736     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17737       return SDValue();
17738
17739     // Record which element was extracted.
17740     ExtractedElements |=
17741       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17742
17743     Uses.push_back(Extract);
17744   }
17745
17746   // If not all the elements were used, this may not be worthwhile.
17747   if (ExtractedElements != 15)
17748     return SDValue();
17749
17750   // Ok, we've now decided to do the transformation.
17751   SDLoc dl(InputVector);
17752
17753   // Store the value to a temporary stack slot.
17754   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17755   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17756                             MachinePointerInfo(), false, false, 0);
17757
17758   // Replace each use (extract) with a load of the appropriate element.
17759   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17760        UE = Uses.end(); UI != UE; ++UI) {
17761     SDNode *Extract = *UI;
17762
17763     // cOMpute the element's address.
17764     SDValue Idx = Extract->getOperand(1);
17765     unsigned EltSize =
17766         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17767     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17768     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17769     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17770
17771     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17772                                      StackPtr, OffsetVal);
17773
17774     // Load the scalar.
17775     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17776                                      ScalarAddr, MachinePointerInfo(),
17777                                      false, false, false, 0);
17778
17779     // Replace the exact with the load.
17780     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17781   }
17782
17783   // The replacement was made in place; don't return anything.
17784   return SDValue();
17785 }
17786
17787 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17788 static std::pair<unsigned, bool>
17789 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17790                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17791   if (!VT.isVector())
17792     return std::make_pair(0, false);
17793
17794   bool NeedSplit = false;
17795   switch (VT.getSimpleVT().SimpleTy) {
17796   default: return std::make_pair(0, false);
17797   case MVT::v32i8:
17798   case MVT::v16i16:
17799   case MVT::v8i32:
17800     if (!Subtarget->hasAVX2())
17801       NeedSplit = true;
17802     if (!Subtarget->hasAVX())
17803       return std::make_pair(0, false);
17804     break;
17805   case MVT::v16i8:
17806   case MVT::v8i16:
17807   case MVT::v4i32:
17808     if (!Subtarget->hasSSE2())
17809       return std::make_pair(0, false);
17810   }
17811
17812   // SSE2 has only a small subset of the operations.
17813   bool hasUnsigned = Subtarget->hasSSE41() ||
17814                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17815   bool hasSigned = Subtarget->hasSSE41() ||
17816                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17817
17818   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17819
17820   unsigned Opc = 0;
17821   // Check for x CC y ? x : y.
17822   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17823       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17824     switch (CC) {
17825     default: break;
17826     case ISD::SETULT:
17827     case ISD::SETULE:
17828       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17829     case ISD::SETUGT:
17830     case ISD::SETUGE:
17831       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17832     case ISD::SETLT:
17833     case ISD::SETLE:
17834       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17835     case ISD::SETGT:
17836     case ISD::SETGE:
17837       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17838     }
17839   // Check for x CC y ? y : x -- a min/max with reversed arms.
17840   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17841              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17842     switch (CC) {
17843     default: break;
17844     case ISD::SETULT:
17845     case ISD::SETULE:
17846       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17847     case ISD::SETUGT:
17848     case ISD::SETUGE:
17849       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17850     case ISD::SETLT:
17851     case ISD::SETLE:
17852       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17853     case ISD::SETGT:
17854     case ISD::SETGE:
17855       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17856     }
17857   }
17858
17859   return std::make_pair(Opc, NeedSplit);
17860 }
17861
17862 static SDValue
17863 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17864                                       const X86Subtarget *Subtarget) {
17865   SDLoc dl(N);
17866   SDValue Cond = N->getOperand(0);
17867   SDValue LHS = N->getOperand(1);
17868   SDValue RHS = N->getOperand(2);
17869
17870   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17871     SDValue CondSrc = Cond->getOperand(0);
17872     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17873       Cond = CondSrc->getOperand(0);
17874   }
17875
17876   MVT VT = N->getSimpleValueType(0);
17877   MVT EltVT = VT.getVectorElementType();
17878   unsigned NumElems = VT.getVectorNumElements();
17879   // There is no blend with immediate in AVX-512.
17880   if (VT.is512BitVector())
17881     return SDValue();
17882
17883   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
17884     return SDValue();
17885   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
17886     return SDValue();
17887
17888   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
17889     return SDValue();
17890
17891   unsigned MaskValue = 0;
17892   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
17893     return SDValue();
17894
17895   SmallVector<int, 8> ShuffleMask(NumElems, -1);
17896   for (unsigned i = 0; i < NumElems; ++i) {
17897     // Be sure we emit undef where we can.
17898     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
17899       ShuffleMask[i] = -1;
17900     else
17901       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
17902   }
17903
17904   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
17905 }
17906
17907 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17908 /// nodes.
17909 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17910                                     TargetLowering::DAGCombinerInfo &DCI,
17911                                     const X86Subtarget *Subtarget) {
17912   SDLoc DL(N);
17913   SDValue Cond = N->getOperand(0);
17914   // Get the LHS/RHS of the select.
17915   SDValue LHS = N->getOperand(1);
17916   SDValue RHS = N->getOperand(2);
17917   EVT VT = LHS.getValueType();
17918   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17919
17920   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17921   // instructions match the semantics of the common C idiom x<y?x:y but not
17922   // x<=y?x:y, because of how they handle negative zero (which can be
17923   // ignored in unsafe-math mode).
17924   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17925       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17926       (Subtarget->hasSSE2() ||
17927        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17928     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17929
17930     unsigned Opcode = 0;
17931     // Check for x CC y ? x : y.
17932     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17933         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17934       switch (CC) {
17935       default: break;
17936       case ISD::SETULT:
17937         // Converting this to a min would handle NaNs incorrectly, and swapping
17938         // the operands would cause it to handle comparisons between positive
17939         // and negative zero incorrectly.
17940         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17941           if (!DAG.getTarget().Options.UnsafeFPMath &&
17942               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17943             break;
17944           std::swap(LHS, RHS);
17945         }
17946         Opcode = X86ISD::FMIN;
17947         break;
17948       case ISD::SETOLE:
17949         // Converting this to a min would handle comparisons between positive
17950         // and negative zero incorrectly.
17951         if (!DAG.getTarget().Options.UnsafeFPMath &&
17952             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17953           break;
17954         Opcode = X86ISD::FMIN;
17955         break;
17956       case ISD::SETULE:
17957         // Converting this to a min would handle both negative zeros and NaNs
17958         // incorrectly, but we can swap the operands to fix both.
17959         std::swap(LHS, RHS);
17960       case ISD::SETOLT:
17961       case ISD::SETLT:
17962       case ISD::SETLE:
17963         Opcode = X86ISD::FMIN;
17964         break;
17965
17966       case ISD::SETOGE:
17967         // Converting this to a max would handle comparisons between positive
17968         // and negative zero incorrectly.
17969         if (!DAG.getTarget().Options.UnsafeFPMath &&
17970             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17971           break;
17972         Opcode = X86ISD::FMAX;
17973         break;
17974       case ISD::SETUGT:
17975         // Converting this to a max would handle NaNs incorrectly, and swapping
17976         // the operands would cause it to handle comparisons between positive
17977         // and negative zero incorrectly.
17978         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17979           if (!DAG.getTarget().Options.UnsafeFPMath &&
17980               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17981             break;
17982           std::swap(LHS, RHS);
17983         }
17984         Opcode = X86ISD::FMAX;
17985         break;
17986       case ISD::SETUGE:
17987         // Converting this to a max would handle both negative zeros and NaNs
17988         // incorrectly, but we can swap the operands to fix both.
17989         std::swap(LHS, RHS);
17990       case ISD::SETOGT:
17991       case ISD::SETGT:
17992       case ISD::SETGE:
17993         Opcode = X86ISD::FMAX;
17994         break;
17995       }
17996     // Check for x CC y ? y : x -- a min/max with reversed arms.
17997     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17998                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17999       switch (CC) {
18000       default: break;
18001       case ISD::SETOGE:
18002         // Converting this to a min would handle comparisons between positive
18003         // and negative zero incorrectly, and swapping the operands would
18004         // cause it to handle NaNs incorrectly.
18005         if (!DAG.getTarget().Options.UnsafeFPMath &&
18006             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18007           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18008             break;
18009           std::swap(LHS, RHS);
18010         }
18011         Opcode = X86ISD::FMIN;
18012         break;
18013       case ISD::SETUGT:
18014         // Converting this to a min would handle NaNs incorrectly.
18015         if (!DAG.getTarget().Options.UnsafeFPMath &&
18016             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18017           break;
18018         Opcode = X86ISD::FMIN;
18019         break;
18020       case ISD::SETUGE:
18021         // Converting this to a min would handle both negative zeros and NaNs
18022         // incorrectly, but we can swap the operands to fix both.
18023         std::swap(LHS, RHS);
18024       case ISD::SETOGT:
18025       case ISD::SETGT:
18026       case ISD::SETGE:
18027         Opcode = X86ISD::FMIN;
18028         break;
18029
18030       case ISD::SETULT:
18031         // Converting this to a max would handle NaNs incorrectly.
18032         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18033           break;
18034         Opcode = X86ISD::FMAX;
18035         break;
18036       case ISD::SETOLE:
18037         // Converting this to a max would handle comparisons between positive
18038         // and negative zero incorrectly, and swapping the operands would
18039         // cause it to handle NaNs incorrectly.
18040         if (!DAG.getTarget().Options.UnsafeFPMath &&
18041             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18042           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18043             break;
18044           std::swap(LHS, RHS);
18045         }
18046         Opcode = X86ISD::FMAX;
18047         break;
18048       case ISD::SETULE:
18049         // Converting this to a max would handle both negative zeros and NaNs
18050         // incorrectly, but we can swap the operands to fix both.
18051         std::swap(LHS, RHS);
18052       case ISD::SETOLT:
18053       case ISD::SETLT:
18054       case ISD::SETLE:
18055         Opcode = X86ISD::FMAX;
18056         break;
18057       }
18058     }
18059
18060     if (Opcode)
18061       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18062   }
18063
18064   EVT CondVT = Cond.getValueType();
18065   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18066       CondVT.getVectorElementType() == MVT::i1) {
18067     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18068     // lowering on AVX-512. In this case we convert it to
18069     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18070     // The same situation for all 128 and 256-bit vectors of i8 and i16
18071     EVT OpVT = LHS.getValueType();
18072     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18073         (OpVT.getVectorElementType() == MVT::i8 ||
18074          OpVT.getVectorElementType() == MVT::i16)) {
18075       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18076       DCI.AddToWorklist(Cond.getNode());
18077       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18078     }
18079   }
18080   // If this is a select between two integer constants, try to do some
18081   // optimizations.
18082   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18083     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18084       // Don't do this for crazy integer types.
18085       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18086         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18087         // so that TrueC (the true value) is larger than FalseC.
18088         bool NeedsCondInvert = false;
18089
18090         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18091             // Efficiently invertible.
18092             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
18093              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
18094               isa<ConstantSDNode>(Cond.getOperand(1))))) {
18095           NeedsCondInvert = true;
18096           std::swap(TrueC, FalseC);
18097         }
18098
18099         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
18100         if (FalseC->getAPIntValue() == 0 &&
18101             TrueC->getAPIntValue().isPowerOf2()) {
18102           if (NeedsCondInvert) // Invert the condition if needed.
18103             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18104                                DAG.getConstant(1, Cond.getValueType()));
18105
18106           // Zero extend the condition if needed.
18107           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18108
18109           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18110           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18111                              DAG.getConstant(ShAmt, MVT::i8));
18112         }
18113
18114         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18115         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18116           if (NeedsCondInvert) // Invert the condition if needed.
18117             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18118                                DAG.getConstant(1, Cond.getValueType()));
18119
18120           // Zero extend the condition if needed.
18121           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18122                              FalseC->getValueType(0), Cond);
18123           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18124                              SDValue(FalseC, 0));
18125         }
18126
18127         // Optimize cases that will turn into an LEA instruction.  This requires
18128         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18129         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18130           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18131           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18132
18133           bool isFastMultiplier = false;
18134           if (Diff < 10) {
18135             switch ((unsigned char)Diff) {
18136               default: break;
18137               case 1:  // result = add base, cond
18138               case 2:  // result = lea base(    , cond*2)
18139               case 3:  // result = lea base(cond, cond*2)
18140               case 4:  // result = lea base(    , cond*4)
18141               case 5:  // result = lea base(cond, cond*4)
18142               case 8:  // result = lea base(    , cond*8)
18143               case 9:  // result = lea base(cond, cond*8)
18144                 isFastMultiplier = true;
18145                 break;
18146             }
18147           }
18148
18149           if (isFastMultiplier) {
18150             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18151             if (NeedsCondInvert) // Invert the condition if needed.
18152               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18153                                  DAG.getConstant(1, Cond.getValueType()));
18154
18155             // Zero extend the condition if needed.
18156             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18157                                Cond);
18158             // Scale the condition by the difference.
18159             if (Diff != 1)
18160               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18161                                  DAG.getConstant(Diff, Cond.getValueType()));
18162
18163             // Add the base if non-zero.
18164             if (FalseC->getAPIntValue() != 0)
18165               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18166                                  SDValue(FalseC, 0));
18167             return Cond;
18168           }
18169         }
18170       }
18171   }
18172
18173   // Canonicalize max and min:
18174   // (x > y) ? x : y -> (x >= y) ? x : y
18175   // (x < y) ? x : y -> (x <= y) ? x : y
18176   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18177   // the need for an extra compare
18178   // against zero. e.g.
18179   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18180   // subl   %esi, %edi
18181   // testl  %edi, %edi
18182   // movl   $0, %eax
18183   // cmovgl %edi, %eax
18184   // =>
18185   // xorl   %eax, %eax
18186   // subl   %esi, $edi
18187   // cmovsl %eax, %edi
18188   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18189       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18190       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18191     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18192     switch (CC) {
18193     default: break;
18194     case ISD::SETLT:
18195     case ISD::SETGT: {
18196       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18197       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18198                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18199       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18200     }
18201     }
18202   }
18203
18204   // Early exit check
18205   if (!TLI.isTypeLegal(VT))
18206     return SDValue();
18207
18208   // Match VSELECTs into subs with unsigned saturation.
18209   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18210       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18211       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18212        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18213     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18214
18215     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18216     // left side invert the predicate to simplify logic below.
18217     SDValue Other;
18218     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18219       Other = RHS;
18220       CC = ISD::getSetCCInverse(CC, true);
18221     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18222       Other = LHS;
18223     }
18224
18225     if (Other.getNode() && Other->getNumOperands() == 2 &&
18226         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18227       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18228       SDValue CondRHS = Cond->getOperand(1);
18229
18230       // Look for a general sub with unsigned saturation first.
18231       // x >= y ? x-y : 0 --> subus x, y
18232       // x >  y ? x-y : 0 --> subus x, y
18233       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18234           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18235         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18236
18237       // If the RHS is a constant we have to reverse the const canonicalization.
18238       // x > C-1 ? x+-C : 0 --> subus x, C
18239       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18240           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18241         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18242         if (CondRHS.getConstantOperandVal(0) == -A-1)
18243           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18244                              DAG.getConstant(-A, VT));
18245       }
18246
18247       // Another special case: If C was a sign bit, the sub has been
18248       // canonicalized into a xor.
18249       // FIXME: Would it be better to use computeKnownBits to determine whether
18250       //        it's safe to decanonicalize the xor?
18251       // x s< 0 ? x^C : 0 --> subus x, C
18252       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18253           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18254           isSplatVector(OpRHS.getNode())) {
18255         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18256         if (A.isSignBit())
18257           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18258       }
18259     }
18260   }
18261
18262   // Try to match a min/max vector operation.
18263   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18264     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18265     unsigned Opc = ret.first;
18266     bool NeedSplit = ret.second;
18267
18268     if (Opc && NeedSplit) {
18269       unsigned NumElems = VT.getVectorNumElements();
18270       // Extract the LHS vectors
18271       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18272       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18273
18274       // Extract the RHS vectors
18275       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18276       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18277
18278       // Create min/max for each subvector
18279       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18280       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18281
18282       // Merge the result
18283       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18284     } else if (Opc)
18285       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18286   }
18287
18288   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18289   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18290       // Check if SETCC has already been promoted
18291       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18292       // Check that condition value type matches vselect operand type
18293       CondVT == VT) { 
18294
18295     assert(Cond.getValueType().isVector() &&
18296            "vector select expects a vector selector!");
18297
18298     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18299     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18300
18301     if (!TValIsAllOnes && !FValIsAllZeros) {
18302       // Try invert the condition if true value is not all 1s and false value
18303       // is not all 0s.
18304       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18305       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18306
18307       if (TValIsAllZeros || FValIsAllOnes) {
18308         SDValue CC = Cond.getOperand(2);
18309         ISD::CondCode NewCC =
18310           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18311                                Cond.getOperand(0).getValueType().isInteger());
18312         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18313         std::swap(LHS, RHS);
18314         TValIsAllOnes = FValIsAllOnes;
18315         FValIsAllZeros = TValIsAllZeros;
18316       }
18317     }
18318
18319     if (TValIsAllOnes || FValIsAllZeros) {
18320       SDValue Ret;
18321
18322       if (TValIsAllOnes && FValIsAllZeros)
18323         Ret = Cond;
18324       else if (TValIsAllOnes)
18325         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18326                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18327       else if (FValIsAllZeros)
18328         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18329                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18330
18331       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18332     }
18333   }
18334
18335   // Try to fold this VSELECT into a MOVSS/MOVSD
18336   if (N->getOpcode() == ISD::VSELECT &&
18337       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18338     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18339         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18340       bool CanFold = false;
18341       unsigned NumElems = Cond.getNumOperands();
18342       SDValue A = LHS;
18343       SDValue B = RHS;
18344       
18345       if (isZero(Cond.getOperand(0))) {
18346         CanFold = true;
18347
18348         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18349         // fold (vselect <0,-1> -> (movsd A, B)
18350         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18351           CanFold = isAllOnes(Cond.getOperand(i));
18352       } else if (isAllOnes(Cond.getOperand(0))) {
18353         CanFold = true;
18354         std::swap(A, B);
18355
18356         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18357         // fold (vselect <-1,0> -> (movsd B, A)
18358         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18359           CanFold = isZero(Cond.getOperand(i));
18360       }
18361
18362       if (CanFold) {
18363         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18364           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18365         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18366       }
18367
18368       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18369         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18370         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18371         //                             (v2i64 (bitcast B)))))
18372         //
18373         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18374         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18375         //                             (v2f64 (bitcast B)))))
18376         //
18377         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18378         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18379         //                             (v2i64 (bitcast A)))))
18380         //
18381         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18382         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18383         //                             (v2f64 (bitcast A)))))
18384
18385         CanFold = (isZero(Cond.getOperand(0)) &&
18386                    isZero(Cond.getOperand(1)) &&
18387                    isAllOnes(Cond.getOperand(2)) &&
18388                    isAllOnes(Cond.getOperand(3)));
18389
18390         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18391             isAllOnes(Cond.getOperand(1)) &&
18392             isZero(Cond.getOperand(2)) &&
18393             isZero(Cond.getOperand(3))) {
18394           CanFold = true;
18395           std::swap(LHS, RHS);
18396         }
18397
18398         if (CanFold) {
18399           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18400           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18401           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18402           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18403                                                 NewB, DAG);
18404           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18405         }
18406       }
18407     }
18408   }
18409
18410   // If we know that this node is legal then we know that it is going to be
18411   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18412   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18413   // to simplify previous instructions.
18414   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18415       !DCI.isBeforeLegalize() &&
18416       // We explicitly check against v8i16 and v16i16 because, although
18417       // they're marked as Custom, they might only be legal when Cond is a
18418       // build_vector of constants. This will be taken care in a later
18419       // condition.
18420       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18421        VT != MVT::v8i16)) {
18422     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18423
18424     // Don't optimize vector selects that map to mask-registers.
18425     if (BitWidth == 1)
18426       return SDValue();
18427
18428     // Check all uses of that condition operand to check whether it will be
18429     // consumed by non-BLEND instructions, which may depend on all bits are set
18430     // properly.
18431     for (SDNode::use_iterator I = Cond->use_begin(),
18432                               E = Cond->use_end(); I != E; ++I)
18433       if (I->getOpcode() != ISD::VSELECT)
18434         // TODO: Add other opcodes eventually lowered into BLEND.
18435         return SDValue();
18436
18437     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18438     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18439
18440     APInt KnownZero, KnownOne;
18441     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18442                                           DCI.isBeforeLegalizeOps());
18443     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18444         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18445       DCI.CommitTargetLoweringOpt(TLO);
18446   }
18447
18448   // We should generate an X86ISD::BLENDI from a vselect if its argument
18449   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18450   // constants. This specific pattern gets generated when we split a
18451   // selector for a 512 bit vector in a machine without AVX512 (but with
18452   // 256-bit vectors), during legalization:
18453   //
18454   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18455   //
18456   // Iff we find this pattern and the build_vectors are built from
18457   // constants, we translate the vselect into a shuffle_vector that we
18458   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18459   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18460     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18461     if (Shuffle.getNode())
18462       return Shuffle;
18463   }
18464
18465   return SDValue();
18466 }
18467
18468 // Check whether a boolean test is testing a boolean value generated by
18469 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18470 // code.
18471 //
18472 // Simplify the following patterns:
18473 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18474 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18475 // to (Op EFLAGS Cond)
18476 //
18477 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18478 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18479 // to (Op EFLAGS !Cond)
18480 //
18481 // where Op could be BRCOND or CMOV.
18482 //
18483 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18484   // Quit if not CMP and SUB with its value result used.
18485   if (Cmp.getOpcode() != X86ISD::CMP &&
18486       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18487       return SDValue();
18488
18489   // Quit if not used as a boolean value.
18490   if (CC != X86::COND_E && CC != X86::COND_NE)
18491     return SDValue();
18492
18493   // Check CMP operands. One of them should be 0 or 1 and the other should be
18494   // an SetCC or extended from it.
18495   SDValue Op1 = Cmp.getOperand(0);
18496   SDValue Op2 = Cmp.getOperand(1);
18497
18498   SDValue SetCC;
18499   const ConstantSDNode* C = nullptr;
18500   bool needOppositeCond = (CC == X86::COND_E);
18501   bool checkAgainstTrue = false; // Is it a comparison against 1?
18502
18503   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18504     SetCC = Op2;
18505   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18506     SetCC = Op1;
18507   else // Quit if all operands are not constants.
18508     return SDValue();
18509
18510   if (C->getZExtValue() == 1) {
18511     needOppositeCond = !needOppositeCond;
18512     checkAgainstTrue = true;
18513   } else if (C->getZExtValue() != 0)
18514     // Quit if the constant is neither 0 or 1.
18515     return SDValue();
18516
18517   bool truncatedToBoolWithAnd = false;
18518   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18519   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18520          SetCC.getOpcode() == ISD::TRUNCATE ||
18521          SetCC.getOpcode() == ISD::AND) {
18522     if (SetCC.getOpcode() == ISD::AND) {
18523       int OpIdx = -1;
18524       ConstantSDNode *CS;
18525       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18526           CS->getZExtValue() == 1)
18527         OpIdx = 1;
18528       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18529           CS->getZExtValue() == 1)
18530         OpIdx = 0;
18531       if (OpIdx == -1)
18532         break;
18533       SetCC = SetCC.getOperand(OpIdx);
18534       truncatedToBoolWithAnd = true;
18535     } else
18536       SetCC = SetCC.getOperand(0);
18537   }
18538
18539   switch (SetCC.getOpcode()) {
18540   case X86ISD::SETCC_CARRY:
18541     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18542     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18543     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18544     // truncated to i1 using 'and'.
18545     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18546       break;
18547     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18548            "Invalid use of SETCC_CARRY!");
18549     // FALL THROUGH
18550   case X86ISD::SETCC:
18551     // Set the condition code or opposite one if necessary.
18552     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18553     if (needOppositeCond)
18554       CC = X86::GetOppositeBranchCondition(CC);
18555     return SetCC.getOperand(1);
18556   case X86ISD::CMOV: {
18557     // Check whether false/true value has canonical one, i.e. 0 or 1.
18558     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18559     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18560     // Quit if true value is not a constant.
18561     if (!TVal)
18562       return SDValue();
18563     // Quit if false value is not a constant.
18564     if (!FVal) {
18565       SDValue Op = SetCC.getOperand(0);
18566       // Skip 'zext' or 'trunc' node.
18567       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18568           Op.getOpcode() == ISD::TRUNCATE)
18569         Op = Op.getOperand(0);
18570       // A special case for rdrand/rdseed, where 0 is set if false cond is
18571       // found.
18572       if ((Op.getOpcode() != X86ISD::RDRAND &&
18573            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18574         return SDValue();
18575     }
18576     // Quit if false value is not the constant 0 or 1.
18577     bool FValIsFalse = true;
18578     if (FVal && FVal->getZExtValue() != 0) {
18579       if (FVal->getZExtValue() != 1)
18580         return SDValue();
18581       // If FVal is 1, opposite cond is needed.
18582       needOppositeCond = !needOppositeCond;
18583       FValIsFalse = false;
18584     }
18585     // Quit if TVal is not the constant opposite of FVal.
18586     if (FValIsFalse && TVal->getZExtValue() != 1)
18587       return SDValue();
18588     if (!FValIsFalse && TVal->getZExtValue() != 0)
18589       return SDValue();
18590     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18591     if (needOppositeCond)
18592       CC = X86::GetOppositeBranchCondition(CC);
18593     return SetCC.getOperand(3);
18594   }
18595   }
18596
18597   return SDValue();
18598 }
18599
18600 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18601 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18602                                   TargetLowering::DAGCombinerInfo &DCI,
18603                                   const X86Subtarget *Subtarget) {
18604   SDLoc DL(N);
18605
18606   // If the flag operand isn't dead, don't touch this CMOV.
18607   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18608     return SDValue();
18609
18610   SDValue FalseOp = N->getOperand(0);
18611   SDValue TrueOp = N->getOperand(1);
18612   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18613   SDValue Cond = N->getOperand(3);
18614
18615   if (CC == X86::COND_E || CC == X86::COND_NE) {
18616     switch (Cond.getOpcode()) {
18617     default: break;
18618     case X86ISD::BSR:
18619     case X86ISD::BSF:
18620       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18621       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18622         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18623     }
18624   }
18625
18626   SDValue Flags;
18627
18628   Flags = checkBoolTestSetCCCombine(Cond, CC);
18629   if (Flags.getNode() &&
18630       // Extra check as FCMOV only supports a subset of X86 cond.
18631       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18632     SDValue Ops[] = { FalseOp, TrueOp,
18633                       DAG.getConstant(CC, MVT::i8), Flags };
18634     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18635   }
18636
18637   // If this is a select between two integer constants, try to do some
18638   // optimizations.  Note that the operands are ordered the opposite of SELECT
18639   // operands.
18640   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18641     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18642       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18643       // larger than FalseC (the false value).
18644       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18645         CC = X86::GetOppositeBranchCondition(CC);
18646         std::swap(TrueC, FalseC);
18647         std::swap(TrueOp, FalseOp);
18648       }
18649
18650       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18651       // This is efficient for any integer data type (including i8/i16) and
18652       // shift amount.
18653       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18654         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18655                            DAG.getConstant(CC, MVT::i8), Cond);
18656
18657         // Zero extend the condition if needed.
18658         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18659
18660         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18661         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18662                            DAG.getConstant(ShAmt, MVT::i8));
18663         if (N->getNumValues() == 2)  // Dead flag value?
18664           return DCI.CombineTo(N, Cond, SDValue());
18665         return Cond;
18666       }
18667
18668       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18669       // for any integer data type, including i8/i16.
18670       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18671         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18672                            DAG.getConstant(CC, MVT::i8), Cond);
18673
18674         // Zero extend the condition if needed.
18675         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18676                            FalseC->getValueType(0), Cond);
18677         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18678                            SDValue(FalseC, 0));
18679
18680         if (N->getNumValues() == 2)  // Dead flag value?
18681           return DCI.CombineTo(N, Cond, SDValue());
18682         return Cond;
18683       }
18684
18685       // Optimize cases that will turn into an LEA instruction.  This requires
18686       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18687       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18688         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18689         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18690
18691         bool isFastMultiplier = false;
18692         if (Diff < 10) {
18693           switch ((unsigned char)Diff) {
18694           default: break;
18695           case 1:  // result = add base, cond
18696           case 2:  // result = lea base(    , cond*2)
18697           case 3:  // result = lea base(cond, cond*2)
18698           case 4:  // result = lea base(    , cond*4)
18699           case 5:  // result = lea base(cond, cond*4)
18700           case 8:  // result = lea base(    , cond*8)
18701           case 9:  // result = lea base(cond, cond*8)
18702             isFastMultiplier = true;
18703             break;
18704           }
18705         }
18706
18707         if (isFastMultiplier) {
18708           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18709           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18710                              DAG.getConstant(CC, MVT::i8), Cond);
18711           // Zero extend the condition if needed.
18712           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18713                              Cond);
18714           // Scale the condition by the difference.
18715           if (Diff != 1)
18716             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18717                                DAG.getConstant(Diff, Cond.getValueType()));
18718
18719           // Add the base if non-zero.
18720           if (FalseC->getAPIntValue() != 0)
18721             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18722                                SDValue(FalseC, 0));
18723           if (N->getNumValues() == 2)  // Dead flag value?
18724             return DCI.CombineTo(N, Cond, SDValue());
18725           return Cond;
18726         }
18727       }
18728     }
18729   }
18730
18731   // Handle these cases:
18732   //   (select (x != c), e, c) -> select (x != c), e, x),
18733   //   (select (x == c), c, e) -> select (x == c), x, e)
18734   // where the c is an integer constant, and the "select" is the combination
18735   // of CMOV and CMP.
18736   //
18737   // The rationale for this change is that the conditional-move from a constant
18738   // needs two instructions, however, conditional-move from a register needs
18739   // only one instruction.
18740   //
18741   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18742   //  some instruction-combining opportunities. This opt needs to be
18743   //  postponed as late as possible.
18744   //
18745   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18746     // the DCI.xxxx conditions are provided to postpone the optimization as
18747     // late as possible.
18748
18749     ConstantSDNode *CmpAgainst = nullptr;
18750     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18751         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18752         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18753
18754       if (CC == X86::COND_NE &&
18755           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18756         CC = X86::GetOppositeBranchCondition(CC);
18757         std::swap(TrueOp, FalseOp);
18758       }
18759
18760       if (CC == X86::COND_E &&
18761           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18762         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18763                           DAG.getConstant(CC, MVT::i8), Cond };
18764         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18765       }
18766     }
18767   }
18768
18769   return SDValue();
18770 }
18771
18772 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18773                                                 const X86Subtarget *Subtarget) {
18774   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18775   switch (IntNo) {
18776   default: return SDValue();
18777   // SSE/AVX/AVX2 blend intrinsics.
18778   case Intrinsic::x86_avx2_pblendvb:
18779   case Intrinsic::x86_avx2_pblendw:
18780   case Intrinsic::x86_avx2_pblendd_128:
18781   case Intrinsic::x86_avx2_pblendd_256:
18782     // Don't try to simplify this intrinsic if we don't have AVX2.
18783     if (!Subtarget->hasAVX2())
18784       return SDValue();
18785     // FALL-THROUGH
18786   case Intrinsic::x86_avx_blend_pd_256:
18787   case Intrinsic::x86_avx_blend_ps_256:
18788   case Intrinsic::x86_avx_blendv_pd_256:
18789   case Intrinsic::x86_avx_blendv_ps_256:
18790     // Don't try to simplify this intrinsic if we don't have AVX.
18791     if (!Subtarget->hasAVX())
18792       return SDValue();
18793     // FALL-THROUGH
18794   case Intrinsic::x86_sse41_pblendw:
18795   case Intrinsic::x86_sse41_blendpd:
18796   case Intrinsic::x86_sse41_blendps:
18797   case Intrinsic::x86_sse41_blendvps:
18798   case Intrinsic::x86_sse41_blendvpd:
18799   case Intrinsic::x86_sse41_pblendvb: {
18800     SDValue Op0 = N->getOperand(1);
18801     SDValue Op1 = N->getOperand(2);
18802     SDValue Mask = N->getOperand(3);
18803
18804     // Don't try to simplify this intrinsic if we don't have SSE4.1.
18805     if (!Subtarget->hasSSE41())
18806       return SDValue();
18807
18808     // fold (blend A, A, Mask) -> A
18809     if (Op0 == Op1)
18810       return Op0;
18811     // fold (blend A, B, allZeros) -> A
18812     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18813       return Op0;
18814     // fold (blend A, B, allOnes) -> B
18815     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18816       return Op1;
18817     
18818     // Simplify the case where the mask is a constant i32 value.
18819     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18820       if (C->isNullValue())
18821         return Op0;
18822       if (C->isAllOnesValue())
18823         return Op1;
18824     }
18825   }
18826
18827   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18828   case Intrinsic::x86_sse2_psrai_w:
18829   case Intrinsic::x86_sse2_psrai_d:
18830   case Intrinsic::x86_avx2_psrai_w:
18831   case Intrinsic::x86_avx2_psrai_d:
18832   case Intrinsic::x86_sse2_psra_w:
18833   case Intrinsic::x86_sse2_psra_d:
18834   case Intrinsic::x86_avx2_psra_w:
18835   case Intrinsic::x86_avx2_psra_d: {
18836     SDValue Op0 = N->getOperand(1);
18837     SDValue Op1 = N->getOperand(2);
18838     EVT VT = Op0.getValueType();
18839     assert(VT.isVector() && "Expected a vector type!");
18840
18841     if (isa<BuildVectorSDNode>(Op1))
18842       Op1 = Op1.getOperand(0);
18843
18844     if (!isa<ConstantSDNode>(Op1))
18845       return SDValue();
18846
18847     EVT SVT = VT.getVectorElementType();
18848     unsigned SVTBits = SVT.getSizeInBits();
18849
18850     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18851     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18852     uint64_t ShAmt = C.getZExtValue();
18853
18854     // Don't try to convert this shift into a ISD::SRA if the shift
18855     // count is bigger than or equal to the element size.
18856     if (ShAmt >= SVTBits)
18857       return SDValue();
18858
18859     // Trivial case: if the shift count is zero, then fold this
18860     // into the first operand.
18861     if (ShAmt == 0)
18862       return Op0;
18863
18864     // Replace this packed shift intrinsic with a target independent
18865     // shift dag node.
18866     SDValue Splat = DAG.getConstant(C, VT);
18867     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18868   }
18869   }
18870 }
18871
18872 /// PerformMulCombine - Optimize a single multiply with constant into two
18873 /// in order to implement it with two cheaper instructions, e.g.
18874 /// LEA + SHL, LEA + LEA.
18875 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18876                                  TargetLowering::DAGCombinerInfo &DCI) {
18877   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18878     return SDValue();
18879
18880   EVT VT = N->getValueType(0);
18881   if (VT != MVT::i64)
18882     return SDValue();
18883
18884   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18885   if (!C)
18886     return SDValue();
18887   uint64_t MulAmt = C->getZExtValue();
18888   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18889     return SDValue();
18890
18891   uint64_t MulAmt1 = 0;
18892   uint64_t MulAmt2 = 0;
18893   if ((MulAmt % 9) == 0) {
18894     MulAmt1 = 9;
18895     MulAmt2 = MulAmt / 9;
18896   } else if ((MulAmt % 5) == 0) {
18897     MulAmt1 = 5;
18898     MulAmt2 = MulAmt / 5;
18899   } else if ((MulAmt % 3) == 0) {
18900     MulAmt1 = 3;
18901     MulAmt2 = MulAmt / 3;
18902   }
18903   if (MulAmt2 &&
18904       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18905     SDLoc DL(N);
18906
18907     if (isPowerOf2_64(MulAmt2) &&
18908         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18909       // If second multiplifer is pow2, issue it first. We want the multiply by
18910       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18911       // is an add.
18912       std::swap(MulAmt1, MulAmt2);
18913
18914     SDValue NewMul;
18915     if (isPowerOf2_64(MulAmt1))
18916       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18917                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18918     else
18919       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18920                            DAG.getConstant(MulAmt1, VT));
18921
18922     if (isPowerOf2_64(MulAmt2))
18923       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18924                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18925     else
18926       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18927                            DAG.getConstant(MulAmt2, VT));
18928
18929     // Do not add new nodes to DAG combiner worklist.
18930     DCI.CombineTo(N, NewMul, false);
18931   }
18932   return SDValue();
18933 }
18934
18935 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18936   SDValue N0 = N->getOperand(0);
18937   SDValue N1 = N->getOperand(1);
18938   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18939   EVT VT = N0.getValueType();
18940
18941   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18942   // since the result of setcc_c is all zero's or all ones.
18943   if (VT.isInteger() && !VT.isVector() &&
18944       N1C && N0.getOpcode() == ISD::AND &&
18945       N0.getOperand(1).getOpcode() == ISD::Constant) {
18946     SDValue N00 = N0.getOperand(0);
18947     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18948         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18949           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18950          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18951       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18952       APInt ShAmt = N1C->getAPIntValue();
18953       Mask = Mask.shl(ShAmt);
18954       if (Mask != 0)
18955         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18956                            N00, DAG.getConstant(Mask, VT));
18957     }
18958   }
18959
18960   // Hardware support for vector shifts is sparse which makes us scalarize the
18961   // vector operations in many cases. Also, on sandybridge ADD is faster than
18962   // shl.
18963   // (shl V, 1) -> add V,V
18964   if (isSplatVector(N1.getNode())) {
18965     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18966     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18967     // We shift all of the values by one. In many cases we do not have
18968     // hardware support for this operation. This is better expressed as an ADD
18969     // of two values.
18970     if (N1C && (1 == N1C->getZExtValue())) {
18971       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18972     }
18973   }
18974
18975   return SDValue();
18976 }
18977
18978 /// \brief Returns a vector of 0s if the node in input is a vector logical
18979 /// shift by a constant amount which is known to be bigger than or equal
18980 /// to the vector element size in bits.
18981 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18982                                       const X86Subtarget *Subtarget) {
18983   EVT VT = N->getValueType(0);
18984
18985   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18986       (!Subtarget->hasInt256() ||
18987        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18988     return SDValue();
18989
18990   SDValue Amt = N->getOperand(1);
18991   SDLoc DL(N);
18992   if (isSplatVector(Amt.getNode())) {
18993     SDValue SclrAmt = Amt->getOperand(0);
18994     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18995       APInt ShiftAmt = C->getAPIntValue();
18996       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18997
18998       // SSE2/AVX2 logical shifts always return a vector of 0s
18999       // if the shift amount is bigger than or equal to
19000       // the element size. The constant shift amount will be
19001       // encoded as a 8-bit immediate.
19002       if (ShiftAmt.trunc(8).uge(MaxAmount))
19003         return getZeroVector(VT, Subtarget, DAG, DL);
19004     }
19005   }
19006
19007   return SDValue();
19008 }
19009
19010 /// PerformShiftCombine - Combine shifts.
19011 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19012                                    TargetLowering::DAGCombinerInfo &DCI,
19013                                    const X86Subtarget *Subtarget) {
19014   if (N->getOpcode() == ISD::SHL) {
19015     SDValue V = PerformSHLCombine(N, DAG);
19016     if (V.getNode()) return V;
19017   }
19018
19019   if (N->getOpcode() != ISD::SRA) {
19020     // Try to fold this logical shift into a zero vector.
19021     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19022     if (V.getNode()) return V;
19023   }
19024
19025   return SDValue();
19026 }
19027
19028 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
19029 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19030 // and friends.  Likewise for OR -> CMPNEQSS.
19031 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19032                             TargetLowering::DAGCombinerInfo &DCI,
19033                             const X86Subtarget *Subtarget) {
19034   unsigned opcode;
19035
19036   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19037   // we're requiring SSE2 for both.
19038   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19039     SDValue N0 = N->getOperand(0);
19040     SDValue N1 = N->getOperand(1);
19041     SDValue CMP0 = N0->getOperand(1);
19042     SDValue CMP1 = N1->getOperand(1);
19043     SDLoc DL(N);
19044
19045     // The SETCCs should both refer to the same CMP.
19046     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19047       return SDValue();
19048
19049     SDValue CMP00 = CMP0->getOperand(0);
19050     SDValue CMP01 = CMP0->getOperand(1);
19051     EVT     VT    = CMP00.getValueType();
19052
19053     if (VT == MVT::f32 || VT == MVT::f64) {
19054       bool ExpectingFlags = false;
19055       // Check for any users that want flags:
19056       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19057            !ExpectingFlags && UI != UE; ++UI)
19058         switch (UI->getOpcode()) {
19059         default:
19060         case ISD::BR_CC:
19061         case ISD::BRCOND:
19062         case ISD::SELECT:
19063           ExpectingFlags = true;
19064           break;
19065         case ISD::CopyToReg:
19066         case ISD::SIGN_EXTEND:
19067         case ISD::ZERO_EXTEND:
19068         case ISD::ANY_EXTEND:
19069           break;
19070         }
19071
19072       if (!ExpectingFlags) {
19073         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19074         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19075
19076         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19077           X86::CondCode tmp = cc0;
19078           cc0 = cc1;
19079           cc1 = tmp;
19080         }
19081
19082         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
19083             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19084           // FIXME: need symbolic constants for these magic numbers.
19085           // See X86ATTInstPrinter.cpp:printSSECC().
19086           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19087           if (Subtarget->hasAVX512()) {
19088             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19089                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
19090             if (N->getValueType(0) != MVT::i1)
19091               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19092                                  FSetCC);
19093             return FSetCC;
19094           }
19095           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19096                                               CMP00.getValueType(), CMP00, CMP01,
19097                                               DAG.getConstant(x86cc, MVT::i8));
19098
19099           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19100           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19101
19102           if (is64BitFP && !Subtarget->is64Bit()) {
19103             // On a 32-bit target, we cannot bitcast the 64-bit float to a
19104             // 64-bit integer, since that's not a legal type. Since
19105             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19106             // bits, but can do this little dance to extract the lowest 32 bits
19107             // and work with those going forward.
19108             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19109                                            OnesOrZeroesF);
19110             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19111                                            Vector64);
19112             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19113                                         Vector32, DAG.getIntPtrConstant(0));
19114             IntVT = MVT::i32;
19115           }
19116
19117           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19118           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19119                                       DAG.getConstant(1, IntVT));
19120           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19121           return OneBitOfTruth;
19122         }
19123       }
19124     }
19125   }
19126   return SDValue();
19127 }
19128
19129 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19130 /// so it can be folded inside ANDNP.
19131 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19132   EVT VT = N->getValueType(0);
19133
19134   // Match direct AllOnes for 128 and 256-bit vectors
19135   if (ISD::isBuildVectorAllOnes(N))
19136     return true;
19137
19138   // Look through a bit convert.
19139   if (N->getOpcode() == ISD::BITCAST)
19140     N = N->getOperand(0).getNode();
19141
19142   // Sometimes the operand may come from a insert_subvector building a 256-bit
19143   // allones vector
19144   if (VT.is256BitVector() &&
19145       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19146     SDValue V1 = N->getOperand(0);
19147     SDValue V2 = N->getOperand(1);
19148
19149     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19150         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19151         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19152         ISD::isBuildVectorAllOnes(V2.getNode()))
19153       return true;
19154   }
19155
19156   return false;
19157 }
19158
19159 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19160 // register. In most cases we actually compare or select YMM-sized registers
19161 // and mixing the two types creates horrible code. This method optimizes
19162 // some of the transition sequences.
19163 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19164                                  TargetLowering::DAGCombinerInfo &DCI,
19165                                  const X86Subtarget *Subtarget) {
19166   EVT VT = N->getValueType(0);
19167   if (!VT.is256BitVector())
19168     return SDValue();
19169
19170   assert((N->getOpcode() == ISD::ANY_EXTEND ||
19171           N->getOpcode() == ISD::ZERO_EXTEND ||
19172           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19173
19174   SDValue Narrow = N->getOperand(0);
19175   EVT NarrowVT = Narrow->getValueType(0);
19176   if (!NarrowVT.is128BitVector())
19177     return SDValue();
19178
19179   if (Narrow->getOpcode() != ISD::XOR &&
19180       Narrow->getOpcode() != ISD::AND &&
19181       Narrow->getOpcode() != ISD::OR)
19182     return SDValue();
19183
19184   SDValue N0  = Narrow->getOperand(0);
19185   SDValue N1  = Narrow->getOperand(1);
19186   SDLoc DL(Narrow);
19187
19188   // The Left side has to be a trunc.
19189   if (N0.getOpcode() != ISD::TRUNCATE)
19190     return SDValue();
19191
19192   // The type of the truncated inputs.
19193   EVT WideVT = N0->getOperand(0)->getValueType(0);
19194   if (WideVT != VT)
19195     return SDValue();
19196
19197   // The right side has to be a 'trunc' or a constant vector.
19198   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19199   bool RHSConst = (isSplatVector(N1.getNode()) &&
19200                    isa<ConstantSDNode>(N1->getOperand(0)));
19201   if (!RHSTrunc && !RHSConst)
19202     return SDValue();
19203
19204   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19205
19206   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19207     return SDValue();
19208
19209   // Set N0 and N1 to hold the inputs to the new wide operation.
19210   N0 = N0->getOperand(0);
19211   if (RHSConst) {
19212     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19213                      N1->getOperand(0));
19214     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19215     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19216   } else if (RHSTrunc) {
19217     N1 = N1->getOperand(0);
19218   }
19219
19220   // Generate the wide operation.
19221   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19222   unsigned Opcode = N->getOpcode();
19223   switch (Opcode) {
19224   case ISD::ANY_EXTEND:
19225     return Op;
19226   case ISD::ZERO_EXTEND: {
19227     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19228     APInt Mask = APInt::getAllOnesValue(InBits);
19229     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19230     return DAG.getNode(ISD::AND, DL, VT,
19231                        Op, DAG.getConstant(Mask, VT));
19232   }
19233   case ISD::SIGN_EXTEND:
19234     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19235                        Op, DAG.getValueType(NarrowVT));
19236   default:
19237     llvm_unreachable("Unexpected opcode");
19238   }
19239 }
19240
19241 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19242                                  TargetLowering::DAGCombinerInfo &DCI,
19243                                  const X86Subtarget *Subtarget) {
19244   EVT VT = N->getValueType(0);
19245   if (DCI.isBeforeLegalizeOps())
19246     return SDValue();
19247
19248   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19249   if (R.getNode())
19250     return R;
19251
19252   // Create BEXTR instructions
19253   // BEXTR is ((X >> imm) & (2**size-1))
19254   if (VT == MVT::i32 || VT == MVT::i64) {
19255     SDValue N0 = N->getOperand(0);
19256     SDValue N1 = N->getOperand(1);
19257     SDLoc DL(N);
19258
19259     // Check for BEXTR.
19260     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19261         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19262       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19263       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19264       if (MaskNode && ShiftNode) {
19265         uint64_t Mask = MaskNode->getZExtValue();
19266         uint64_t Shift = ShiftNode->getZExtValue();
19267         if (isMask_64(Mask)) {
19268           uint64_t MaskSize = CountPopulation_64(Mask);
19269           if (Shift + MaskSize <= VT.getSizeInBits())
19270             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19271                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19272         }
19273       }
19274     } // BEXTR
19275
19276     return SDValue();
19277   }
19278
19279   // Want to form ANDNP nodes:
19280   // 1) In the hopes of then easily combining them with OR and AND nodes
19281   //    to form PBLEND/PSIGN.
19282   // 2) To match ANDN packed intrinsics
19283   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19284     return SDValue();
19285
19286   SDValue N0 = N->getOperand(0);
19287   SDValue N1 = N->getOperand(1);
19288   SDLoc DL(N);
19289
19290   // Check LHS for vnot
19291   if (N0.getOpcode() == ISD::XOR &&
19292       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19293       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19294     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19295
19296   // Check RHS for vnot
19297   if (N1.getOpcode() == ISD::XOR &&
19298       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19299       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19300     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19301
19302   return SDValue();
19303 }
19304
19305 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19306                                 TargetLowering::DAGCombinerInfo &DCI,
19307                                 const X86Subtarget *Subtarget) {
19308   if (DCI.isBeforeLegalizeOps())
19309     return SDValue();
19310
19311   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19312   if (R.getNode())
19313     return R;
19314
19315   SDValue N0 = N->getOperand(0);
19316   SDValue N1 = N->getOperand(1);
19317   EVT VT = N->getValueType(0);
19318
19319   // look for psign/blend
19320   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19321     if (!Subtarget->hasSSSE3() ||
19322         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19323       return SDValue();
19324
19325     // Canonicalize pandn to RHS
19326     if (N0.getOpcode() == X86ISD::ANDNP)
19327       std::swap(N0, N1);
19328     // or (and (m, y), (pandn m, x))
19329     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19330       SDValue Mask = N1.getOperand(0);
19331       SDValue X    = N1.getOperand(1);
19332       SDValue Y;
19333       if (N0.getOperand(0) == Mask)
19334         Y = N0.getOperand(1);
19335       if (N0.getOperand(1) == Mask)
19336         Y = N0.getOperand(0);
19337
19338       // Check to see if the mask appeared in both the AND and ANDNP and
19339       if (!Y.getNode())
19340         return SDValue();
19341
19342       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19343       // Look through mask bitcast.
19344       if (Mask.getOpcode() == ISD::BITCAST)
19345         Mask = Mask.getOperand(0);
19346       if (X.getOpcode() == ISD::BITCAST)
19347         X = X.getOperand(0);
19348       if (Y.getOpcode() == ISD::BITCAST)
19349         Y = Y.getOperand(0);
19350
19351       EVT MaskVT = Mask.getValueType();
19352
19353       // Validate that the Mask operand is a vector sra node.
19354       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19355       // there is no psrai.b
19356       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19357       unsigned SraAmt = ~0;
19358       if (Mask.getOpcode() == ISD::SRA) {
19359         SDValue Amt = Mask.getOperand(1);
19360         if (isSplatVector(Amt.getNode())) {
19361           SDValue SclrAmt = Amt->getOperand(0);
19362           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19363             SraAmt = C->getZExtValue();
19364         }
19365       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19366         SDValue SraC = Mask.getOperand(1);
19367         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19368       }
19369       if ((SraAmt + 1) != EltBits)
19370         return SDValue();
19371
19372       SDLoc DL(N);
19373
19374       // Now we know we at least have a plendvb with the mask val.  See if
19375       // we can form a psignb/w/d.
19376       // psign = x.type == y.type == mask.type && y = sub(0, x);
19377       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19378           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19379           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19380         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19381                "Unsupported VT for PSIGN");
19382         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19383         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19384       }
19385       // PBLENDVB only available on SSE 4.1
19386       if (!Subtarget->hasSSE41())
19387         return SDValue();
19388
19389       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19390
19391       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19392       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19393       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19394       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19395       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19396     }
19397   }
19398
19399   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19400     return SDValue();
19401
19402   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19403   MachineFunction &MF = DAG.getMachineFunction();
19404   bool OptForSize = MF.getFunction()->getAttributes().
19405     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19406
19407   // SHLD/SHRD instructions have lower register pressure, but on some
19408   // platforms they have higher latency than the equivalent
19409   // series of shifts/or that would otherwise be generated.
19410   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19411   // have higher latencies and we are not optimizing for size.
19412   if (!OptForSize && Subtarget->isSHLDSlow())
19413     return SDValue();
19414
19415   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19416     std::swap(N0, N1);
19417   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19418     return SDValue();
19419   if (!N0.hasOneUse() || !N1.hasOneUse())
19420     return SDValue();
19421
19422   SDValue ShAmt0 = N0.getOperand(1);
19423   if (ShAmt0.getValueType() != MVT::i8)
19424     return SDValue();
19425   SDValue ShAmt1 = N1.getOperand(1);
19426   if (ShAmt1.getValueType() != MVT::i8)
19427     return SDValue();
19428   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19429     ShAmt0 = ShAmt0.getOperand(0);
19430   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19431     ShAmt1 = ShAmt1.getOperand(0);
19432
19433   SDLoc DL(N);
19434   unsigned Opc = X86ISD::SHLD;
19435   SDValue Op0 = N0.getOperand(0);
19436   SDValue Op1 = N1.getOperand(0);
19437   if (ShAmt0.getOpcode() == ISD::SUB) {
19438     Opc = X86ISD::SHRD;
19439     std::swap(Op0, Op1);
19440     std::swap(ShAmt0, ShAmt1);
19441   }
19442
19443   unsigned Bits = VT.getSizeInBits();
19444   if (ShAmt1.getOpcode() == ISD::SUB) {
19445     SDValue Sum = ShAmt1.getOperand(0);
19446     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19447       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19448       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19449         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19450       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19451         return DAG.getNode(Opc, DL, VT,
19452                            Op0, Op1,
19453                            DAG.getNode(ISD::TRUNCATE, DL,
19454                                        MVT::i8, ShAmt0));
19455     }
19456   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19457     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19458     if (ShAmt0C &&
19459         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19460       return DAG.getNode(Opc, DL, VT,
19461                          N0.getOperand(0), N1.getOperand(0),
19462                          DAG.getNode(ISD::TRUNCATE, DL,
19463                                        MVT::i8, ShAmt0));
19464   }
19465
19466   return SDValue();
19467 }
19468
19469 // Generate NEG and CMOV for integer abs.
19470 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19471   EVT VT = N->getValueType(0);
19472
19473   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19474   // 8-bit integer abs to NEG and CMOV.
19475   if (VT.isInteger() && VT.getSizeInBits() == 8)
19476     return SDValue();
19477
19478   SDValue N0 = N->getOperand(0);
19479   SDValue N1 = N->getOperand(1);
19480   SDLoc DL(N);
19481
19482   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19483   // and change it to SUB and CMOV.
19484   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19485       N0.getOpcode() == ISD::ADD &&
19486       N0.getOperand(1) == N1 &&
19487       N1.getOpcode() == ISD::SRA &&
19488       N1.getOperand(0) == N0.getOperand(0))
19489     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19490       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19491         // Generate SUB & CMOV.
19492         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19493                                   DAG.getConstant(0, VT), N0.getOperand(0));
19494
19495         SDValue Ops[] = { N0.getOperand(0), Neg,
19496                           DAG.getConstant(X86::COND_GE, MVT::i8),
19497                           SDValue(Neg.getNode(), 1) };
19498         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19499       }
19500   return SDValue();
19501 }
19502
19503 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19504 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19505                                  TargetLowering::DAGCombinerInfo &DCI,
19506                                  const X86Subtarget *Subtarget) {
19507   if (DCI.isBeforeLegalizeOps())
19508     return SDValue();
19509
19510   if (Subtarget->hasCMov()) {
19511     SDValue RV = performIntegerAbsCombine(N, DAG);
19512     if (RV.getNode())
19513       return RV;
19514   }
19515
19516   return SDValue();
19517 }
19518
19519 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19520 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19521                                   TargetLowering::DAGCombinerInfo &DCI,
19522                                   const X86Subtarget *Subtarget) {
19523   LoadSDNode *Ld = cast<LoadSDNode>(N);
19524   EVT RegVT = Ld->getValueType(0);
19525   EVT MemVT = Ld->getMemoryVT();
19526   SDLoc dl(Ld);
19527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19528   unsigned RegSz = RegVT.getSizeInBits();
19529
19530   // On Sandybridge unaligned 256bit loads are inefficient.
19531   ISD::LoadExtType Ext = Ld->getExtensionType();
19532   unsigned Alignment = Ld->getAlignment();
19533   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19534   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19535       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19536     unsigned NumElems = RegVT.getVectorNumElements();
19537     if (NumElems < 2)
19538       return SDValue();
19539
19540     SDValue Ptr = Ld->getBasePtr();
19541     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19542
19543     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19544                                   NumElems/2);
19545     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19546                                 Ld->getPointerInfo(), Ld->isVolatile(),
19547                                 Ld->isNonTemporal(), Ld->isInvariant(),
19548                                 Alignment);
19549     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19550     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19551                                 Ld->getPointerInfo(), Ld->isVolatile(),
19552                                 Ld->isNonTemporal(), Ld->isInvariant(),
19553                                 std::min(16U, Alignment));
19554     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19555                              Load1.getValue(1),
19556                              Load2.getValue(1));
19557
19558     SDValue NewVec = DAG.getUNDEF(RegVT);
19559     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19560     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19561     return DCI.CombineTo(N, NewVec, TF, true);
19562   }
19563
19564   // If this is a vector EXT Load then attempt to optimize it using a
19565   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19566   // expansion is still better than scalar code.
19567   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19568   // emit a shuffle and a arithmetic shift.
19569   // TODO: It is possible to support ZExt by zeroing the undef values
19570   // during the shuffle phase or after the shuffle.
19571   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19572       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19573     assert(MemVT != RegVT && "Cannot extend to the same type");
19574     assert(MemVT.isVector() && "Must load a vector from memory");
19575
19576     unsigned NumElems = RegVT.getVectorNumElements();
19577     unsigned MemSz = MemVT.getSizeInBits();
19578     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19579
19580     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19581       return SDValue();
19582
19583     // All sizes must be a power of two.
19584     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19585       return SDValue();
19586
19587     // Attempt to load the original value using scalar loads.
19588     // Find the largest scalar type that divides the total loaded size.
19589     MVT SclrLoadTy = MVT::i8;
19590     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19591          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19592       MVT Tp = (MVT::SimpleValueType)tp;
19593       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19594         SclrLoadTy = Tp;
19595       }
19596     }
19597
19598     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19599     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19600         (64 <= MemSz))
19601       SclrLoadTy = MVT::f64;
19602
19603     // Calculate the number of scalar loads that we need to perform
19604     // in order to load our vector from memory.
19605     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19606     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19607       return SDValue();
19608
19609     unsigned loadRegZize = RegSz;
19610     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19611       loadRegZize /= 2;
19612
19613     // Represent our vector as a sequence of elements which are the
19614     // largest scalar that we can load.
19615     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19616       loadRegZize/SclrLoadTy.getSizeInBits());
19617
19618     // Represent the data using the same element type that is stored in
19619     // memory. In practice, we ''widen'' MemVT.
19620     EVT WideVecVT =
19621           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19622                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19623
19624     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19625       "Invalid vector type");
19626
19627     // We can't shuffle using an illegal type.
19628     if (!TLI.isTypeLegal(WideVecVT))
19629       return SDValue();
19630
19631     SmallVector<SDValue, 8> Chains;
19632     SDValue Ptr = Ld->getBasePtr();
19633     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19634                                         TLI.getPointerTy());
19635     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19636
19637     for (unsigned i = 0; i < NumLoads; ++i) {
19638       // Perform a single load.
19639       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19640                                        Ptr, Ld->getPointerInfo(),
19641                                        Ld->isVolatile(), Ld->isNonTemporal(),
19642                                        Ld->isInvariant(), Ld->getAlignment());
19643       Chains.push_back(ScalarLoad.getValue(1));
19644       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19645       // another round of DAGCombining.
19646       if (i == 0)
19647         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19648       else
19649         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19650                           ScalarLoad, DAG.getIntPtrConstant(i));
19651
19652       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19653     }
19654
19655     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19656
19657     // Bitcast the loaded value to a vector of the original element type, in
19658     // the size of the target vector type.
19659     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19660     unsigned SizeRatio = RegSz/MemSz;
19661
19662     if (Ext == ISD::SEXTLOAD) {
19663       // If we have SSE4.1 we can directly emit a VSEXT node.
19664       if (Subtarget->hasSSE41()) {
19665         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19666         return DCI.CombineTo(N, Sext, TF, true);
19667       }
19668
19669       // Otherwise we'll shuffle the small elements in the high bits of the
19670       // larger type and perform an arithmetic shift. If the shift is not legal
19671       // it's better to scalarize.
19672       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19673         return SDValue();
19674
19675       // Redistribute the loaded elements into the different locations.
19676       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19677       for (unsigned i = 0; i != NumElems; ++i)
19678         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19679
19680       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19681                                            DAG.getUNDEF(WideVecVT),
19682                                            &ShuffleVec[0]);
19683
19684       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19685
19686       // Build the arithmetic shift.
19687       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19688                      MemVT.getVectorElementType().getSizeInBits();
19689       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19690                           DAG.getConstant(Amt, RegVT));
19691
19692       return DCI.CombineTo(N, Shuff, TF, true);
19693     }
19694
19695     // Redistribute the loaded elements into the different locations.
19696     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19697     for (unsigned i = 0; i != NumElems; ++i)
19698       ShuffleVec[i*SizeRatio] = i;
19699
19700     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19701                                          DAG.getUNDEF(WideVecVT),
19702                                          &ShuffleVec[0]);
19703
19704     // Bitcast to the requested type.
19705     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19706     // Replace the original load with the new sequence
19707     // and return the new chain.
19708     return DCI.CombineTo(N, Shuff, TF, true);
19709   }
19710
19711   return SDValue();
19712 }
19713
19714 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19715 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19716                                    const X86Subtarget *Subtarget) {
19717   StoreSDNode *St = cast<StoreSDNode>(N);
19718   EVT VT = St->getValue().getValueType();
19719   EVT StVT = St->getMemoryVT();
19720   SDLoc dl(St);
19721   SDValue StoredVal = St->getOperand(1);
19722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19723
19724   // If we are saving a concatenation of two XMM registers, perform two stores.
19725   // On Sandy Bridge, 256-bit memory operations are executed by two
19726   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19727   // memory  operation.
19728   unsigned Alignment = St->getAlignment();
19729   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19730   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19731       StVT == VT && !IsAligned) {
19732     unsigned NumElems = VT.getVectorNumElements();
19733     if (NumElems < 2)
19734       return SDValue();
19735
19736     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19737     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19738
19739     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19740     SDValue Ptr0 = St->getBasePtr();
19741     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19742
19743     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19744                                 St->getPointerInfo(), St->isVolatile(),
19745                                 St->isNonTemporal(), Alignment);
19746     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19747                                 St->getPointerInfo(), St->isVolatile(),
19748                                 St->isNonTemporal(),
19749                                 std::min(16U, Alignment));
19750     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19751   }
19752
19753   // Optimize trunc store (of multiple scalars) to shuffle and store.
19754   // First, pack all of the elements in one place. Next, store to memory
19755   // in fewer chunks.
19756   if (St->isTruncatingStore() && VT.isVector()) {
19757     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19758     unsigned NumElems = VT.getVectorNumElements();
19759     assert(StVT != VT && "Cannot truncate to the same type");
19760     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19761     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19762
19763     // From, To sizes and ElemCount must be pow of two
19764     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19765     // We are going to use the original vector elt for storing.
19766     // Accumulated smaller vector elements must be a multiple of the store size.
19767     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19768
19769     unsigned SizeRatio  = FromSz / ToSz;
19770
19771     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19772
19773     // Create a type on which we perform the shuffle
19774     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19775             StVT.getScalarType(), NumElems*SizeRatio);
19776
19777     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19778
19779     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19780     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19781     for (unsigned i = 0; i != NumElems; ++i)
19782       ShuffleVec[i] = i * SizeRatio;
19783
19784     // Can't shuffle using an illegal type.
19785     if (!TLI.isTypeLegal(WideVecVT))
19786       return SDValue();
19787
19788     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19789                                          DAG.getUNDEF(WideVecVT),
19790                                          &ShuffleVec[0]);
19791     // At this point all of the data is stored at the bottom of the
19792     // register. We now need to save it to mem.
19793
19794     // Find the largest store unit
19795     MVT StoreType = MVT::i8;
19796     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19797          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19798       MVT Tp = (MVT::SimpleValueType)tp;
19799       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19800         StoreType = Tp;
19801     }
19802
19803     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19804     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19805         (64 <= NumElems * ToSz))
19806       StoreType = MVT::f64;
19807
19808     // Bitcast the original vector into a vector of store-size units
19809     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19810             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19811     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19812     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19813     SmallVector<SDValue, 8> Chains;
19814     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19815                                         TLI.getPointerTy());
19816     SDValue Ptr = St->getBasePtr();
19817
19818     // Perform one or more big stores into memory.
19819     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19820       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19821                                    StoreType, ShuffWide,
19822                                    DAG.getIntPtrConstant(i));
19823       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19824                                 St->getPointerInfo(), St->isVolatile(),
19825                                 St->isNonTemporal(), St->getAlignment());
19826       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19827       Chains.push_back(Ch);
19828     }
19829
19830     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19831   }
19832
19833   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19834   // the FP state in cases where an emms may be missing.
19835   // A preferable solution to the general problem is to figure out the right
19836   // places to insert EMMS.  This qualifies as a quick hack.
19837
19838   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19839   if (VT.getSizeInBits() != 64)
19840     return SDValue();
19841
19842   const Function *F = DAG.getMachineFunction().getFunction();
19843   bool NoImplicitFloatOps = F->getAttributes().
19844     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19845   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19846                      && Subtarget->hasSSE2();
19847   if ((VT.isVector() ||
19848        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19849       isa<LoadSDNode>(St->getValue()) &&
19850       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19851       St->getChain().hasOneUse() && !St->isVolatile()) {
19852     SDNode* LdVal = St->getValue().getNode();
19853     LoadSDNode *Ld = nullptr;
19854     int TokenFactorIndex = -1;
19855     SmallVector<SDValue, 8> Ops;
19856     SDNode* ChainVal = St->getChain().getNode();
19857     // Must be a store of a load.  We currently handle two cases:  the load
19858     // is a direct child, and it's under an intervening TokenFactor.  It is
19859     // possible to dig deeper under nested TokenFactors.
19860     if (ChainVal == LdVal)
19861       Ld = cast<LoadSDNode>(St->getChain());
19862     else if (St->getValue().hasOneUse() &&
19863              ChainVal->getOpcode() == ISD::TokenFactor) {
19864       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19865         if (ChainVal->getOperand(i).getNode() == LdVal) {
19866           TokenFactorIndex = i;
19867           Ld = cast<LoadSDNode>(St->getValue());
19868         } else
19869           Ops.push_back(ChainVal->getOperand(i));
19870       }
19871     }
19872
19873     if (!Ld || !ISD::isNormalLoad(Ld))
19874       return SDValue();
19875
19876     // If this is not the MMX case, i.e. we are just turning i64 load/store
19877     // into f64 load/store, avoid the transformation if there are multiple
19878     // uses of the loaded value.
19879     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19880       return SDValue();
19881
19882     SDLoc LdDL(Ld);
19883     SDLoc StDL(N);
19884     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19885     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19886     // pair instead.
19887     if (Subtarget->is64Bit() || F64IsLegal) {
19888       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19889       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19890                                   Ld->getPointerInfo(), Ld->isVolatile(),
19891                                   Ld->isNonTemporal(), Ld->isInvariant(),
19892                                   Ld->getAlignment());
19893       SDValue NewChain = NewLd.getValue(1);
19894       if (TokenFactorIndex != -1) {
19895         Ops.push_back(NewChain);
19896         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19897       }
19898       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19899                           St->getPointerInfo(),
19900                           St->isVolatile(), St->isNonTemporal(),
19901                           St->getAlignment());
19902     }
19903
19904     // Otherwise, lower to two pairs of 32-bit loads / stores.
19905     SDValue LoAddr = Ld->getBasePtr();
19906     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19907                                  DAG.getConstant(4, MVT::i32));
19908
19909     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19910                                Ld->getPointerInfo(),
19911                                Ld->isVolatile(), Ld->isNonTemporal(),
19912                                Ld->isInvariant(), Ld->getAlignment());
19913     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19914                                Ld->getPointerInfo().getWithOffset(4),
19915                                Ld->isVolatile(), Ld->isNonTemporal(),
19916                                Ld->isInvariant(),
19917                                MinAlign(Ld->getAlignment(), 4));
19918
19919     SDValue NewChain = LoLd.getValue(1);
19920     if (TokenFactorIndex != -1) {
19921       Ops.push_back(LoLd);
19922       Ops.push_back(HiLd);
19923       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19924     }
19925
19926     LoAddr = St->getBasePtr();
19927     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19928                          DAG.getConstant(4, MVT::i32));
19929
19930     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19931                                 St->getPointerInfo(),
19932                                 St->isVolatile(), St->isNonTemporal(),
19933                                 St->getAlignment());
19934     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19935                                 St->getPointerInfo().getWithOffset(4),
19936                                 St->isVolatile(),
19937                                 St->isNonTemporal(),
19938                                 MinAlign(St->getAlignment(), 4));
19939     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19940   }
19941   return SDValue();
19942 }
19943
19944 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19945 /// and return the operands for the horizontal operation in LHS and RHS.  A
19946 /// horizontal operation performs the binary operation on successive elements
19947 /// of its first operand, then on successive elements of its second operand,
19948 /// returning the resulting values in a vector.  For example, if
19949 ///   A = < float a0, float a1, float a2, float a3 >
19950 /// and
19951 ///   B = < float b0, float b1, float b2, float b3 >
19952 /// then the result of doing a horizontal operation on A and B is
19953 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19954 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19955 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19956 /// set to A, RHS to B, and the routine returns 'true'.
19957 /// Note that the binary operation should have the property that if one of the
19958 /// operands is UNDEF then the result is UNDEF.
19959 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19960   // Look for the following pattern: if
19961   //   A = < float a0, float a1, float a2, float a3 >
19962   //   B = < float b0, float b1, float b2, float b3 >
19963   // and
19964   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19965   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19966   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19967   // which is A horizontal-op B.
19968
19969   // At least one of the operands should be a vector shuffle.
19970   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19971       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19972     return false;
19973
19974   MVT VT = LHS.getSimpleValueType();
19975
19976   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19977          "Unsupported vector type for horizontal add/sub");
19978
19979   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19980   // operate independently on 128-bit lanes.
19981   unsigned NumElts = VT.getVectorNumElements();
19982   unsigned NumLanes = VT.getSizeInBits()/128;
19983   unsigned NumLaneElts = NumElts / NumLanes;
19984   assert((NumLaneElts % 2 == 0) &&
19985          "Vector type should have an even number of elements in each lane");
19986   unsigned HalfLaneElts = NumLaneElts/2;
19987
19988   // View LHS in the form
19989   //   LHS = VECTOR_SHUFFLE A, B, LMask
19990   // If LHS is not a shuffle then pretend it is the shuffle
19991   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19992   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19993   // type VT.
19994   SDValue A, B;
19995   SmallVector<int, 16> LMask(NumElts);
19996   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19997     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19998       A = LHS.getOperand(0);
19999     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20000       B = LHS.getOperand(1);
20001     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20002     std::copy(Mask.begin(), Mask.end(), LMask.begin());
20003   } else {
20004     if (LHS.getOpcode() != ISD::UNDEF)
20005       A = LHS;
20006     for (unsigned i = 0; i != NumElts; ++i)
20007       LMask[i] = i;
20008   }
20009
20010   // Likewise, view RHS in the form
20011   //   RHS = VECTOR_SHUFFLE C, D, RMask
20012   SDValue C, D;
20013   SmallVector<int, 16> RMask(NumElts);
20014   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20015     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20016       C = RHS.getOperand(0);
20017     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20018       D = RHS.getOperand(1);
20019     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20020     std::copy(Mask.begin(), Mask.end(), RMask.begin());
20021   } else {
20022     if (RHS.getOpcode() != ISD::UNDEF)
20023       C = RHS;
20024     for (unsigned i = 0; i != NumElts; ++i)
20025       RMask[i] = i;
20026   }
20027
20028   // Check that the shuffles are both shuffling the same vectors.
20029   if (!(A == C && B == D) && !(A == D && B == C))
20030     return false;
20031
20032   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20033   if (!A.getNode() && !B.getNode())
20034     return false;
20035
20036   // If A and B occur in reverse order in RHS, then "swap" them (which means
20037   // rewriting the mask).
20038   if (A != C)
20039     CommuteVectorShuffleMask(RMask, NumElts);
20040
20041   // At this point LHS and RHS are equivalent to
20042   //   LHS = VECTOR_SHUFFLE A, B, LMask
20043   //   RHS = VECTOR_SHUFFLE A, B, RMask
20044   // Check that the masks correspond to performing a horizontal operation.
20045   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20046     for (unsigned i = 0; i != NumLaneElts; ++i) {
20047       int LIdx = LMask[i+l], RIdx = RMask[i+l];
20048
20049       // Ignore any UNDEF components.
20050       if (LIdx < 0 || RIdx < 0 ||
20051           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20052           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20053         continue;
20054
20055       // Check that successive elements are being operated on.  If not, this is
20056       // not a horizontal operation.
20057       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20058       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20059       if (!(LIdx == Index && RIdx == Index + 1) &&
20060           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20061         return false;
20062     }
20063   }
20064
20065   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20066   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20067   return true;
20068 }
20069
20070 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20071 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20072                                   const X86Subtarget *Subtarget) {
20073   EVT VT = N->getValueType(0);
20074   SDValue LHS = N->getOperand(0);
20075   SDValue RHS = N->getOperand(1);
20076
20077   // Try to synthesize horizontal adds from adds of shuffles.
20078   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20079        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20080       isHorizontalBinOp(LHS, RHS, true))
20081     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20082   return SDValue();
20083 }
20084
20085 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20086 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20087                                   const X86Subtarget *Subtarget) {
20088   EVT VT = N->getValueType(0);
20089   SDValue LHS = N->getOperand(0);
20090   SDValue RHS = N->getOperand(1);
20091
20092   // Try to synthesize horizontal subs from subs of shuffles.
20093   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20094        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20095       isHorizontalBinOp(LHS, RHS, false))
20096     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20097   return SDValue();
20098 }
20099
20100 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20101 /// X86ISD::FXOR nodes.
20102 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20103   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20104   // F[X]OR(0.0, x) -> x
20105   // F[X]OR(x, 0.0) -> x
20106   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20107     if (C->getValueAPF().isPosZero())
20108       return N->getOperand(1);
20109   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20110     if (C->getValueAPF().isPosZero())
20111       return N->getOperand(0);
20112   return SDValue();
20113 }
20114
20115 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20116 /// X86ISD::FMAX nodes.
20117 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20118   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20119
20120   // Only perform optimizations if UnsafeMath is used.
20121   if (!DAG.getTarget().Options.UnsafeFPMath)
20122     return SDValue();
20123
20124   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20125   // into FMINC and FMAXC, which are Commutative operations.
20126   unsigned NewOp = 0;
20127   switch (N->getOpcode()) {
20128     default: llvm_unreachable("unknown opcode");
20129     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
20130     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
20131   }
20132
20133   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20134                      N->getOperand(0), N->getOperand(1));
20135 }
20136
20137 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20138 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20139   // FAND(0.0, x) -> 0.0
20140   // FAND(x, 0.0) -> 0.0
20141   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20142     if (C->getValueAPF().isPosZero())
20143       return N->getOperand(0);
20144   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20145     if (C->getValueAPF().isPosZero())
20146       return N->getOperand(1);
20147   return SDValue();
20148 }
20149
20150 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20151 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20152   // FANDN(x, 0.0) -> 0.0
20153   // FANDN(0.0, x) -> x
20154   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20155     if (C->getValueAPF().isPosZero())
20156       return N->getOperand(1);
20157   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20158     if (C->getValueAPF().isPosZero())
20159       return N->getOperand(1);
20160   return SDValue();
20161 }
20162
20163 static SDValue PerformBTCombine(SDNode *N,
20164                                 SelectionDAG &DAG,
20165                                 TargetLowering::DAGCombinerInfo &DCI) {
20166   // BT ignores high bits in the bit index operand.
20167   SDValue Op1 = N->getOperand(1);
20168   if (Op1.hasOneUse()) {
20169     unsigned BitWidth = Op1.getValueSizeInBits();
20170     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20171     APInt KnownZero, KnownOne;
20172     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20173                                           !DCI.isBeforeLegalizeOps());
20174     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20175     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20176         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20177       DCI.CommitTargetLoweringOpt(TLO);
20178   }
20179   return SDValue();
20180 }
20181
20182 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20183   SDValue Op = N->getOperand(0);
20184   if (Op.getOpcode() == ISD::BITCAST)
20185     Op = Op.getOperand(0);
20186   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20187   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20188       VT.getVectorElementType().getSizeInBits() ==
20189       OpVT.getVectorElementType().getSizeInBits()) {
20190     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20191   }
20192   return SDValue();
20193 }
20194
20195 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20196                                                const X86Subtarget *Subtarget) {
20197   EVT VT = N->getValueType(0);
20198   if (!VT.isVector())
20199     return SDValue();
20200
20201   SDValue N0 = N->getOperand(0);
20202   SDValue N1 = N->getOperand(1);
20203   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20204   SDLoc dl(N);
20205
20206   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20207   // both SSE and AVX2 since there is no sign-extended shift right
20208   // operation on a vector with 64-bit elements.
20209   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20210   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20211   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20212       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20213     SDValue N00 = N0.getOperand(0);
20214
20215     // EXTLOAD has a better solution on AVX2,
20216     // it may be replaced with X86ISD::VSEXT node.
20217     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20218       if (!ISD::isNormalLoad(N00.getNode()))
20219         return SDValue();
20220
20221     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20222         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20223                                   N00, N1);
20224       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20225     }
20226   }
20227   return SDValue();
20228 }
20229
20230 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20231                                   TargetLowering::DAGCombinerInfo &DCI,
20232                                   const X86Subtarget *Subtarget) {
20233   if (!DCI.isBeforeLegalizeOps())
20234     return SDValue();
20235
20236   if (!Subtarget->hasFp256())
20237     return SDValue();
20238
20239   EVT VT = N->getValueType(0);
20240   if (VT.isVector() && VT.getSizeInBits() == 256) {
20241     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20242     if (R.getNode())
20243       return R;
20244   }
20245
20246   return SDValue();
20247 }
20248
20249 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20250                                  const X86Subtarget* Subtarget) {
20251   SDLoc dl(N);
20252   EVT VT = N->getValueType(0);
20253
20254   // Let legalize expand this if it isn't a legal type yet.
20255   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20256     return SDValue();
20257
20258   EVT ScalarVT = VT.getScalarType();
20259   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20260       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20261     return SDValue();
20262
20263   SDValue A = N->getOperand(0);
20264   SDValue B = N->getOperand(1);
20265   SDValue C = N->getOperand(2);
20266
20267   bool NegA = (A.getOpcode() == ISD::FNEG);
20268   bool NegB = (B.getOpcode() == ISD::FNEG);
20269   bool NegC = (C.getOpcode() == ISD::FNEG);
20270
20271   // Negative multiplication when NegA xor NegB
20272   bool NegMul = (NegA != NegB);
20273   if (NegA)
20274     A = A.getOperand(0);
20275   if (NegB)
20276     B = B.getOperand(0);
20277   if (NegC)
20278     C = C.getOperand(0);
20279
20280   unsigned Opcode;
20281   if (!NegMul)
20282     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20283   else
20284     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20285
20286   return DAG.getNode(Opcode, dl, VT, A, B, C);
20287 }
20288
20289 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20290                                   TargetLowering::DAGCombinerInfo &DCI,
20291                                   const X86Subtarget *Subtarget) {
20292   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20293   //           (and (i32 x86isd::setcc_carry), 1)
20294   // This eliminates the zext. This transformation is necessary because
20295   // ISD::SETCC is always legalized to i8.
20296   SDLoc dl(N);
20297   SDValue N0 = N->getOperand(0);
20298   EVT VT = N->getValueType(0);
20299
20300   if (N0.getOpcode() == ISD::AND &&
20301       N0.hasOneUse() &&
20302       N0.getOperand(0).hasOneUse()) {
20303     SDValue N00 = N0.getOperand(0);
20304     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20305       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20306       if (!C || C->getZExtValue() != 1)
20307         return SDValue();
20308       return DAG.getNode(ISD::AND, dl, VT,
20309                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20310                                      N00.getOperand(0), N00.getOperand(1)),
20311                          DAG.getConstant(1, VT));
20312     }
20313   }
20314
20315   if (N0.getOpcode() == ISD::TRUNCATE &&
20316       N0.hasOneUse() &&
20317       N0.getOperand(0).hasOneUse()) {
20318     SDValue N00 = N0.getOperand(0);
20319     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20320       return DAG.getNode(ISD::AND, dl, VT,
20321                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20322                                      N00.getOperand(0), N00.getOperand(1)),
20323                          DAG.getConstant(1, VT));
20324     }
20325   }
20326   if (VT.is256BitVector()) {
20327     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20328     if (R.getNode())
20329       return R;
20330   }
20331
20332   return SDValue();
20333 }
20334
20335 // Optimize x == -y --> x+y == 0
20336 //          x != -y --> x+y != 0
20337 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20338                                       const X86Subtarget* Subtarget) {
20339   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20340   SDValue LHS = N->getOperand(0);
20341   SDValue RHS = N->getOperand(1);
20342   EVT VT = N->getValueType(0);
20343   SDLoc DL(N);
20344
20345   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20346     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20347       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20348         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20349                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20350         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20351                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20352       }
20353   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20354     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20355       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20356         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20357                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20358         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20359                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20360       }
20361
20362   if (VT.getScalarType() == MVT::i1) {
20363     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20364       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20365     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20366     if (!IsSEXT0 && !IsVZero0)
20367       return SDValue();
20368     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20369       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20370     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20371
20372     if (!IsSEXT1 && !IsVZero1)
20373       return SDValue();
20374
20375     if (IsSEXT0 && IsVZero1) {
20376       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20377       if (CC == ISD::SETEQ)
20378         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20379       return LHS.getOperand(0);
20380     }
20381     if (IsSEXT1 && IsVZero0) {
20382       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20383       if (CC == ISD::SETEQ)
20384         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20385       return RHS.getOperand(0);
20386     }
20387   }
20388
20389   return SDValue();
20390 }
20391
20392 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20393                                       const X86Subtarget *Subtarget) {
20394   SDLoc dl(N);
20395   MVT VT = N->getOperand(1)->getSimpleValueType(0);
20396   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20397          "X86insertps is only defined for v4x32");
20398
20399   SDValue Ld = N->getOperand(1);
20400   if (MayFoldLoad(Ld)) {
20401     // Extract the countS bits from the immediate so we can get the proper
20402     // address when narrowing the vector load to a specific element.
20403     // When the second source op is a memory address, interps doesn't use
20404     // countS and just gets an f32 from that address.
20405     unsigned DestIndex =
20406         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20407     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20408   } else
20409     return SDValue();
20410
20411   // Create this as a scalar to vector to match the instruction pattern.
20412   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20413   // countS bits are ignored when loading from memory on insertps, which
20414   // means we don't need to explicitly set them to 0.
20415   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20416                      LoadScalarToVector, N->getOperand(2));
20417 }
20418
20419 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20420 // as "sbb reg,reg", since it can be extended without zext and produces
20421 // an all-ones bit which is more useful than 0/1 in some cases.
20422 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20423                                MVT VT) {
20424   if (VT == MVT::i8)
20425     return DAG.getNode(ISD::AND, DL, VT,
20426                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20427                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20428                        DAG.getConstant(1, VT));
20429   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20430   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20431                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20432                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20433 }
20434
20435 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20436 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20437                                    TargetLowering::DAGCombinerInfo &DCI,
20438                                    const X86Subtarget *Subtarget) {
20439   SDLoc DL(N);
20440   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20441   SDValue EFLAGS = N->getOperand(1);
20442
20443   if (CC == X86::COND_A) {
20444     // Try to convert COND_A into COND_B in an attempt to facilitate
20445     // materializing "setb reg".
20446     //
20447     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20448     // cannot take an immediate as its first operand.
20449     //
20450     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20451         EFLAGS.getValueType().isInteger() &&
20452         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20453       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20454                                    EFLAGS.getNode()->getVTList(),
20455                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20456       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20457       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20458     }
20459   }
20460
20461   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20462   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20463   // cases.
20464   if (CC == X86::COND_B)
20465     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20466
20467   SDValue Flags;
20468
20469   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20470   if (Flags.getNode()) {
20471     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20472     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20473   }
20474
20475   return SDValue();
20476 }
20477
20478 // Optimize branch condition evaluation.
20479 //
20480 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20481                                     TargetLowering::DAGCombinerInfo &DCI,
20482                                     const X86Subtarget *Subtarget) {
20483   SDLoc DL(N);
20484   SDValue Chain = N->getOperand(0);
20485   SDValue Dest = N->getOperand(1);
20486   SDValue EFLAGS = N->getOperand(3);
20487   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20488
20489   SDValue Flags;
20490
20491   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20492   if (Flags.getNode()) {
20493     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20494     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20495                        Flags);
20496   }
20497
20498   return SDValue();
20499 }
20500
20501 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20502                                         const X86TargetLowering *XTLI) {
20503   SDValue Op0 = N->getOperand(0);
20504   EVT InVT = Op0->getValueType(0);
20505
20506   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20507   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20508     SDLoc dl(N);
20509     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20510     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20511     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20512   }
20513
20514   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20515   // a 32-bit target where SSE doesn't support i64->FP operations.
20516   if (Op0.getOpcode() == ISD::LOAD) {
20517     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20518     EVT VT = Ld->getValueType(0);
20519     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20520         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20521         !XTLI->getSubtarget()->is64Bit() &&
20522         VT == MVT::i64) {
20523       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20524                                           Ld->getChain(), Op0, DAG);
20525       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20526       return FILDChain;
20527     }
20528   }
20529   return SDValue();
20530 }
20531
20532 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20533 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20534                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20535   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20536   // the result is either zero or one (depending on the input carry bit).
20537   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20538   if (X86::isZeroNode(N->getOperand(0)) &&
20539       X86::isZeroNode(N->getOperand(1)) &&
20540       // We don't have a good way to replace an EFLAGS use, so only do this when
20541       // dead right now.
20542       SDValue(N, 1).use_empty()) {
20543     SDLoc DL(N);
20544     EVT VT = N->getValueType(0);
20545     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20546     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20547                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20548                                            DAG.getConstant(X86::COND_B,MVT::i8),
20549                                            N->getOperand(2)),
20550                                DAG.getConstant(1, VT));
20551     return DCI.CombineTo(N, Res1, CarryOut);
20552   }
20553
20554   return SDValue();
20555 }
20556
20557 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20558 //      (add Y, (setne X, 0)) -> sbb -1, Y
20559 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20560 //      (sub (setne X, 0), Y) -> adc -1, Y
20561 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20562   SDLoc DL(N);
20563
20564   // Look through ZExts.
20565   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20566   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20567     return SDValue();
20568
20569   SDValue SetCC = Ext.getOperand(0);
20570   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20571     return SDValue();
20572
20573   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20574   if (CC != X86::COND_E && CC != X86::COND_NE)
20575     return SDValue();
20576
20577   SDValue Cmp = SetCC.getOperand(1);
20578   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20579       !X86::isZeroNode(Cmp.getOperand(1)) ||
20580       !Cmp.getOperand(0).getValueType().isInteger())
20581     return SDValue();
20582
20583   SDValue CmpOp0 = Cmp.getOperand(0);
20584   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20585                                DAG.getConstant(1, CmpOp0.getValueType()));
20586
20587   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20588   if (CC == X86::COND_NE)
20589     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20590                        DL, OtherVal.getValueType(), OtherVal,
20591                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20592   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20593                      DL, OtherVal.getValueType(), OtherVal,
20594                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20595 }
20596
20597 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20598 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20599                                  const X86Subtarget *Subtarget) {
20600   EVT VT = N->getValueType(0);
20601   SDValue Op0 = N->getOperand(0);
20602   SDValue Op1 = N->getOperand(1);
20603
20604   // Try to synthesize horizontal adds from adds of shuffles.
20605   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20606        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20607       isHorizontalBinOp(Op0, Op1, true))
20608     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20609
20610   return OptimizeConditionalInDecrement(N, DAG);
20611 }
20612
20613 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20614                                  const X86Subtarget *Subtarget) {
20615   SDValue Op0 = N->getOperand(0);
20616   SDValue Op1 = N->getOperand(1);
20617
20618   // X86 can't encode an immediate LHS of a sub. See if we can push the
20619   // negation into a preceding instruction.
20620   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20621     // If the RHS of the sub is a XOR with one use and a constant, invert the
20622     // immediate. Then add one to the LHS of the sub so we can turn
20623     // X-Y -> X+~Y+1, saving one register.
20624     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20625         isa<ConstantSDNode>(Op1.getOperand(1))) {
20626       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20627       EVT VT = Op0.getValueType();
20628       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20629                                    Op1.getOperand(0),
20630                                    DAG.getConstant(~XorC, VT));
20631       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20632                          DAG.getConstant(C->getAPIntValue()+1, VT));
20633     }
20634   }
20635
20636   // Try to synthesize horizontal adds from adds of shuffles.
20637   EVT VT = N->getValueType(0);
20638   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20639        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20640       isHorizontalBinOp(Op0, Op1, true))
20641     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20642
20643   return OptimizeConditionalInDecrement(N, DAG);
20644 }
20645
20646 /// performVZEXTCombine - Performs build vector combines
20647 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20648                                         TargetLowering::DAGCombinerInfo &DCI,
20649                                         const X86Subtarget *Subtarget) {
20650   // (vzext (bitcast (vzext (x)) -> (vzext x)
20651   SDValue In = N->getOperand(0);
20652   while (In.getOpcode() == ISD::BITCAST)
20653     In = In.getOperand(0);
20654
20655   if (In.getOpcode() != X86ISD::VZEXT)
20656     return SDValue();
20657
20658   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20659                      In.getOperand(0));
20660 }
20661
20662 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20663                                              DAGCombinerInfo &DCI) const {
20664   SelectionDAG &DAG = DCI.DAG;
20665   switch (N->getOpcode()) {
20666   default: break;
20667   case ISD::EXTRACT_VECTOR_ELT:
20668     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20669   case ISD::VSELECT:
20670   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20671   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20672   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20673   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20674   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20675   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20676   case ISD::SHL:
20677   case ISD::SRA:
20678   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20679   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20680   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20681   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20682   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20683   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20684   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20685   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20686   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20687   case X86ISD::FXOR:
20688   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20689   case X86ISD::FMIN:
20690   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20691   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20692   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20693   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20694   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20695   case ISD::ANY_EXTEND:
20696   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20697   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20698   case ISD::SIGN_EXTEND_INREG:
20699     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20700   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20701   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20702   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20703   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20704   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20705   case X86ISD::SHUFP:       // Handle all target specific shuffles
20706   case X86ISD::PALIGNR:
20707   case X86ISD::UNPCKH:
20708   case X86ISD::UNPCKL:
20709   case X86ISD::MOVHLPS:
20710   case X86ISD::MOVLHPS:
20711   case X86ISD::PSHUFD:
20712   case X86ISD::PSHUFHW:
20713   case X86ISD::PSHUFLW:
20714   case X86ISD::MOVSS:
20715   case X86ISD::MOVSD:
20716   case X86ISD::VPERMILP:
20717   case X86ISD::VPERM2X128:
20718   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20719   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20720   case ISD::INTRINSIC_WO_CHAIN:
20721     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20722   case X86ISD::INSERTPS:
20723     return PerformINSERTPSCombine(N, DAG, Subtarget);
20724   }
20725
20726   return SDValue();
20727 }
20728
20729 /// isTypeDesirableForOp - Return true if the target has native support for
20730 /// the specified value type and it is 'desirable' to use the type for the
20731 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20732 /// instruction encodings are longer and some i16 instructions are slow.
20733 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20734   if (!isTypeLegal(VT))
20735     return false;
20736   if (VT != MVT::i16)
20737     return true;
20738
20739   switch (Opc) {
20740   default:
20741     return true;
20742   case ISD::LOAD:
20743   case ISD::SIGN_EXTEND:
20744   case ISD::ZERO_EXTEND:
20745   case ISD::ANY_EXTEND:
20746   case ISD::SHL:
20747   case ISD::SRL:
20748   case ISD::SUB:
20749   case ISD::ADD:
20750   case ISD::MUL:
20751   case ISD::AND:
20752   case ISD::OR:
20753   case ISD::XOR:
20754     return false;
20755   }
20756 }
20757
20758 /// IsDesirableToPromoteOp - This method query the target whether it is
20759 /// beneficial for dag combiner to promote the specified node. If true, it
20760 /// should return the desired promotion type by reference.
20761 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20762   EVT VT = Op.getValueType();
20763   if (VT != MVT::i16)
20764     return false;
20765
20766   bool Promote = false;
20767   bool Commute = false;
20768   switch (Op.getOpcode()) {
20769   default: break;
20770   case ISD::LOAD: {
20771     LoadSDNode *LD = cast<LoadSDNode>(Op);
20772     // If the non-extending load has a single use and it's not live out, then it
20773     // might be folded.
20774     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20775                                                      Op.hasOneUse()*/) {
20776       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20777              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20778         // The only case where we'd want to promote LOAD (rather then it being
20779         // promoted as an operand is when it's only use is liveout.
20780         if (UI->getOpcode() != ISD::CopyToReg)
20781           return false;
20782       }
20783     }
20784     Promote = true;
20785     break;
20786   }
20787   case ISD::SIGN_EXTEND:
20788   case ISD::ZERO_EXTEND:
20789   case ISD::ANY_EXTEND:
20790     Promote = true;
20791     break;
20792   case ISD::SHL:
20793   case ISD::SRL: {
20794     SDValue N0 = Op.getOperand(0);
20795     // Look out for (store (shl (load), x)).
20796     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20797       return false;
20798     Promote = true;
20799     break;
20800   }
20801   case ISD::ADD:
20802   case ISD::MUL:
20803   case ISD::AND:
20804   case ISD::OR:
20805   case ISD::XOR:
20806     Commute = true;
20807     // fallthrough
20808   case ISD::SUB: {
20809     SDValue N0 = Op.getOperand(0);
20810     SDValue N1 = Op.getOperand(1);
20811     if (!Commute && MayFoldLoad(N1))
20812       return false;
20813     // Avoid disabling potential load folding opportunities.
20814     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20815       return false;
20816     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20817       return false;
20818     Promote = true;
20819   }
20820   }
20821
20822   PVT = MVT::i32;
20823   return Promote;
20824 }
20825
20826 //===----------------------------------------------------------------------===//
20827 //                           X86 Inline Assembly Support
20828 //===----------------------------------------------------------------------===//
20829
20830 namespace {
20831   // Helper to match a string separated by whitespace.
20832   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20833     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20834
20835     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20836       StringRef piece(*args[i]);
20837       if (!s.startswith(piece)) // Check if the piece matches.
20838         return false;
20839
20840       s = s.substr(piece.size());
20841       StringRef::size_type pos = s.find_first_not_of(" \t");
20842       if (pos == 0) // We matched a prefix.
20843         return false;
20844
20845       s = s.substr(pos);
20846     }
20847
20848     return s.empty();
20849   }
20850   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20851 }
20852
20853 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20854
20855   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20856     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20857         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20858         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20859
20860       if (AsmPieces.size() == 3)
20861         return true;
20862       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20863         return true;
20864     }
20865   }
20866   return false;
20867 }
20868
20869 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20870   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20871
20872   std::string AsmStr = IA->getAsmString();
20873
20874   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20875   if (!Ty || Ty->getBitWidth() % 16 != 0)
20876     return false;
20877
20878   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20879   SmallVector<StringRef, 4> AsmPieces;
20880   SplitString(AsmStr, AsmPieces, ";\n");
20881
20882   switch (AsmPieces.size()) {
20883   default: return false;
20884   case 1:
20885     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20886     // we will turn this bswap into something that will be lowered to logical
20887     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20888     // lower so don't worry about this.
20889     // bswap $0
20890     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20891         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20892         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20893         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20894         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20895         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20896       // No need to check constraints, nothing other than the equivalent of
20897       // "=r,0" would be valid here.
20898       return IntrinsicLowering::LowerToByteSwap(CI);
20899     }
20900
20901     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20902     if (CI->getType()->isIntegerTy(16) &&
20903         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20904         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20905          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20906       AsmPieces.clear();
20907       const std::string &ConstraintsStr = IA->getConstraintString();
20908       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20909       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20910       if (clobbersFlagRegisters(AsmPieces))
20911         return IntrinsicLowering::LowerToByteSwap(CI);
20912     }
20913     break;
20914   case 3:
20915     if (CI->getType()->isIntegerTy(32) &&
20916         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20917         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20918         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20919         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20920       AsmPieces.clear();
20921       const std::string &ConstraintsStr = IA->getConstraintString();
20922       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20923       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20924       if (clobbersFlagRegisters(AsmPieces))
20925         return IntrinsicLowering::LowerToByteSwap(CI);
20926     }
20927
20928     if (CI->getType()->isIntegerTy(64)) {
20929       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20930       if (Constraints.size() >= 2 &&
20931           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20932           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20933         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20934         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20935             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20936             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20937           return IntrinsicLowering::LowerToByteSwap(CI);
20938       }
20939     }
20940     break;
20941   }
20942   return false;
20943 }
20944
20945 /// getConstraintType - Given a constraint letter, return the type of
20946 /// constraint it is for this target.
20947 X86TargetLowering::ConstraintType
20948 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20949   if (Constraint.size() == 1) {
20950     switch (Constraint[0]) {
20951     case 'R':
20952     case 'q':
20953     case 'Q':
20954     case 'f':
20955     case 't':
20956     case 'u':
20957     case 'y':
20958     case 'x':
20959     case 'Y':
20960     case 'l':
20961       return C_RegisterClass;
20962     case 'a':
20963     case 'b':
20964     case 'c':
20965     case 'd':
20966     case 'S':
20967     case 'D':
20968     case 'A':
20969       return C_Register;
20970     case 'I':
20971     case 'J':
20972     case 'K':
20973     case 'L':
20974     case 'M':
20975     case 'N':
20976     case 'G':
20977     case 'C':
20978     case 'e':
20979     case 'Z':
20980       return C_Other;
20981     default:
20982       break;
20983     }
20984   }
20985   return TargetLowering::getConstraintType(Constraint);
20986 }
20987
20988 /// Examine constraint type and operand type and determine a weight value.
20989 /// This object must already have been set up with the operand type
20990 /// and the current alternative constraint selected.
20991 TargetLowering::ConstraintWeight
20992   X86TargetLowering::getSingleConstraintMatchWeight(
20993     AsmOperandInfo &info, const char *constraint) const {
20994   ConstraintWeight weight = CW_Invalid;
20995   Value *CallOperandVal = info.CallOperandVal;
20996     // If we don't have a value, we can't do a match,
20997     // but allow it at the lowest weight.
20998   if (!CallOperandVal)
20999     return CW_Default;
21000   Type *type = CallOperandVal->getType();
21001   // Look at the constraint type.
21002   switch (*constraint) {
21003   default:
21004     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21005   case 'R':
21006   case 'q':
21007   case 'Q':
21008   case 'a':
21009   case 'b':
21010   case 'c':
21011   case 'd':
21012   case 'S':
21013   case 'D':
21014   case 'A':
21015     if (CallOperandVal->getType()->isIntegerTy())
21016       weight = CW_SpecificReg;
21017     break;
21018   case 'f':
21019   case 't':
21020   case 'u':
21021     if (type->isFloatingPointTy())
21022       weight = CW_SpecificReg;
21023     break;
21024   case 'y':
21025     if (type->isX86_MMXTy() && Subtarget->hasMMX())
21026       weight = CW_SpecificReg;
21027     break;
21028   case 'x':
21029   case 'Y':
21030     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21031         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21032       weight = CW_Register;
21033     break;
21034   case 'I':
21035     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21036       if (C->getZExtValue() <= 31)
21037         weight = CW_Constant;
21038     }
21039     break;
21040   case 'J':
21041     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21042       if (C->getZExtValue() <= 63)
21043         weight = CW_Constant;
21044     }
21045     break;
21046   case 'K':
21047     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21048       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21049         weight = CW_Constant;
21050     }
21051     break;
21052   case 'L':
21053     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21054       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21055         weight = CW_Constant;
21056     }
21057     break;
21058   case 'M':
21059     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21060       if (C->getZExtValue() <= 3)
21061         weight = CW_Constant;
21062     }
21063     break;
21064   case 'N':
21065     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21066       if (C->getZExtValue() <= 0xff)
21067         weight = CW_Constant;
21068     }
21069     break;
21070   case 'G':
21071   case 'C':
21072     if (dyn_cast<ConstantFP>(CallOperandVal)) {
21073       weight = CW_Constant;
21074     }
21075     break;
21076   case 'e':
21077     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21078       if ((C->getSExtValue() >= -0x80000000LL) &&
21079           (C->getSExtValue() <= 0x7fffffffLL))
21080         weight = CW_Constant;
21081     }
21082     break;
21083   case 'Z':
21084     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21085       if (C->getZExtValue() <= 0xffffffff)
21086         weight = CW_Constant;
21087     }
21088     break;
21089   }
21090   return weight;
21091 }
21092
21093 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21094 /// with another that has more specific requirements based on the type of the
21095 /// corresponding operand.
21096 const char *X86TargetLowering::
21097 LowerXConstraint(EVT ConstraintVT) const {
21098   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21099   // 'f' like normal targets.
21100   if (ConstraintVT.isFloatingPoint()) {
21101     if (Subtarget->hasSSE2())
21102       return "Y";
21103     if (Subtarget->hasSSE1())
21104       return "x";
21105   }
21106
21107   return TargetLowering::LowerXConstraint(ConstraintVT);
21108 }
21109
21110 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21111 /// vector.  If it is invalid, don't add anything to Ops.
21112 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21113                                                      std::string &Constraint,
21114                                                      std::vector<SDValue>&Ops,
21115                                                      SelectionDAG &DAG) const {
21116   SDValue Result;
21117
21118   // Only support length 1 constraints for now.
21119   if (Constraint.length() > 1) return;
21120
21121   char ConstraintLetter = Constraint[0];
21122   switch (ConstraintLetter) {
21123   default: break;
21124   case 'I':
21125     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21126       if (C->getZExtValue() <= 31) {
21127         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21128         break;
21129       }
21130     }
21131     return;
21132   case 'J':
21133     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21134       if (C->getZExtValue() <= 63) {
21135         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21136         break;
21137       }
21138     }
21139     return;
21140   case 'K':
21141     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21142       if (isInt<8>(C->getSExtValue())) {
21143         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21144         break;
21145       }
21146     }
21147     return;
21148   case 'N':
21149     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21150       if (C->getZExtValue() <= 255) {
21151         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21152         break;
21153       }
21154     }
21155     return;
21156   case 'e': {
21157     // 32-bit signed value
21158     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21159       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21160                                            C->getSExtValue())) {
21161         // Widen to 64 bits here to get it sign extended.
21162         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21163         break;
21164       }
21165     // FIXME gcc accepts some relocatable values here too, but only in certain
21166     // memory models; it's complicated.
21167     }
21168     return;
21169   }
21170   case 'Z': {
21171     // 32-bit unsigned value
21172     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21173       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21174                                            C->getZExtValue())) {
21175         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21176         break;
21177       }
21178     }
21179     // FIXME gcc accepts some relocatable values here too, but only in certain
21180     // memory models; it's complicated.
21181     return;
21182   }
21183   case 'i': {
21184     // Literal immediates are always ok.
21185     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21186       // Widen to 64 bits here to get it sign extended.
21187       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21188       break;
21189     }
21190
21191     // In any sort of PIC mode addresses need to be computed at runtime by
21192     // adding in a register or some sort of table lookup.  These can't
21193     // be used as immediates.
21194     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21195       return;
21196
21197     // If we are in non-pic codegen mode, we allow the address of a global (with
21198     // an optional displacement) to be used with 'i'.
21199     GlobalAddressSDNode *GA = nullptr;
21200     int64_t Offset = 0;
21201
21202     // Match either (GA), (GA+C), (GA+C1+C2), etc.
21203     while (1) {
21204       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21205         Offset += GA->getOffset();
21206         break;
21207       } else if (Op.getOpcode() == ISD::ADD) {
21208         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21209           Offset += C->getZExtValue();
21210           Op = Op.getOperand(0);
21211           continue;
21212         }
21213       } else if (Op.getOpcode() == ISD::SUB) {
21214         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21215           Offset += -C->getZExtValue();
21216           Op = Op.getOperand(0);
21217           continue;
21218         }
21219       }
21220
21221       // Otherwise, this isn't something we can handle, reject it.
21222       return;
21223     }
21224
21225     const GlobalValue *GV = GA->getGlobal();
21226     // If we require an extra load to get this address, as in PIC mode, we
21227     // can't accept it.
21228     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21229                                                         getTargetMachine())))
21230       return;
21231
21232     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21233                                         GA->getValueType(0), Offset);
21234     break;
21235   }
21236   }
21237
21238   if (Result.getNode()) {
21239     Ops.push_back(Result);
21240     return;
21241   }
21242   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21243 }
21244
21245 std::pair<unsigned, const TargetRegisterClass*>
21246 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21247                                                 MVT VT) const {
21248   // First, see if this is a constraint that directly corresponds to an LLVM
21249   // register class.
21250   if (Constraint.size() == 1) {
21251     // GCC Constraint Letters
21252     switch (Constraint[0]) {
21253     default: break;
21254       // TODO: Slight differences here in allocation order and leaving
21255       // RIP in the class. Do they matter any more here than they do
21256       // in the normal allocation?
21257     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21258       if (Subtarget->is64Bit()) {
21259         if (VT == MVT::i32 || VT == MVT::f32)
21260           return std::make_pair(0U, &X86::GR32RegClass);
21261         if (VT == MVT::i16)
21262           return std::make_pair(0U, &X86::GR16RegClass);
21263         if (VT == MVT::i8 || VT == MVT::i1)
21264           return std::make_pair(0U, &X86::GR8RegClass);
21265         if (VT == MVT::i64 || VT == MVT::f64)
21266           return std::make_pair(0U, &X86::GR64RegClass);
21267         break;
21268       }
21269       // 32-bit fallthrough
21270     case 'Q':   // Q_REGS
21271       if (VT == MVT::i32 || VT == MVT::f32)
21272         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21273       if (VT == MVT::i16)
21274         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21275       if (VT == MVT::i8 || VT == MVT::i1)
21276         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21277       if (VT == MVT::i64)
21278         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21279       break;
21280     case 'r':   // GENERAL_REGS
21281     case 'l':   // INDEX_REGS
21282       if (VT == MVT::i8 || VT == MVT::i1)
21283         return std::make_pair(0U, &X86::GR8RegClass);
21284       if (VT == MVT::i16)
21285         return std::make_pair(0U, &X86::GR16RegClass);
21286       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21287         return std::make_pair(0U, &X86::GR32RegClass);
21288       return std::make_pair(0U, &X86::GR64RegClass);
21289     case 'R':   // LEGACY_REGS
21290       if (VT == MVT::i8 || VT == MVT::i1)
21291         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21292       if (VT == MVT::i16)
21293         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21294       if (VT == MVT::i32 || !Subtarget->is64Bit())
21295         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21296       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21297     case 'f':  // FP Stack registers.
21298       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21299       // value to the correct fpstack register class.
21300       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21301         return std::make_pair(0U, &X86::RFP32RegClass);
21302       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21303         return std::make_pair(0U, &X86::RFP64RegClass);
21304       return std::make_pair(0U, &X86::RFP80RegClass);
21305     case 'y':   // MMX_REGS if MMX allowed.
21306       if (!Subtarget->hasMMX()) break;
21307       return std::make_pair(0U, &X86::VR64RegClass);
21308     case 'Y':   // SSE_REGS if SSE2 allowed
21309       if (!Subtarget->hasSSE2()) break;
21310       // FALL THROUGH.
21311     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21312       if (!Subtarget->hasSSE1()) break;
21313
21314       switch (VT.SimpleTy) {
21315       default: break;
21316       // Scalar SSE types.
21317       case MVT::f32:
21318       case MVT::i32:
21319         return std::make_pair(0U, &X86::FR32RegClass);
21320       case MVT::f64:
21321       case MVT::i64:
21322         return std::make_pair(0U, &X86::FR64RegClass);
21323       // Vector types.
21324       case MVT::v16i8:
21325       case MVT::v8i16:
21326       case MVT::v4i32:
21327       case MVT::v2i64:
21328       case MVT::v4f32:
21329       case MVT::v2f64:
21330         return std::make_pair(0U, &X86::VR128RegClass);
21331       // AVX types.
21332       case MVT::v32i8:
21333       case MVT::v16i16:
21334       case MVT::v8i32:
21335       case MVT::v4i64:
21336       case MVT::v8f32:
21337       case MVT::v4f64:
21338         return std::make_pair(0U, &X86::VR256RegClass);
21339       case MVT::v8f64:
21340       case MVT::v16f32:
21341       case MVT::v16i32:
21342       case MVT::v8i64:
21343         return std::make_pair(0U, &X86::VR512RegClass);
21344       }
21345       break;
21346     }
21347   }
21348
21349   // Use the default implementation in TargetLowering to convert the register
21350   // constraint into a member of a register class.
21351   std::pair<unsigned, const TargetRegisterClass*> Res;
21352   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21353
21354   // Not found as a standard register?
21355   if (!Res.second) {
21356     // Map st(0) -> st(7) -> ST0
21357     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21358         tolower(Constraint[1]) == 's' &&
21359         tolower(Constraint[2]) == 't' &&
21360         Constraint[3] == '(' &&
21361         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21362         Constraint[5] == ')' &&
21363         Constraint[6] == '}') {
21364
21365       Res.first = X86::ST0+Constraint[4]-'0';
21366       Res.second = &X86::RFP80RegClass;
21367       return Res;
21368     }
21369
21370     // GCC allows "st(0)" to be called just plain "st".
21371     if (StringRef("{st}").equals_lower(Constraint)) {
21372       Res.first = X86::ST0;
21373       Res.second = &X86::RFP80RegClass;
21374       return Res;
21375     }
21376
21377     // flags -> EFLAGS
21378     if (StringRef("{flags}").equals_lower(Constraint)) {
21379       Res.first = X86::EFLAGS;
21380       Res.second = &X86::CCRRegClass;
21381       return Res;
21382     }
21383
21384     // 'A' means EAX + EDX.
21385     if (Constraint == "A") {
21386       Res.first = X86::EAX;
21387       Res.second = &X86::GR32_ADRegClass;
21388       return Res;
21389     }
21390     return Res;
21391   }
21392
21393   // Otherwise, check to see if this is a register class of the wrong value
21394   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21395   // turn into {ax},{dx}.
21396   if (Res.second->hasType(VT))
21397     return Res;   // Correct type already, nothing to do.
21398
21399   // All of the single-register GCC register classes map their values onto
21400   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21401   // really want an 8-bit or 32-bit register, map to the appropriate register
21402   // class and return the appropriate register.
21403   if (Res.second == &X86::GR16RegClass) {
21404     if (VT == MVT::i8 || VT == MVT::i1) {
21405       unsigned DestReg = 0;
21406       switch (Res.first) {
21407       default: break;
21408       case X86::AX: DestReg = X86::AL; break;
21409       case X86::DX: DestReg = X86::DL; break;
21410       case X86::CX: DestReg = X86::CL; break;
21411       case X86::BX: DestReg = X86::BL; break;
21412       }
21413       if (DestReg) {
21414         Res.first = DestReg;
21415         Res.second = &X86::GR8RegClass;
21416       }
21417     } else if (VT == MVT::i32 || VT == MVT::f32) {
21418       unsigned DestReg = 0;
21419       switch (Res.first) {
21420       default: break;
21421       case X86::AX: DestReg = X86::EAX; break;
21422       case X86::DX: DestReg = X86::EDX; break;
21423       case X86::CX: DestReg = X86::ECX; break;
21424       case X86::BX: DestReg = X86::EBX; break;
21425       case X86::SI: DestReg = X86::ESI; break;
21426       case X86::DI: DestReg = X86::EDI; break;
21427       case X86::BP: DestReg = X86::EBP; break;
21428       case X86::SP: DestReg = X86::ESP; break;
21429       }
21430       if (DestReg) {
21431         Res.first = DestReg;
21432         Res.second = &X86::GR32RegClass;
21433       }
21434     } else if (VT == MVT::i64 || VT == MVT::f64) {
21435       unsigned DestReg = 0;
21436       switch (Res.first) {
21437       default: break;
21438       case X86::AX: DestReg = X86::RAX; break;
21439       case X86::DX: DestReg = X86::RDX; break;
21440       case X86::CX: DestReg = X86::RCX; break;
21441       case X86::BX: DestReg = X86::RBX; break;
21442       case X86::SI: DestReg = X86::RSI; break;
21443       case X86::DI: DestReg = X86::RDI; break;
21444       case X86::BP: DestReg = X86::RBP; break;
21445       case X86::SP: DestReg = X86::RSP; break;
21446       }
21447       if (DestReg) {
21448         Res.first = DestReg;
21449         Res.second = &X86::GR64RegClass;
21450       }
21451     }
21452   } else if (Res.second == &X86::FR32RegClass ||
21453              Res.second == &X86::FR64RegClass ||
21454              Res.second == &X86::VR128RegClass ||
21455              Res.second == &X86::VR256RegClass ||
21456              Res.second == &X86::FR32XRegClass ||
21457              Res.second == &X86::FR64XRegClass ||
21458              Res.second == &X86::VR128XRegClass ||
21459              Res.second == &X86::VR256XRegClass ||
21460              Res.second == &X86::VR512RegClass) {
21461     // Handle references to XMM physical registers that got mapped into the
21462     // wrong class.  This can happen with constraints like {xmm0} where the
21463     // target independent register mapper will just pick the first match it can
21464     // find, ignoring the required type.
21465
21466     if (VT == MVT::f32 || VT == MVT::i32)
21467       Res.second = &X86::FR32RegClass;
21468     else if (VT == MVT::f64 || VT == MVT::i64)
21469       Res.second = &X86::FR64RegClass;
21470     else if (X86::VR128RegClass.hasType(VT))
21471       Res.second = &X86::VR128RegClass;
21472     else if (X86::VR256RegClass.hasType(VT))
21473       Res.second = &X86::VR256RegClass;
21474     else if (X86::VR512RegClass.hasType(VT))
21475       Res.second = &X86::VR512RegClass;
21476   }
21477
21478   return Res;
21479 }
21480
21481 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21482                                             Type *Ty) const {
21483   // Scaling factors are not free at all.
21484   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21485   // will take 2 allocations in the out of order engine instead of 1
21486   // for plain addressing mode, i.e. inst (reg1).
21487   // E.g.,
21488   // vaddps (%rsi,%drx), %ymm0, %ymm1
21489   // Requires two allocations (one for the load, one for the computation)
21490   // whereas:
21491   // vaddps (%rsi), %ymm0, %ymm1
21492   // Requires just 1 allocation, i.e., freeing allocations for other operations
21493   // and having less micro operations to execute.
21494   //
21495   // For some X86 architectures, this is even worse because for instance for
21496   // stores, the complex addressing mode forces the instruction to use the
21497   // "load" ports instead of the dedicated "store" port.
21498   // E.g., on Haswell:
21499   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21500   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21501   if (isLegalAddressingMode(AM, Ty))
21502     // Scale represents reg2 * scale, thus account for 1
21503     // as soon as we use a second register.
21504     return AM.Scale != 0;
21505   return -1;
21506 }