AVX-512: optimized icmp -> sext -> icmp pattern
[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 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86CallingConv.h"
20 #include "X86InstrBuilder.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.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/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.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 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62                                 SelectionDAG &DAG, SDLoc dl,
63                                 unsigned vectorWidth) {
64   assert((vectorWidth == 128 || vectorWidth == 256) &&
65          "Unsupported vector width");
66   EVT VT = Vec.getValueType();
67   EVT ElVT = VT.getVectorElementType();
68   unsigned Factor = VT.getSizeInBits()/vectorWidth;
69   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70                                   VT.getVectorNumElements()/Factor);
71
72   // Extract from UNDEF is UNDEF.
73   if (Vec.getOpcode() == ISD::UNDEF)
74     return DAG.getUNDEF(ResultVT);
75
76   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
77   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
78
79   // This is the index of the first element of the vectorWidth-bit chunk
80   // we want.
81   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
82                                * ElemsPerChunk);
83
84   // If the input is a buildvector just emit a smaller one.
85   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
88
89   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
91                                VecIdx);
92
93   return Result;
94
95 }
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103                                    SelectionDAG &DAG, SDLoc dl) {
104   assert((Vec.getValueType().is256BitVector() ||
105           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
107 }
108
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111                                    SelectionDAG &DAG, SDLoc dl) {
112   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
114 }
115
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117                                unsigned IdxVal, SelectionDAG &DAG,
118                                SDLoc dl, unsigned vectorWidth) {
119   assert((vectorWidth == 128 || vectorWidth == 256) &&
120          "Unsupported vector width");
121   // Inserting UNDEF is Result
122   if (Vec.getOpcode() == ISD::UNDEF)
123     return Result;
124   EVT VT = Vec.getValueType();
125   EVT ElVT = VT.getVectorElementType();
126   EVT ResultVT = Result.getValueType();
127
128   // Insert the relevant vectorWidth bits.
129   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
130
131   // This is the index of the first element of the vectorWidth-bit chunk
132   // we want.
133   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
134                                * ElemsPerChunk);
135
136   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
138                      VecIdx);
139 }
140 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference.  Idx is an index in the 128 bits
144 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147                                   unsigned IdxVal, SelectionDAG &DAG,
148                                   SDLoc dl) {
149   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
151 }
152
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154                                   unsigned IdxVal, SelectionDAG &DAG,
155                                   SDLoc dl) {
156   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
158 }
159
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165                                    unsigned NumElems, SelectionDAG &DAG,
166                                    SDLoc dl) {
167   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
169 }
170
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172                                    unsigned NumElems, SelectionDAG &DAG,
173                                    SDLoc dl) {
174   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
176 }
177
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180   bool is64Bit = Subtarget->is64Bit();
181
182   if (Subtarget->isTargetMacho()) {
183     if (is64Bit)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (Subtarget->isTargetLinux())
189     return new X86LinuxTargetObjectFile();
190   if (Subtarget->isTargetELF())
191     return new TargetLoweringObjectFileELF();
192   if (Subtarget->isTargetWindows())
193     return new X86WindowsTargetObjectFile();
194   if (Subtarget->isTargetCOFF())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(TM)) {
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->isTargetWindows() && !Subtarget->isTargetCygMing()) {
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, 0);
269     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
270     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
271     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
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->isTargetMingw()) {
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   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
509
510   // These should be promoted to a larger select which is supported.
511   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
512   // X86 wants to expand cmov itself.
513   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
514   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
515   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
516   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
517   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
519   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
520   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
523   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
525   if (Subtarget->is64Bit()) {
526     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
527     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
528   }
529   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
530   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
531   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
532   // support continuation, user-level threading, and etc.. As a result, no
533   // other SjLj exception interfaces are implemented and please don't build
534   // your own exception handling based on them.
535   // LLVM/Clang supports zero-cost DWARF exception handling.
536   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
537   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
538
539   // Darwin ABI issue.
540   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
541   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
542   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
543   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
544   if (Subtarget->is64Bit())
545     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
546   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
547   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
548   if (Subtarget->is64Bit()) {
549     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
550     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
551     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
552     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
553     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
554   }
555   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
556   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
557   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
558   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
559   if (Subtarget->is64Bit()) {
560     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
561     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
562     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
563   }
564
565   if (Subtarget->hasSSE1())
566     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
567
568   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
569
570   // Expand certain atomics
571   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
572     MVT VT = IntVTs[i];
573     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
574     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
575     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
576   }
577
578   if (!Subtarget->is64Bit()) {
579     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
591   }
592
593   if (Subtarget->hasCmpxchg16b()) {
594     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
595   }
596
597   // FIXME - use subtarget debug flags
598   if (!Subtarget->isTargetDarwin() &&
599       !Subtarget->isTargetELF() &&
600       !Subtarget->isTargetCygMing()) {
601     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
602   }
603
604   if (Subtarget->is64Bit()) {
605     setExceptionPointerRegister(X86::RAX);
606     setExceptionSelectorRegister(X86::RDX);
607   } else {
608     setExceptionPointerRegister(X86::EAX);
609     setExceptionSelectorRegister(X86::EDX);
610   }
611   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
612   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
613
614   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
615   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
616
617   setOperationAction(ISD::TRAP, MVT::Other, Legal);
618   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
619
620   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
621   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
622   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
623   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
624     // TargetInfo::X86_64ABIBuiltinVaList
625     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
626     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
627   } else {
628     // TargetInfo::CharPtrBuiltinVaList
629     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
630     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
631   }
632
633   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
634   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
635
636   if (Subtarget->isOSWindows() && !Subtarget->isTargetMacho())
637     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
638                        MVT::i64 : MVT::i32, Custom);
639   else if (TM.Options.EnableSegmentedStacks)
640     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
641                        MVT::i64 : MVT::i32, Custom);
642   else
643     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
644                        MVT::i64 : MVT::i32, Expand);
645
646   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
647     // f32 and f64 use SSE.
648     // Set up the FP register classes.
649     addRegisterClass(MVT::f32, &X86::FR32RegClass);
650     addRegisterClass(MVT::f64, &X86::FR64RegClass);
651
652     // Use ANDPD to simulate FABS.
653     setOperationAction(ISD::FABS , MVT::f64, Custom);
654     setOperationAction(ISD::FABS , MVT::f32, Custom);
655
656     // Use XORP to simulate FNEG.
657     setOperationAction(ISD::FNEG , MVT::f64, Custom);
658     setOperationAction(ISD::FNEG , MVT::f32, Custom);
659
660     // Use ANDPD and ORPD to simulate FCOPYSIGN.
661     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
662     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
663
664     // Lower this to FGETSIGNx86 plus an AND.
665     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
666     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
667
668     // We don't support sin/cos/fmod
669     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
670     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
671     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
672     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
673     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
674     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
675
676     // Expand FP immediates into loads from the stack, except for the special
677     // cases we handle.
678     addLegalFPImmediate(APFloat(+0.0)); // xorpd
679     addLegalFPImmediate(APFloat(+0.0f)); // xorps
680   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
681     // Use SSE for f32, x87 for f64.
682     // Set up the FP register classes.
683     addRegisterClass(MVT::f32, &X86::FR32RegClass);
684     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
685
686     // Use ANDPS to simulate FABS.
687     setOperationAction(ISD::FABS , MVT::f32, Custom);
688
689     // Use XORP to simulate FNEG.
690     setOperationAction(ISD::FNEG , MVT::f32, Custom);
691
692     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
693
694     // Use ANDPS and ORPS to simulate FCOPYSIGN.
695     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
696     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
697
698     // We don't support sin/cos/fmod
699     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
700     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
701     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
702
703     // Special cases we handle for FP constants.
704     addLegalFPImmediate(APFloat(+0.0f)); // xorps
705     addLegalFPImmediate(APFloat(+0.0)); // FLD0
706     addLegalFPImmediate(APFloat(+1.0)); // FLD1
707     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
708     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
709
710     if (!TM.Options.UnsafeFPMath) {
711       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
712       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
713       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
714     }
715   } else if (!TM.Options.UseSoftFloat) {
716     // f32 and f64 in x87.
717     // Set up the FP register classes.
718     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
719     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
720
721     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
722     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
723     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
724     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
725
726     if (!TM.Options.UnsafeFPMath) {
727       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
728       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
729       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
730       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
731       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
733     }
734     addLegalFPImmediate(APFloat(+0.0)); // FLD0
735     addLegalFPImmediate(APFloat(+1.0)); // FLD1
736     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
737     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
738     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
739     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
740     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
741     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
742   }
743
744   // We don't support FMA.
745   setOperationAction(ISD::FMA, MVT::f64, Expand);
746   setOperationAction(ISD::FMA, MVT::f32, Expand);
747
748   // Long double always uses X87.
749   if (!TM.Options.UseSoftFloat) {
750     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
751     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
752     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
753     {
754       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
755       addLegalFPImmediate(TmpFlt);  // FLD0
756       TmpFlt.changeSign();
757       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
758
759       bool ignored;
760       APFloat TmpFlt2(+1.0);
761       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
762                       &ignored);
763       addLegalFPImmediate(TmpFlt2);  // FLD1
764       TmpFlt2.changeSign();
765       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
766     }
767
768     if (!TM.Options.UnsafeFPMath) {
769       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
770       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
771       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
772     }
773
774     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
775     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
776     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
777     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
778     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
779     setOperationAction(ISD::FMA, MVT::f80, Expand);
780   }
781
782   // Always use a library call for pow.
783   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
784   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
785   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
786
787   setOperationAction(ISD::FLOG, MVT::f80, Expand);
788   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
789   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
790   setOperationAction(ISD::FEXP, MVT::f80, Expand);
791   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
792
793   // First set operation action for all vector types to either promote
794   // (for widening) or expand (for scalarization). Then we will selectively
795   // turn on ones that can be effectively codegen'd.
796   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
797            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
798     MVT VT = (MVT::SimpleValueType)i;
799     setOperationAction(ISD::ADD , VT, Expand);
800     setOperationAction(ISD::SUB , VT, Expand);
801     setOperationAction(ISD::FADD, VT, Expand);
802     setOperationAction(ISD::FNEG, VT, Expand);
803     setOperationAction(ISD::FSUB, VT, Expand);
804     setOperationAction(ISD::MUL , VT, Expand);
805     setOperationAction(ISD::FMUL, VT, Expand);
806     setOperationAction(ISD::SDIV, VT, Expand);
807     setOperationAction(ISD::UDIV, VT, Expand);
808     setOperationAction(ISD::FDIV, VT, Expand);
809     setOperationAction(ISD::SREM, VT, Expand);
810     setOperationAction(ISD::UREM, VT, Expand);
811     setOperationAction(ISD::LOAD, VT, Expand);
812     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
813     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
814     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
815     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
816     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
817     setOperationAction(ISD::FABS, VT, Expand);
818     setOperationAction(ISD::FSIN, VT, Expand);
819     setOperationAction(ISD::FSINCOS, VT, Expand);
820     setOperationAction(ISD::FCOS, VT, Expand);
821     setOperationAction(ISD::FSINCOS, VT, Expand);
822     setOperationAction(ISD::FREM, VT, Expand);
823     setOperationAction(ISD::FMA,  VT, Expand);
824     setOperationAction(ISD::FPOWI, VT, Expand);
825     setOperationAction(ISD::FSQRT, VT, Expand);
826     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
827     setOperationAction(ISD::FFLOOR, VT, Expand);
828     setOperationAction(ISD::FCEIL, VT, Expand);
829     setOperationAction(ISD::FTRUNC, VT, Expand);
830     setOperationAction(ISD::FRINT, VT, Expand);
831     setOperationAction(ISD::FNEARBYINT, VT, Expand);
832     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
833     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
834     setOperationAction(ISD::SDIVREM, VT, Expand);
835     setOperationAction(ISD::UDIVREM, VT, Expand);
836     setOperationAction(ISD::FPOW, VT, Expand);
837     setOperationAction(ISD::CTPOP, VT, Expand);
838     setOperationAction(ISD::CTTZ, VT, Expand);
839     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::CTLZ, VT, Expand);
841     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
842     setOperationAction(ISD::SHL, VT, Expand);
843     setOperationAction(ISD::SRA, VT, Expand);
844     setOperationAction(ISD::SRL, VT, Expand);
845     setOperationAction(ISD::ROTL, VT, Expand);
846     setOperationAction(ISD::ROTR, VT, Expand);
847     setOperationAction(ISD::BSWAP, VT, Expand);
848     setOperationAction(ISD::SETCC, VT, Expand);
849     setOperationAction(ISD::FLOG, VT, Expand);
850     setOperationAction(ISD::FLOG2, VT, Expand);
851     setOperationAction(ISD::FLOG10, VT, Expand);
852     setOperationAction(ISD::FEXP, VT, Expand);
853     setOperationAction(ISD::FEXP2, VT, Expand);
854     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859     setOperationAction(ISD::TRUNCATE, VT, Expand);
860     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863     setOperationAction(ISD::VSELECT, VT, Expand);
864     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
865              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
866       setTruncStoreAction(VT,
867                           (MVT::SimpleValueType)InnerVT, Expand);
868     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
869     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
870     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871   }
872
873   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
874   // with -msoft-float, disable use of MMX as well.
875   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
876     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
877     // No operations on x86mmx supported, everything uses intrinsics.
878   }
879
880   // MMX-sized vectors (other than x86mmx) are expected to be expanded
881   // into smaller operations.
882   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
883   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
884   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
885   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
886   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
887   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
888   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
889   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
890   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
891   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
892   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
893   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
894   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
895   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
896   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
897   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
901   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
902   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
904   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
906   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
910   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
911
912   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
913     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
914
915     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
919     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
920     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
921     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
922     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
923     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
924     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
925     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
927   }
928
929   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
930     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
931
932     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
933     // registers cannot be used even for integer operations.
934     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
935     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
936     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
937     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
938
939     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
940     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
941     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
942     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
943     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
944     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
945     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
946     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
947     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
948     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
949     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
950     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
955     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
956     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
957
958     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
961     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
962
963     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
964     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
968
969     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
970     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
971       MVT VT = (MVT::SimpleValueType)i;
972       // Do not attempt to custom lower non-power-of-2 vectors
973       if (!isPowerOf2_32(VT.getVectorNumElements()))
974         continue;
975       // Do not attempt to custom lower non-128-bit vectors
976       if (!VT.is128BitVector())
977         continue;
978       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
979       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
980       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
981     }
982
983     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
984     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
985     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
986     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
988     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
989
990     if (Subtarget->is64Bit()) {
991       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
992       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
993     }
994
995     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
996     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
997       MVT VT = (MVT::SimpleValueType)i;
998
999       // Do not attempt to promote non-128-bit vectors
1000       if (!VT.is128BitVector())
1001         continue;
1002
1003       setOperationAction(ISD::AND,    VT, Promote);
1004       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1005       setOperationAction(ISD::OR,     VT, Promote);
1006       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1007       setOperationAction(ISD::XOR,    VT, Promote);
1008       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1009       setOperationAction(ISD::LOAD,   VT, Promote);
1010       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1011       setOperationAction(ISD::SELECT, VT, Promote);
1012       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1013     }
1014
1015     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1016
1017     // Custom lower v2i64 and v2f64 selects.
1018     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1019     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1020     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1021     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1022
1023     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1024     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1025
1026     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1027     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1028     // As there is no 64-bit GPR available, we need build a special custom
1029     // sequence to convert from v2i32 to v2f32.
1030     if (!Subtarget->is64Bit())
1031       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1032
1033     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1034     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1035
1036     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1037   }
1038
1039   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1040     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1041     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1042     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1043     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1044     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1045     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1046     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1047     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1048     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1049     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1050
1051     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1052     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1053     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1054     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1055     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1061
1062     // FIXME: Do we need to handle scalar-to-vector here?
1063     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1064
1065     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1068     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1069     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1070
1071     // i8 and i16 vectors are custom , because the source register and source
1072     // source memory operand types are not the same width.  f32 vectors are
1073     // custom since the immediate controlling the insert encodes additional
1074     // information.
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1077     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1078     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1079
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1082     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1083     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1084
1085     // FIXME: these should be Legal but thats only for the case where
1086     // the index is constant.  For now custom expand to deal with that.
1087     if (Subtarget->is64Bit()) {
1088       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1089       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1090     }
1091   }
1092
1093   if (Subtarget->hasSSE2()) {
1094     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1095     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1096
1097     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1098     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1099
1100     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1101     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1102
1103     // In the customized shift lowering, the legal cases in AVX2 will be
1104     // recognized.
1105     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1106     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1107
1108     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1109     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1110
1111     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1112
1113     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1114     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1115   }
1116
1117   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1118     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1120     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1122     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1123     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1124
1125     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1126     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1127     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1128
1129     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1132     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1133     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1135     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1136     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1137     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1138     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1139     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1140     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1141
1142     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1145     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1146     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1148     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1149     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1150     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1151     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1152     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1153     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1154
1155     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1156
1157     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1158     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1159     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1160     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1161
1162     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1163     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1164
1165     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1166
1167     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1168     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1169
1170     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1171     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1172
1173     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1174     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1175
1176     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1177
1178     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1182
1183     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1184     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1185     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1186
1187     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1191
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1200     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1202     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1203     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1204
1205     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1206       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1208       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1209       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1210       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1211       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1212     }
1213
1214     if (Subtarget->hasInt256()) {
1215       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1217       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1218       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1219
1220       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1222       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1223       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1224
1225       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1226       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1227       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1228       // Don't lower v32i8 because there is no 128-bit byte mul
1229
1230       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1231
1232       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1233     } else {
1234       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1235       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1236       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1237       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1238
1239       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1240       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1241       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1242       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1243
1244       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1245       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1246       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1247       // Don't lower v32i8 because there is no 128-bit byte mul
1248     }
1249
1250     // In the customized shift lowering, the legal cases in AVX2 will be
1251     // recognized.
1252     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1253     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1254
1255     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1256     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1257
1258     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1259
1260     // Custom lower several nodes for 256-bit types.
1261     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1262              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1263       MVT VT = (MVT::SimpleValueType)i;
1264
1265       // Extract subvector is special because the value type
1266       // (result) is 128-bit but the source is 256-bit wide.
1267       if (VT.is128BitVector())
1268         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1269
1270       // Do not attempt to custom lower other non-256-bit vectors
1271       if (!VT.is256BitVector())
1272         continue;
1273
1274       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1275       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1276       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1277       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1278       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1279       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1280       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1281     }
1282
1283     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1284     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1285       MVT VT = (MVT::SimpleValueType)i;
1286
1287       // Do not attempt to promote non-256-bit vectors
1288       if (!VT.is256BitVector())
1289         continue;
1290
1291       setOperationAction(ISD::AND,    VT, Promote);
1292       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1293       setOperationAction(ISD::OR,     VT, Promote);
1294       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1295       setOperationAction(ISD::XOR,    VT, Promote);
1296       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1297       setOperationAction(ISD::LOAD,   VT, Promote);
1298       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1299       setOperationAction(ISD::SELECT, VT, Promote);
1300       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1301     }
1302   }
1303
1304   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1305     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1308     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1309
1310     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1311     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1312     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1313
1314     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1315     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1316     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1317     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1318     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1319     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1323     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1324     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1325
1326     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1329     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1330     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1331     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1332
1333     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1336     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1337     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1338     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1339     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1340     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1341     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1342
1343     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1344     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1345     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1347     if (Subtarget->is64Bit()) {
1348       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1349       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1350       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1351       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1352     }
1353     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1355     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1356     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1359     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1360     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1361
1362     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1363     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1364     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1365     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1366     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1368     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1369     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1370     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1371     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1372     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1373     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1374     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1375
1376     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1377     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1378     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1379     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1380     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1381     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1382
1383     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1384     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1385
1386     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1387
1388     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1389     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1390     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1391     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1392     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1393     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1394     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1395
1396     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1397     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1398
1399     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1400     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1401
1402     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1403
1404     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1405     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1406
1407     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1408     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1409
1410     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1411     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1412
1413     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1414     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1415     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1416     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1417     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1418     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1419
1420     // Custom lower several nodes.
1421     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1422              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1423       MVT VT = (MVT::SimpleValueType)i;
1424
1425       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1426       // Extract subvector is special because the value type
1427       // (result) is 256/128-bit but the source is 512-bit wide.
1428       if (VT.is128BitVector() || VT.is256BitVector())
1429         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1430
1431       if (VT.getVectorElementType() == MVT::i1)
1432         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1433
1434       // Do not attempt to custom lower other non-512-bit vectors
1435       if (!VT.is512BitVector())
1436         continue;
1437
1438       if ( EltSize >= 32) {
1439         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1440         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1441         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1442         setOperationAction(ISD::VSELECT,             VT, Legal);
1443         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1444         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1445         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1446       }
1447     }
1448     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1449       MVT VT = (MVT::SimpleValueType)i;
1450
1451       // Do not attempt to promote non-256-bit vectors
1452       if (!VT.is512BitVector())
1453         continue;
1454
1455       setOperationAction(ISD::SELECT, VT, Promote);
1456       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1457     }
1458   }// has  AVX-512
1459
1460   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1461   // of this type with custom code.
1462   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1463            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1464     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1465                        Custom);
1466   }
1467
1468   // We want to custom lower some of our intrinsics.
1469   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1470   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1471   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1472
1473   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1474   // handle type legalization for these operations here.
1475   //
1476   // FIXME: We really should do custom legalization for addition and
1477   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1478   // than generic legalization for 64-bit multiplication-with-overflow, though.
1479   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1480     // Add/Sub/Mul with overflow operations are custom lowered.
1481     MVT VT = IntVTs[i];
1482     setOperationAction(ISD::SADDO, VT, Custom);
1483     setOperationAction(ISD::UADDO, VT, Custom);
1484     setOperationAction(ISD::SSUBO, VT, Custom);
1485     setOperationAction(ISD::USUBO, VT, Custom);
1486     setOperationAction(ISD::SMULO, VT, Custom);
1487     setOperationAction(ISD::UMULO, VT, Custom);
1488   }
1489
1490   // There are no 8-bit 3-address imul/mul instructions
1491   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1492   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1493
1494   if (!Subtarget->is64Bit()) {
1495     // These libcalls are not available in 32-bit.
1496     setLibcallName(RTLIB::SHL_I128, 0);
1497     setLibcallName(RTLIB::SRL_I128, 0);
1498     setLibcallName(RTLIB::SRA_I128, 0);
1499   }
1500
1501   // Combine sin / cos into one node or libcall if possible.
1502   if (Subtarget->hasSinCos()) {
1503     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1504     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1505     if (Subtarget->isTargetDarwin()) {
1506       // For MacOSX, we don't want to the normal expansion of a libcall to
1507       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1508       // traffic.
1509       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1510       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1511     }
1512   }
1513
1514   // We have target-specific dag combine patterns for the following nodes:
1515   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1516   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1517   setTargetDAGCombine(ISD::VSELECT);
1518   setTargetDAGCombine(ISD::SELECT);
1519   setTargetDAGCombine(ISD::SHL);
1520   setTargetDAGCombine(ISD::SRA);
1521   setTargetDAGCombine(ISD::SRL);
1522   setTargetDAGCombine(ISD::OR);
1523   setTargetDAGCombine(ISD::AND);
1524   setTargetDAGCombine(ISD::ADD);
1525   setTargetDAGCombine(ISD::FADD);
1526   setTargetDAGCombine(ISD::FSUB);
1527   setTargetDAGCombine(ISD::FMA);
1528   setTargetDAGCombine(ISD::SUB);
1529   setTargetDAGCombine(ISD::LOAD);
1530   setTargetDAGCombine(ISD::STORE);
1531   setTargetDAGCombine(ISD::ZERO_EXTEND);
1532   setTargetDAGCombine(ISD::ANY_EXTEND);
1533   setTargetDAGCombine(ISD::SIGN_EXTEND);
1534   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1535   setTargetDAGCombine(ISD::TRUNCATE);
1536   setTargetDAGCombine(ISD::SINT_TO_FP);
1537   setTargetDAGCombine(ISD::SETCC);
1538   if (Subtarget->is64Bit())
1539     setTargetDAGCombine(ISD::MUL);
1540   setTargetDAGCombine(ISD::XOR);
1541
1542   computeRegisterProperties();
1543
1544   // On Darwin, -Os means optimize for size without hurting performance,
1545   // do not reduce the limit.
1546   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1547   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1548   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1549   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1550   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1551   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1552   setPrefLoopAlignment(4); // 2^4 bytes.
1553
1554   // Predictable cmov don't hurt on atom because it's in-order.
1555   PredictableSelectIsExpensive = !Subtarget->isAtom();
1556
1557   setPrefFunctionAlignment(4); // 2^4 bytes.
1558 }
1559
1560 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1561   if (!VT.isVector())
1562     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1563
1564   if (Subtarget->hasAVX512())
1565     switch(VT.getVectorNumElements()) {
1566     case  8: return MVT::v8i1;
1567     case 16: return MVT::v16i1;
1568   }
1569
1570   return VT.changeVectorElementTypeToInteger();
1571 }
1572
1573 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1574 /// the desired ByVal argument alignment.
1575 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1576   if (MaxAlign == 16)
1577     return;
1578   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1579     if (VTy->getBitWidth() == 128)
1580       MaxAlign = 16;
1581   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1582     unsigned EltAlign = 0;
1583     getMaxByValAlign(ATy->getElementType(), EltAlign);
1584     if (EltAlign > MaxAlign)
1585       MaxAlign = EltAlign;
1586   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1587     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1588       unsigned EltAlign = 0;
1589       getMaxByValAlign(STy->getElementType(i), EltAlign);
1590       if (EltAlign > MaxAlign)
1591         MaxAlign = EltAlign;
1592       if (MaxAlign == 16)
1593         break;
1594     }
1595   }
1596 }
1597
1598 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1599 /// function arguments in the caller parameter area. For X86, aggregates
1600 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1601 /// are at 4-byte boundaries.
1602 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1603   if (Subtarget->is64Bit()) {
1604     // Max of 8 and alignment of type.
1605     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1606     if (TyAlign > 8)
1607       return TyAlign;
1608     return 8;
1609   }
1610
1611   unsigned Align = 4;
1612   if (Subtarget->hasSSE1())
1613     getMaxByValAlign(Ty, Align);
1614   return Align;
1615 }
1616
1617 /// getOptimalMemOpType - Returns the target specific optimal type for load
1618 /// and store operations as a result of memset, memcpy, and memmove
1619 /// lowering. If DstAlign is zero that means it's safe to destination
1620 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1621 /// means there isn't a need to check it against alignment requirement,
1622 /// probably because the source does not need to be loaded. If 'IsMemset' is
1623 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1624 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1625 /// source is constant so it does not need to be loaded.
1626 /// It returns EVT::Other if the type should be determined using generic
1627 /// target-independent logic.
1628 EVT
1629 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1630                                        unsigned DstAlign, unsigned SrcAlign,
1631                                        bool IsMemset, bool ZeroMemset,
1632                                        bool MemcpyStrSrc,
1633                                        MachineFunction &MF) const {
1634   const Function *F = MF.getFunction();
1635   if ((!IsMemset || ZeroMemset) &&
1636       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1637                                        Attribute::NoImplicitFloat)) {
1638     if (Size >= 16 &&
1639         (Subtarget->isUnalignedMemAccessFast() ||
1640          ((DstAlign == 0 || DstAlign >= 16) &&
1641           (SrcAlign == 0 || SrcAlign >= 16)))) {
1642       if (Size >= 32) {
1643         if (Subtarget->hasInt256())
1644           return MVT::v8i32;
1645         if (Subtarget->hasFp256())
1646           return MVT::v8f32;
1647       }
1648       if (Subtarget->hasSSE2())
1649         return MVT::v4i32;
1650       if (Subtarget->hasSSE1())
1651         return MVT::v4f32;
1652     } else if (!MemcpyStrSrc && Size >= 8 &&
1653                !Subtarget->is64Bit() &&
1654                Subtarget->hasSSE2()) {
1655       // Do not use f64 to lower memcpy if source is string constant. It's
1656       // better to use i32 to avoid the loads.
1657       return MVT::f64;
1658     }
1659   }
1660   if (Subtarget->is64Bit() && Size >= 8)
1661     return MVT::i64;
1662   return MVT::i32;
1663 }
1664
1665 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1666   if (VT == MVT::f32)
1667     return X86ScalarSSEf32;
1668   else if (VT == MVT::f64)
1669     return X86ScalarSSEf64;
1670   return true;
1671 }
1672
1673 bool
1674 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1675   if (Fast)
1676     *Fast = Subtarget->isUnalignedMemAccessFast();
1677   return true;
1678 }
1679
1680 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1681 /// current function.  The returned value is a member of the
1682 /// MachineJumpTableInfo::JTEntryKind enum.
1683 unsigned X86TargetLowering::getJumpTableEncoding() const {
1684   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1685   // symbol.
1686   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1687       Subtarget->isPICStyleGOT())
1688     return MachineJumpTableInfo::EK_Custom32;
1689
1690   // Otherwise, use the normal jump table encoding heuristics.
1691   return TargetLowering::getJumpTableEncoding();
1692 }
1693
1694 const MCExpr *
1695 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1696                                              const MachineBasicBlock *MBB,
1697                                              unsigned uid,MCContext &Ctx) const{
1698   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1699          Subtarget->isPICStyleGOT());
1700   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1701   // entries.
1702   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1703                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1704 }
1705
1706 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1707 /// jumptable.
1708 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1709                                                     SelectionDAG &DAG) const {
1710   if (!Subtarget->is64Bit())
1711     // This doesn't have SDLoc associated with it, but is not really the
1712     // same as a Register.
1713     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1714   return Table;
1715 }
1716
1717 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1718 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1719 /// MCExpr.
1720 const MCExpr *X86TargetLowering::
1721 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1722                              MCContext &Ctx) const {
1723   // X86-64 uses RIP relative addressing based on the jump table label.
1724   if (Subtarget->isPICStyleRIPRel())
1725     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1726
1727   // Otherwise, the reference is relative to the PIC base.
1728   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1729 }
1730
1731 // FIXME: Why this routine is here? Move to RegInfo!
1732 std::pair<const TargetRegisterClass*, uint8_t>
1733 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1734   const TargetRegisterClass *RRC = 0;
1735   uint8_t Cost = 1;
1736   switch (VT.SimpleTy) {
1737   default:
1738     return TargetLowering::findRepresentativeClass(VT);
1739   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1740     RRC = Subtarget->is64Bit() ?
1741       (const TargetRegisterClass*)&X86::GR64RegClass :
1742       (const TargetRegisterClass*)&X86::GR32RegClass;
1743     break;
1744   case MVT::x86mmx:
1745     RRC = &X86::VR64RegClass;
1746     break;
1747   case MVT::f32: case MVT::f64:
1748   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1749   case MVT::v4f32: case MVT::v2f64:
1750   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1751   case MVT::v4f64:
1752     RRC = &X86::VR128RegClass;
1753     break;
1754   }
1755   return std::make_pair(RRC, Cost);
1756 }
1757
1758 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1759                                                unsigned &Offset) const {
1760   if (!Subtarget->isTargetLinux())
1761     return false;
1762
1763   if (Subtarget->is64Bit()) {
1764     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1765     Offset = 0x28;
1766     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1767       AddressSpace = 256;
1768     else
1769       AddressSpace = 257;
1770   } else {
1771     // %gs:0x14 on i386
1772     Offset = 0x14;
1773     AddressSpace = 256;
1774   }
1775   return true;
1776 }
1777
1778 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1779                                             unsigned DestAS) const {
1780   assert(SrcAS != DestAS && "Expected different address spaces!");
1781
1782   return SrcAS < 256 && DestAS < 256;
1783 }
1784
1785 //===----------------------------------------------------------------------===//
1786 //               Return Value Calling Convention Implementation
1787 //===----------------------------------------------------------------------===//
1788
1789 #include "X86GenCallingConv.inc"
1790
1791 bool
1792 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1793                                   MachineFunction &MF, bool isVarArg,
1794                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1795                         LLVMContext &Context) const {
1796   SmallVector<CCValAssign, 16> RVLocs;
1797   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1798                  RVLocs, Context);
1799   return CCInfo.CheckReturn(Outs, RetCC_X86);
1800 }
1801
1802 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1803   static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1804   return ScratchRegs;
1805 }
1806
1807 SDValue
1808 X86TargetLowering::LowerReturn(SDValue Chain,
1809                                CallingConv::ID CallConv, bool isVarArg,
1810                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1811                                const SmallVectorImpl<SDValue> &OutVals,
1812                                SDLoc dl, SelectionDAG &DAG) const {
1813   MachineFunction &MF = DAG.getMachineFunction();
1814   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1815
1816   SmallVector<CCValAssign, 16> RVLocs;
1817   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1818                  RVLocs, *DAG.getContext());
1819   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1820
1821   SDValue Flag;
1822   SmallVector<SDValue, 6> RetOps;
1823   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1824   // Operand #1 = Bytes To Pop
1825   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1826                    MVT::i16));
1827
1828   // Copy the result values into the output registers.
1829   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1830     CCValAssign &VA = RVLocs[i];
1831     assert(VA.isRegLoc() && "Can only return in registers!");
1832     SDValue ValToCopy = OutVals[i];
1833     EVT ValVT = ValToCopy.getValueType();
1834
1835     // Promote values to the appropriate types
1836     if (VA.getLocInfo() == CCValAssign::SExt)
1837       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1838     else if (VA.getLocInfo() == CCValAssign::ZExt)
1839       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1840     else if (VA.getLocInfo() == CCValAssign::AExt)
1841       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1842     else if (VA.getLocInfo() == CCValAssign::BCvt)
1843       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1844
1845     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1846            "Unexpected FP-extend for return value.");  
1847
1848     // If this is x86-64, and we disabled SSE, we can't return FP values,
1849     // or SSE or MMX vectors.
1850     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1851          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1852           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1853       report_fatal_error("SSE register return with SSE disabled");
1854     }
1855     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1856     // llvm-gcc has never done it right and no one has noticed, so this
1857     // should be OK for now.
1858     if (ValVT == MVT::f64 &&
1859         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1860       report_fatal_error("SSE2 register return with SSE2 disabled");
1861
1862     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1863     // the RET instruction and handled by the FP Stackifier.
1864     if (VA.getLocReg() == X86::ST0 ||
1865         VA.getLocReg() == X86::ST1) {
1866       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1867       // change the value to the FP stack register class.
1868       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1869         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1870       RetOps.push_back(ValToCopy);
1871       // Don't emit a copytoreg.
1872       continue;
1873     }
1874
1875     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1876     // which is returned in RAX / RDX.
1877     if (Subtarget->is64Bit()) {
1878       if (ValVT == MVT::x86mmx) {
1879         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1880           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1881           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1882                                   ValToCopy);
1883           // If we don't have SSE2 available, convert to v4f32 so the generated
1884           // register is legal.
1885           if (!Subtarget->hasSSE2())
1886             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1887         }
1888       }
1889     }
1890
1891     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1892     Flag = Chain.getValue(1);
1893     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1894   }
1895
1896   // The x86-64 ABIs require that for returning structs by value we copy
1897   // the sret argument into %rax/%eax (depending on ABI) for the return.
1898   // Win32 requires us to put the sret argument to %eax as well.
1899   // We saved the argument into a virtual register in the entry block,
1900   // so now we copy the value out and into %rax/%eax.
1901   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1902       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1903     MachineFunction &MF = DAG.getMachineFunction();
1904     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1905     unsigned Reg = FuncInfo->getSRetReturnReg();
1906     assert(Reg &&
1907            "SRetReturnReg should have been set in LowerFormalArguments().");
1908     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1909
1910     unsigned RetValReg
1911         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1912           X86::RAX : X86::EAX;
1913     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1914     Flag = Chain.getValue(1);
1915
1916     // RAX/EAX now acts like a return value.
1917     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1918   }
1919
1920   RetOps[0] = Chain;  // Update chain.
1921
1922   // Add the flag if we have it.
1923   if (Flag.getNode())
1924     RetOps.push_back(Flag);
1925
1926   return DAG.getNode(X86ISD::RET_FLAG, dl,
1927                      MVT::Other, &RetOps[0], RetOps.size());
1928 }
1929
1930 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1931   if (N->getNumValues() != 1)
1932     return false;
1933   if (!N->hasNUsesOfValue(1, 0))
1934     return false;
1935
1936   SDValue TCChain = Chain;
1937   SDNode *Copy = *N->use_begin();
1938   if (Copy->getOpcode() == ISD::CopyToReg) {
1939     // If the copy has a glue operand, we conservatively assume it isn't safe to
1940     // perform a tail call.
1941     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1942       return false;
1943     TCChain = Copy->getOperand(0);
1944   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1945     return false;
1946
1947   bool HasRet = false;
1948   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1949        UI != UE; ++UI) {
1950     if (UI->getOpcode() != X86ISD::RET_FLAG)
1951       return false;
1952     HasRet = true;
1953   }
1954
1955   if (!HasRet)
1956     return false;
1957
1958   Chain = TCChain;
1959   return true;
1960 }
1961
1962 MVT
1963 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1964                                             ISD::NodeType ExtendKind) const {
1965   MVT ReturnMVT;
1966   // TODO: Is this also valid on 32-bit?
1967   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1968     ReturnMVT = MVT::i8;
1969   else
1970     ReturnMVT = MVT::i32;
1971
1972   MVT MinVT = getRegisterType(ReturnMVT);
1973   return VT.bitsLT(MinVT) ? MinVT : VT;
1974 }
1975
1976 /// LowerCallResult - Lower the result values of a call into the
1977 /// appropriate copies out of appropriate physical registers.
1978 ///
1979 SDValue
1980 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1981                                    CallingConv::ID CallConv, bool isVarArg,
1982                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1983                                    SDLoc dl, SelectionDAG &DAG,
1984                                    SmallVectorImpl<SDValue> &InVals) const {
1985
1986   // Assign locations to each value returned by this call.
1987   SmallVector<CCValAssign, 16> RVLocs;
1988   bool Is64Bit = Subtarget->is64Bit();
1989   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1990                  getTargetMachine(), RVLocs, *DAG.getContext());
1991   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1992
1993   // Copy all of the result registers out of their specified physreg.
1994   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1995     CCValAssign &VA = RVLocs[i];
1996     EVT CopyVT = VA.getValVT();
1997
1998     // If this is x86-64, and we disabled SSE, we can't return FP values
1999     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2000         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2001       report_fatal_error("SSE register return with SSE disabled");
2002     }
2003
2004     SDValue Val;
2005
2006     // If this is a call to a function that returns an fp value on the floating
2007     // point stack, we must guarantee the value is popped from the stack, so
2008     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2009     // if the return value is not used. We use the FpPOP_RETVAL instruction
2010     // instead.
2011     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2012       // If we prefer to use the value in xmm registers, copy it out as f80 and
2013       // use a truncate to move it from fp stack reg to xmm reg.
2014       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2015       SDValue Ops[] = { Chain, InFlag };
2016       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2017                                          MVT::Other, MVT::Glue, Ops), 1);
2018       Val = Chain.getValue(0);
2019
2020       // Round the f80 to the right size, which also moves it to the appropriate
2021       // xmm register.
2022       if (CopyVT != VA.getValVT())
2023         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2024                           // This truncation won't change the value.
2025                           DAG.getIntPtrConstant(1));
2026     } else {
2027       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2028                                  CopyVT, InFlag).getValue(1);
2029       Val = Chain.getValue(0);
2030     }
2031     InFlag = Chain.getValue(2);
2032     InVals.push_back(Val);
2033   }
2034
2035   return Chain;
2036 }
2037
2038 //===----------------------------------------------------------------------===//
2039 //                C & StdCall & Fast Calling Convention implementation
2040 //===----------------------------------------------------------------------===//
2041 //  StdCall calling convention seems to be standard for many Windows' API
2042 //  routines and around. It differs from C calling convention just a little:
2043 //  callee should clean up the stack, not caller. Symbols should be also
2044 //  decorated in some fancy way :) It doesn't support any vector arguments.
2045 //  For info on fast calling convention see Fast Calling Convention (tail call)
2046 //  implementation LowerX86_32FastCCCallTo.
2047
2048 /// CallIsStructReturn - Determines whether a call uses struct return
2049 /// semantics.
2050 enum StructReturnType {
2051   NotStructReturn,
2052   RegStructReturn,
2053   StackStructReturn
2054 };
2055 static StructReturnType
2056 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2057   if (Outs.empty())
2058     return NotStructReturn;
2059
2060   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2061   if (!Flags.isSRet())
2062     return NotStructReturn;
2063   if (Flags.isInReg())
2064     return RegStructReturn;
2065   return StackStructReturn;
2066 }
2067
2068 /// ArgsAreStructReturn - Determines whether a function uses struct
2069 /// return semantics.
2070 static StructReturnType
2071 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2072   if (Ins.empty())
2073     return NotStructReturn;
2074
2075   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2076   if (!Flags.isSRet())
2077     return NotStructReturn;
2078   if (Flags.isInReg())
2079     return RegStructReturn;
2080   return StackStructReturn;
2081 }
2082
2083 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2084 /// by "Src" to address "Dst" with size and alignment information specified by
2085 /// the specific parameter attribute. The copy will be passed as a byval
2086 /// function parameter.
2087 static SDValue
2088 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2089                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2090                           SDLoc dl) {
2091   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2092
2093   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2094                        /*isVolatile*/false, /*AlwaysInline=*/true,
2095                        MachinePointerInfo(), MachinePointerInfo());
2096 }
2097
2098 /// IsTailCallConvention - Return true if the calling convention is one that
2099 /// supports tail call optimization.
2100 static bool IsTailCallConvention(CallingConv::ID CC) {
2101   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2102           CC == CallingConv::HiPE);
2103 }
2104
2105 /// \brief Return true if the calling convention is a C calling convention.
2106 static bool IsCCallConvention(CallingConv::ID CC) {
2107   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2108           CC == CallingConv::X86_64_SysV);
2109 }
2110
2111 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2112   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2113     return false;
2114
2115   CallSite CS(CI);
2116   CallingConv::ID CalleeCC = CS.getCallingConv();
2117   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2118     return false;
2119
2120   return true;
2121 }
2122
2123 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2124 /// a tailcall target by changing its ABI.
2125 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2126                                    bool GuaranteedTailCallOpt) {
2127   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2128 }
2129
2130 SDValue
2131 X86TargetLowering::LowerMemArgument(SDValue Chain,
2132                                     CallingConv::ID CallConv,
2133                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2134                                     SDLoc dl, SelectionDAG &DAG,
2135                                     const CCValAssign &VA,
2136                                     MachineFrameInfo *MFI,
2137                                     unsigned i) const {
2138   // Create the nodes corresponding to a load from this parameter slot.
2139   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2140   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2141                               getTargetMachine().Options.GuaranteedTailCallOpt);
2142   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2143   EVT ValVT;
2144
2145   // If value is passed by pointer we have address passed instead of the value
2146   // itself.
2147   if (VA.getLocInfo() == CCValAssign::Indirect)
2148     ValVT = VA.getLocVT();
2149   else
2150     ValVT = VA.getValVT();
2151
2152   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2153   // changed with more analysis.
2154   // In case of tail call optimization mark all arguments mutable. Since they
2155   // could be overwritten by lowering of arguments in case of a tail call.
2156   if (Flags.isByVal()) {
2157     unsigned Bytes = Flags.getByValSize();
2158     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2159     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2160     return DAG.getFrameIndex(FI, getPointerTy());
2161   } else {
2162     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2163                                     VA.getLocMemOffset(), isImmutable);
2164     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2165     return DAG.getLoad(ValVT, dl, Chain, FIN,
2166                        MachinePointerInfo::getFixedStack(FI),
2167                        false, false, false, 0);
2168   }
2169 }
2170
2171 SDValue
2172 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2173                                         CallingConv::ID CallConv,
2174                                         bool isVarArg,
2175                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2176                                         SDLoc dl,
2177                                         SelectionDAG &DAG,
2178                                         SmallVectorImpl<SDValue> &InVals)
2179                                           const {
2180   MachineFunction &MF = DAG.getMachineFunction();
2181   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2182
2183   const Function* Fn = MF.getFunction();
2184   if (Fn->hasExternalLinkage() &&
2185       Subtarget->isTargetCygMing() &&
2186       Fn->getName() == "main")
2187     FuncInfo->setForceFramePointer(true);
2188
2189   MachineFrameInfo *MFI = MF.getFrameInfo();
2190   bool Is64Bit = Subtarget->is64Bit();
2191   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2192
2193   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2194          "Var args not supported with calling convention fastcc, ghc or hipe");
2195
2196   // Assign locations to all of the incoming arguments.
2197   SmallVector<CCValAssign, 16> ArgLocs;
2198   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2199                  ArgLocs, *DAG.getContext());
2200
2201   // Allocate shadow area for Win64
2202   if (IsWin64)
2203     CCInfo.AllocateStack(32, 8);
2204
2205   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2206
2207   unsigned LastVal = ~0U;
2208   SDValue ArgValue;
2209   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2210     CCValAssign &VA = ArgLocs[i];
2211     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2212     // places.
2213     assert(VA.getValNo() != LastVal &&
2214            "Don't support value assigned to multiple locs yet");
2215     (void)LastVal;
2216     LastVal = VA.getValNo();
2217
2218     if (VA.isRegLoc()) {
2219       EVT RegVT = VA.getLocVT();
2220       const TargetRegisterClass *RC;
2221       if (RegVT == MVT::i32)
2222         RC = &X86::GR32RegClass;
2223       else if (Is64Bit && RegVT == MVT::i64)
2224         RC = &X86::GR64RegClass;
2225       else if (RegVT == MVT::f32)
2226         RC = &X86::FR32RegClass;
2227       else if (RegVT == MVT::f64)
2228         RC = &X86::FR64RegClass;
2229       else if (RegVT.is512BitVector())
2230         RC = &X86::VR512RegClass;
2231       else if (RegVT.is256BitVector())
2232         RC = &X86::VR256RegClass;
2233       else if (RegVT.is128BitVector())
2234         RC = &X86::VR128RegClass;
2235       else if (RegVT == MVT::x86mmx)
2236         RC = &X86::VR64RegClass;
2237       else if (RegVT == MVT::i1)
2238         RC = &X86::VK1RegClass;
2239       else if (RegVT == MVT::v8i1)
2240         RC = &X86::VK8RegClass;
2241       else if (RegVT == MVT::v16i1)
2242         RC = &X86::VK16RegClass;
2243       else
2244         llvm_unreachable("Unknown argument type!");
2245
2246       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2247       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2248
2249       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2250       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2251       // right size.
2252       if (VA.getLocInfo() == CCValAssign::SExt)
2253         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2254                                DAG.getValueType(VA.getValVT()));
2255       else if (VA.getLocInfo() == CCValAssign::ZExt)
2256         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2257                                DAG.getValueType(VA.getValVT()));
2258       else if (VA.getLocInfo() == CCValAssign::BCvt)
2259         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2260
2261       if (VA.isExtInLoc()) {
2262         // Handle MMX values passed in XMM regs.
2263         if (RegVT.isVector())
2264           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2265         else
2266           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2267       }
2268     } else {
2269       assert(VA.isMemLoc());
2270       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2271     }
2272
2273     // If value is passed via pointer - do a load.
2274     if (VA.getLocInfo() == CCValAssign::Indirect)
2275       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2276                              MachinePointerInfo(), false, false, false, 0);
2277
2278     InVals.push_back(ArgValue);
2279   }
2280
2281   // The x86-64 ABIs require that for returning structs by value we copy
2282   // the sret argument into %rax/%eax (depending on ABI) for the return.
2283   // Win32 requires us to put the sret argument to %eax as well.
2284   // Save the argument into a virtual register so that we can access it
2285   // from the return points.
2286   if (MF.getFunction()->hasStructRetAttr() &&
2287       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2288     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2289     unsigned Reg = FuncInfo->getSRetReturnReg();
2290     if (!Reg) {
2291       MVT PtrTy = getPointerTy();
2292       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2293       FuncInfo->setSRetReturnReg(Reg);
2294     }
2295     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2296     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2297   }
2298
2299   unsigned StackSize = CCInfo.getNextStackOffset();
2300   // Align stack specially for tail calls.
2301   if (FuncIsMadeTailCallSafe(CallConv,
2302                              MF.getTarget().Options.GuaranteedTailCallOpt))
2303     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2304
2305   // If the function takes variable number of arguments, make a frame index for
2306   // the start of the first vararg value... for expansion of llvm.va_start.
2307   if (isVarArg) {
2308     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2309                     CallConv != CallingConv::X86_ThisCall)) {
2310       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2311     }
2312     if (Is64Bit) {
2313       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2314
2315       // FIXME: We should really autogenerate these arrays
2316       static const uint16_t GPR64ArgRegsWin64[] = {
2317         X86::RCX, X86::RDX, X86::R8,  X86::R9
2318       };
2319       static const uint16_t GPR64ArgRegs64Bit[] = {
2320         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2321       };
2322       static const uint16_t XMMArgRegs64Bit[] = {
2323         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2324         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2325       };
2326       const uint16_t *GPR64ArgRegs;
2327       unsigned NumXMMRegs = 0;
2328
2329       if (IsWin64) {
2330         // The XMM registers which might contain var arg parameters are shadowed
2331         // in their paired GPR.  So we only need to save the GPR to their home
2332         // slots.
2333         TotalNumIntRegs = 4;
2334         GPR64ArgRegs = GPR64ArgRegsWin64;
2335       } else {
2336         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2337         GPR64ArgRegs = GPR64ArgRegs64Bit;
2338
2339         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2340                                                 TotalNumXMMRegs);
2341       }
2342       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2343                                                        TotalNumIntRegs);
2344
2345       bool NoImplicitFloatOps = Fn->getAttributes().
2346         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2347       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2348              "SSE register cannot be used when SSE is disabled!");
2349       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2350                NoImplicitFloatOps) &&
2351              "SSE register cannot be used when SSE is disabled!");
2352       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2353           !Subtarget->hasSSE1())
2354         // Kernel mode asks for SSE to be disabled, so don't push them
2355         // on the stack.
2356         TotalNumXMMRegs = 0;
2357
2358       if (IsWin64) {
2359         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2360         // Get to the caller-allocated home save location.  Add 8 to account
2361         // for the return address.
2362         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2363         FuncInfo->setRegSaveFrameIndex(
2364           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2365         // Fixup to set vararg frame on shadow area (4 x i64).
2366         if (NumIntRegs < 4)
2367           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2368       } else {
2369         // For X86-64, if there are vararg parameters that are passed via
2370         // registers, then we must store them to their spots on the stack so
2371         // they may be loaded by deferencing the result of va_next.
2372         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2373         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2374         FuncInfo->setRegSaveFrameIndex(
2375           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2376                                false));
2377       }
2378
2379       // Store the integer parameter registers.
2380       SmallVector<SDValue, 8> MemOps;
2381       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2382                                         getPointerTy());
2383       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2384       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2385         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2386                                   DAG.getIntPtrConstant(Offset));
2387         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2388                                      &X86::GR64RegClass);
2389         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2390         SDValue Store =
2391           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2392                        MachinePointerInfo::getFixedStack(
2393                          FuncInfo->getRegSaveFrameIndex(), Offset),
2394                        false, false, 0);
2395         MemOps.push_back(Store);
2396         Offset += 8;
2397       }
2398
2399       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2400         // Now store the XMM (fp + vector) parameter registers.
2401         SmallVector<SDValue, 11> SaveXMMOps;
2402         SaveXMMOps.push_back(Chain);
2403
2404         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2405         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2406         SaveXMMOps.push_back(ALVal);
2407
2408         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2409                                FuncInfo->getRegSaveFrameIndex()));
2410         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2411                                FuncInfo->getVarArgsFPOffset()));
2412
2413         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2414           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2415                                        &X86::VR128RegClass);
2416           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2417           SaveXMMOps.push_back(Val);
2418         }
2419         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2420                                      MVT::Other,
2421                                      &SaveXMMOps[0], SaveXMMOps.size()));
2422       }
2423
2424       if (!MemOps.empty())
2425         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2426                             &MemOps[0], MemOps.size());
2427     }
2428   }
2429
2430   // Some CCs need callee pop.
2431   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2432                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2433     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2434   } else {
2435     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2436     // If this is an sret function, the return should pop the hidden pointer.
2437     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2438         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2439         argsAreStructReturn(Ins) == StackStructReturn)
2440       FuncInfo->setBytesToPopOnReturn(4);
2441   }
2442
2443   if (!Is64Bit) {
2444     // RegSaveFrameIndex is X86-64 only.
2445     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2446     if (CallConv == CallingConv::X86_FastCall ||
2447         CallConv == CallingConv::X86_ThisCall)
2448       // fastcc functions can't have varargs.
2449       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2450   }
2451
2452   FuncInfo->setArgumentStackSize(StackSize);
2453
2454   return Chain;
2455 }
2456
2457 SDValue
2458 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2459                                     SDValue StackPtr, SDValue Arg,
2460                                     SDLoc dl, SelectionDAG &DAG,
2461                                     const CCValAssign &VA,
2462                                     ISD::ArgFlagsTy Flags) const {
2463   unsigned LocMemOffset = VA.getLocMemOffset();
2464   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2465   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2466   if (Flags.isByVal())
2467     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2468
2469   return DAG.getStore(Chain, dl, Arg, PtrOff,
2470                       MachinePointerInfo::getStack(LocMemOffset),
2471                       false, false, 0);
2472 }
2473
2474 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2475 /// optimization is performed and it is required.
2476 SDValue
2477 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2478                                            SDValue &OutRetAddr, SDValue Chain,
2479                                            bool IsTailCall, bool Is64Bit,
2480                                            int FPDiff, SDLoc dl) const {
2481   // Adjust the Return address stack slot.
2482   EVT VT = getPointerTy();
2483   OutRetAddr = getReturnAddressFrameIndex(DAG);
2484
2485   // Load the "old" Return address.
2486   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2487                            false, false, false, 0);
2488   return SDValue(OutRetAddr.getNode(), 1);
2489 }
2490
2491 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2492 /// optimization is performed and it is required (FPDiff!=0).
2493 static SDValue
2494 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2495                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2496                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2497   // Store the return address to the appropriate stack slot.
2498   if (!FPDiff) return Chain;
2499   // Calculate the new stack slot for the return address.
2500   int NewReturnAddrFI =
2501     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2502                                          false);
2503   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2504   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2505                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2506                        false, false, 0);
2507   return Chain;
2508 }
2509
2510 SDValue
2511 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2512                              SmallVectorImpl<SDValue> &InVals) const {
2513   SelectionDAG &DAG                     = CLI.DAG;
2514   SDLoc &dl                             = CLI.DL;
2515   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2516   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2517   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2518   SDValue Chain                         = CLI.Chain;
2519   SDValue Callee                        = CLI.Callee;
2520   CallingConv::ID CallConv              = CLI.CallConv;
2521   bool &isTailCall                      = CLI.IsTailCall;
2522   bool isVarArg                         = CLI.IsVarArg;
2523
2524   MachineFunction &MF = DAG.getMachineFunction();
2525   bool Is64Bit        = Subtarget->is64Bit();
2526   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2527   StructReturnType SR = callIsStructReturn(Outs);
2528   bool IsSibcall      = false;
2529
2530   if (MF.getTarget().Options.DisableTailCalls)
2531     isTailCall = false;
2532
2533   if (isTailCall) {
2534     // Check if it's really possible to do a tail call.
2535     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2536                     isVarArg, SR != NotStructReturn,
2537                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2538                     Outs, OutVals, Ins, DAG);
2539
2540     // Sibcalls are automatically detected tailcalls which do not require
2541     // ABI changes.
2542     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2543       IsSibcall = true;
2544
2545     if (isTailCall)
2546       ++NumTailCalls;
2547   }
2548
2549   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2550          "Var args not supported with calling convention fastcc, ghc or hipe");
2551
2552   // Analyze operands of the call, assigning locations to each operand.
2553   SmallVector<CCValAssign, 16> ArgLocs;
2554   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2555                  ArgLocs, *DAG.getContext());
2556
2557   // Allocate shadow area for Win64
2558   if (IsWin64)
2559     CCInfo.AllocateStack(32, 8);
2560
2561   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2562
2563   // Get a count of how many bytes are to be pushed on the stack.
2564   unsigned NumBytes = CCInfo.getNextStackOffset();
2565   if (IsSibcall)
2566     // This is a sibcall. The memory operands are available in caller's
2567     // own caller's stack.
2568     NumBytes = 0;
2569   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2570            IsTailCallConvention(CallConv))
2571     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2572
2573   int FPDiff = 0;
2574   if (isTailCall && !IsSibcall) {
2575     // Lower arguments at fp - stackoffset + fpdiff.
2576     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2577     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2578
2579     FPDiff = NumBytesCallerPushed - NumBytes;
2580
2581     // Set the delta of movement of the returnaddr stackslot.
2582     // But only set if delta is greater than previous delta.
2583     if (FPDiff < X86Info->getTCReturnAddrDelta())
2584       X86Info->setTCReturnAddrDelta(FPDiff);
2585   }
2586
2587   unsigned NumBytesToPush = NumBytes;
2588   unsigned NumBytesToPop = NumBytes;
2589
2590   // If we have an inalloca argument, all stack space has already been allocated
2591   // for us and be right at the top of the stack.  We don't support multiple
2592   // arguments passed in memory when using inalloca.
2593   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2594     NumBytesToPush = 0;
2595     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2596            "an inalloca argument must be the only memory argument");
2597   }
2598
2599   if (!IsSibcall)
2600     Chain = DAG.getCALLSEQ_START(
2601         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2602
2603   SDValue RetAddrFrIdx;
2604   // Load return address for tail calls.
2605   if (isTailCall && FPDiff)
2606     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2607                                     Is64Bit, FPDiff, dl);
2608
2609   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2610   SmallVector<SDValue, 8> MemOpChains;
2611   SDValue StackPtr;
2612
2613   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2614   // of tail call optimization arguments are handle later.
2615   const X86RegisterInfo *RegInfo =
2616     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2617   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2618     // Skip inalloca arguments, they have already been written.
2619     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2620     if (Flags.isInAlloca())
2621       continue;
2622
2623     CCValAssign &VA = ArgLocs[i];
2624     EVT RegVT = VA.getLocVT();
2625     SDValue Arg = OutVals[i];
2626     bool isByVal = Flags.isByVal();
2627
2628     // Promote the value if needed.
2629     switch (VA.getLocInfo()) {
2630     default: llvm_unreachable("Unknown loc info!");
2631     case CCValAssign::Full: break;
2632     case CCValAssign::SExt:
2633       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2634       break;
2635     case CCValAssign::ZExt:
2636       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2637       break;
2638     case CCValAssign::AExt:
2639       if (RegVT.is128BitVector()) {
2640         // Special case: passing MMX values in XMM registers.
2641         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2642         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2643         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2644       } else
2645         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2646       break;
2647     case CCValAssign::BCvt:
2648       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2649       break;
2650     case CCValAssign::Indirect: {
2651       // Store the argument.
2652       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2653       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2654       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2655                            MachinePointerInfo::getFixedStack(FI),
2656                            false, false, 0);
2657       Arg = SpillSlot;
2658       break;
2659     }
2660     }
2661
2662     if (VA.isRegLoc()) {
2663       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2664       if (isVarArg && IsWin64) {
2665         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2666         // shadow reg if callee is a varargs function.
2667         unsigned ShadowReg = 0;
2668         switch (VA.getLocReg()) {
2669         case X86::XMM0: ShadowReg = X86::RCX; break;
2670         case X86::XMM1: ShadowReg = X86::RDX; break;
2671         case X86::XMM2: ShadowReg = X86::R8; break;
2672         case X86::XMM3: ShadowReg = X86::R9; break;
2673         }
2674         if (ShadowReg)
2675           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2676       }
2677     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2678       assert(VA.isMemLoc());
2679       if (StackPtr.getNode() == 0)
2680         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2681                                       getPointerTy());
2682       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2683                                              dl, DAG, VA, Flags));
2684     }
2685   }
2686
2687   if (!MemOpChains.empty())
2688     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2689                         &MemOpChains[0], MemOpChains.size());
2690
2691   if (Subtarget->isPICStyleGOT()) {
2692     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2693     // GOT pointer.
2694     if (!isTailCall) {
2695       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2696                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2697     } else {
2698       // If we are tail calling and generating PIC/GOT style code load the
2699       // address of the callee into ECX. The value in ecx is used as target of
2700       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2701       // for tail calls on PIC/GOT architectures. Normally we would just put the
2702       // address of GOT into ebx and then call target@PLT. But for tail calls
2703       // ebx would be restored (since ebx is callee saved) before jumping to the
2704       // target@PLT.
2705
2706       // Note: The actual moving to ECX is done further down.
2707       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2708       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2709           !G->getGlobal()->hasProtectedVisibility())
2710         Callee = LowerGlobalAddress(Callee, DAG);
2711       else if (isa<ExternalSymbolSDNode>(Callee))
2712         Callee = LowerExternalSymbol(Callee, DAG);
2713     }
2714   }
2715
2716   if (Is64Bit && isVarArg && !IsWin64) {
2717     // From AMD64 ABI document:
2718     // For calls that may call functions that use varargs or stdargs
2719     // (prototype-less calls or calls to functions containing ellipsis (...) in
2720     // the declaration) %al is used as hidden argument to specify the number
2721     // of SSE registers used. The contents of %al do not need to match exactly
2722     // the number of registers, but must be an ubound on the number of SSE
2723     // registers used and is in the range 0 - 8 inclusive.
2724
2725     // Count the number of XMM registers allocated.
2726     static const uint16_t XMMArgRegs[] = {
2727       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2728       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2729     };
2730     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2731     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2732            && "SSE registers cannot be used when SSE is disabled");
2733
2734     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2735                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2736   }
2737
2738   // For tail calls lower the arguments to the 'real' stack slot.
2739   if (isTailCall) {
2740     // Force all the incoming stack arguments to be loaded from the stack
2741     // before any new outgoing arguments are stored to the stack, because the
2742     // outgoing stack slots may alias the incoming argument stack slots, and
2743     // the alias isn't otherwise explicit. This is slightly more conservative
2744     // than necessary, because it means that each store effectively depends
2745     // on every argument instead of just those arguments it would clobber.
2746     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2747
2748     SmallVector<SDValue, 8> MemOpChains2;
2749     SDValue FIN;
2750     int FI = 0;
2751     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2752       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2753         CCValAssign &VA = ArgLocs[i];
2754         if (VA.isRegLoc())
2755           continue;
2756         assert(VA.isMemLoc());
2757         SDValue Arg = OutVals[i];
2758         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2759         // Create frame index.
2760         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2761         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2762         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2763         FIN = DAG.getFrameIndex(FI, getPointerTy());
2764
2765         if (Flags.isByVal()) {
2766           // Copy relative to framepointer.
2767           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2768           if (StackPtr.getNode() == 0)
2769             StackPtr = DAG.getCopyFromReg(Chain, dl,
2770                                           RegInfo->getStackRegister(),
2771                                           getPointerTy());
2772           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2773
2774           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2775                                                            ArgChain,
2776                                                            Flags, DAG, dl));
2777         } else {
2778           // Store relative to framepointer.
2779           MemOpChains2.push_back(
2780             DAG.getStore(ArgChain, dl, Arg, FIN,
2781                          MachinePointerInfo::getFixedStack(FI),
2782                          false, false, 0));
2783         }
2784       }
2785     }
2786
2787     if (!MemOpChains2.empty())
2788       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2789                           &MemOpChains2[0], MemOpChains2.size());
2790
2791     // Store the return address to the appropriate stack slot.
2792     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2793                                      getPointerTy(), RegInfo->getSlotSize(),
2794                                      FPDiff, dl);
2795   }
2796
2797   // Build a sequence of copy-to-reg nodes chained together with token chain
2798   // and flag operands which copy the outgoing args into registers.
2799   SDValue InFlag;
2800   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2801     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2802                              RegsToPass[i].second, InFlag);
2803     InFlag = Chain.getValue(1);
2804   }
2805
2806   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2807     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2808     // In the 64-bit large code model, we have to make all calls
2809     // through a register, since the call instruction's 32-bit
2810     // pc-relative offset may not be large enough to hold the whole
2811     // address.
2812   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2813     // If the callee is a GlobalAddress node (quite common, every direct call
2814     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2815     // it.
2816
2817     // We should use extra load for direct calls to dllimported functions in
2818     // non-JIT mode.
2819     const GlobalValue *GV = G->getGlobal();
2820     if (!GV->hasDLLImportStorageClass()) {
2821       unsigned char OpFlags = 0;
2822       bool ExtraLoad = false;
2823       unsigned WrapperKind = ISD::DELETED_NODE;
2824
2825       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2826       // external symbols most go through the PLT in PIC mode.  If the symbol
2827       // has hidden or protected visibility, or if it is static or local, then
2828       // we don't need to use the PLT - we can directly call it.
2829       if (Subtarget->isTargetELF() &&
2830           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2831           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2832         OpFlags = X86II::MO_PLT;
2833       } else if (Subtarget->isPICStyleStubAny() &&
2834                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2835                  (!Subtarget->getTargetTriple().isMacOSX() ||
2836                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2837         // PC-relative references to external symbols should go through $stub,
2838         // unless we're building with the leopard linker or later, which
2839         // automatically synthesizes these stubs.
2840         OpFlags = X86II::MO_DARWIN_STUB;
2841       } else if (Subtarget->isPICStyleRIPRel() &&
2842                  isa<Function>(GV) &&
2843                  cast<Function>(GV)->getAttributes().
2844                    hasAttribute(AttributeSet::FunctionIndex,
2845                                 Attribute::NonLazyBind)) {
2846         // If the function is marked as non-lazy, generate an indirect call
2847         // which loads from the GOT directly. This avoids runtime overhead
2848         // at the cost of eager binding (and one extra byte of encoding).
2849         OpFlags = X86II::MO_GOTPCREL;
2850         WrapperKind = X86ISD::WrapperRIP;
2851         ExtraLoad = true;
2852       }
2853
2854       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2855                                           G->getOffset(), OpFlags);
2856
2857       // Add a wrapper if needed.
2858       if (WrapperKind != ISD::DELETED_NODE)
2859         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2860       // Add extra indirection if needed.
2861       if (ExtraLoad)
2862         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2863                              MachinePointerInfo::getGOT(),
2864                              false, false, false, 0);
2865     }
2866   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2867     unsigned char OpFlags = 0;
2868
2869     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2870     // external symbols should go through the PLT.
2871     if (Subtarget->isTargetELF() &&
2872         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2873       OpFlags = X86II::MO_PLT;
2874     } else if (Subtarget->isPICStyleStubAny() &&
2875                (!Subtarget->getTargetTriple().isMacOSX() ||
2876                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2877       // PC-relative references to external symbols should go through $stub,
2878       // unless we're building with the leopard linker or later, which
2879       // automatically synthesizes these stubs.
2880       OpFlags = X86II::MO_DARWIN_STUB;
2881     }
2882
2883     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2884                                          OpFlags);
2885   }
2886
2887   // Returns a chain & a flag for retval copy to use.
2888   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2889   SmallVector<SDValue, 8> Ops;
2890
2891   if (!IsSibcall && isTailCall) {
2892     Chain = DAG.getCALLSEQ_END(Chain,
2893                                DAG.getIntPtrConstant(NumBytesToPop, true),
2894                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2895     InFlag = Chain.getValue(1);
2896   }
2897
2898   Ops.push_back(Chain);
2899   Ops.push_back(Callee);
2900
2901   if (isTailCall)
2902     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2903
2904   // Add argument registers to the end of the list so that they are known live
2905   // into the call.
2906   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2907     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2908                                   RegsToPass[i].second.getValueType()));
2909
2910   // Add a register mask operand representing the call-preserved registers.
2911   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2912   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2913   assert(Mask && "Missing call preserved mask for calling convention");
2914   Ops.push_back(DAG.getRegisterMask(Mask));
2915
2916   if (InFlag.getNode())
2917     Ops.push_back(InFlag);
2918
2919   if (isTailCall) {
2920     // We used to do:
2921     //// If this is the first return lowered for this function, add the regs
2922     //// to the liveout set for the function.
2923     // This isn't right, although it's probably harmless on x86; liveouts
2924     // should be computed from returns not tail calls.  Consider a void
2925     // function making a tail call to a function returning int.
2926     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2927   }
2928
2929   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2930   InFlag = Chain.getValue(1);
2931
2932   // Create the CALLSEQ_END node.
2933   unsigned NumBytesForCalleeToPop;
2934   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2935                        getTargetMachine().Options.GuaranteedTailCallOpt))
2936     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2937   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2938            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2939            SR == StackStructReturn)
2940     // If this is a call to a struct-return function, the callee
2941     // pops the hidden struct pointer, so we have to push it back.
2942     // This is common for Darwin/X86, Linux & Mingw32 targets.
2943     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2944     NumBytesForCalleeToPop = 4;
2945   else
2946     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2947
2948   // Returns a flag for retval copy to use.
2949   if (!IsSibcall) {
2950     Chain = DAG.getCALLSEQ_END(Chain,
2951                                DAG.getIntPtrConstant(NumBytesToPop, true),
2952                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2953                                                      true),
2954                                InFlag, dl);
2955     InFlag = Chain.getValue(1);
2956   }
2957
2958   // Handle result values, copying them out of physregs into vregs that we
2959   // return.
2960   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2961                          Ins, dl, DAG, InVals);
2962 }
2963
2964 //===----------------------------------------------------------------------===//
2965 //                Fast Calling Convention (tail call) implementation
2966 //===----------------------------------------------------------------------===//
2967
2968 //  Like std call, callee cleans arguments, convention except that ECX is
2969 //  reserved for storing the tail called function address. Only 2 registers are
2970 //  free for argument passing (inreg). Tail call optimization is performed
2971 //  provided:
2972 //                * tailcallopt is enabled
2973 //                * caller/callee are fastcc
2974 //  On X86_64 architecture with GOT-style position independent code only local
2975 //  (within module) calls are supported at the moment.
2976 //  To keep the stack aligned according to platform abi the function
2977 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2978 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2979 //  If a tail called function callee has more arguments than the caller the
2980 //  caller needs to make sure that there is room to move the RETADDR to. This is
2981 //  achieved by reserving an area the size of the argument delta right after the
2982 //  original REtADDR, but before the saved framepointer or the spilled registers
2983 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2984 //  stack layout:
2985 //    arg1
2986 //    arg2
2987 //    RETADDR
2988 //    [ new RETADDR
2989 //      move area ]
2990 //    (possible EBP)
2991 //    ESI
2992 //    EDI
2993 //    local1 ..
2994
2995 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2996 /// for a 16 byte align requirement.
2997 unsigned
2998 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2999                                                SelectionDAG& DAG) const {
3000   MachineFunction &MF = DAG.getMachineFunction();
3001   const TargetMachine &TM = MF.getTarget();
3002   const X86RegisterInfo *RegInfo =
3003     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3004   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3005   unsigned StackAlignment = TFI.getStackAlignment();
3006   uint64_t AlignMask = StackAlignment - 1;
3007   int64_t Offset = StackSize;
3008   unsigned SlotSize = RegInfo->getSlotSize();
3009   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3010     // Number smaller than 12 so just add the difference.
3011     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3012   } else {
3013     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3014     Offset = ((~AlignMask) & Offset) + StackAlignment +
3015       (StackAlignment-SlotSize);
3016   }
3017   return Offset;
3018 }
3019
3020 /// MatchingStackOffset - Return true if the given stack call argument is
3021 /// already available in the same position (relatively) of the caller's
3022 /// incoming argument stack.
3023 static
3024 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3025                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3026                          const X86InstrInfo *TII) {
3027   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3028   int FI = INT_MAX;
3029   if (Arg.getOpcode() == ISD::CopyFromReg) {
3030     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3031     if (!TargetRegisterInfo::isVirtualRegister(VR))
3032       return false;
3033     MachineInstr *Def = MRI->getVRegDef(VR);
3034     if (!Def)
3035       return false;
3036     if (!Flags.isByVal()) {
3037       if (!TII->isLoadFromStackSlot(Def, FI))
3038         return false;
3039     } else {
3040       unsigned Opcode = Def->getOpcode();
3041       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3042           Def->getOperand(1).isFI()) {
3043         FI = Def->getOperand(1).getIndex();
3044         Bytes = Flags.getByValSize();
3045       } else
3046         return false;
3047     }
3048   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3049     if (Flags.isByVal())
3050       // ByVal argument is passed in as a pointer but it's now being
3051       // dereferenced. e.g.
3052       // define @foo(%struct.X* %A) {
3053       //   tail call @bar(%struct.X* byval %A)
3054       // }
3055       return false;
3056     SDValue Ptr = Ld->getBasePtr();
3057     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3058     if (!FINode)
3059       return false;
3060     FI = FINode->getIndex();
3061   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3062     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3063     FI = FINode->getIndex();
3064     Bytes = Flags.getByValSize();
3065   } else
3066     return false;
3067
3068   assert(FI != INT_MAX);
3069   if (!MFI->isFixedObjectIndex(FI))
3070     return false;
3071   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3072 }
3073
3074 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3075 /// for tail call optimization. Targets which want to do tail call
3076 /// optimization should implement this function.
3077 bool
3078 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3079                                                      CallingConv::ID CalleeCC,
3080                                                      bool isVarArg,
3081                                                      bool isCalleeStructRet,
3082                                                      bool isCallerStructRet,
3083                                                      Type *RetTy,
3084                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3085                                     const SmallVectorImpl<SDValue> &OutVals,
3086                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3087                                                      SelectionDAG &DAG) const {
3088   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3089     return false;
3090
3091   // If -tailcallopt is specified, make fastcc functions tail-callable.
3092   const MachineFunction &MF = DAG.getMachineFunction();
3093   const Function *CallerF = MF.getFunction();
3094
3095   // If the function return type is x86_fp80 and the callee return type is not,
3096   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3097   // perform a tailcall optimization here.
3098   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3099     return false;
3100
3101   CallingConv::ID CallerCC = CallerF->getCallingConv();
3102   bool CCMatch = CallerCC == CalleeCC;
3103   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3104   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3105
3106   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3107     if (IsTailCallConvention(CalleeCC) && CCMatch)
3108       return true;
3109     return false;
3110   }
3111
3112   // Look for obvious safe cases to perform tail call optimization that do not
3113   // require ABI changes. This is what gcc calls sibcall.
3114
3115   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3116   // emit a special epilogue.
3117   const X86RegisterInfo *RegInfo =
3118     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3119   if (RegInfo->needsStackRealignment(MF))
3120     return false;
3121
3122   // Also avoid sibcall optimization if either caller or callee uses struct
3123   // return semantics.
3124   if (isCalleeStructRet || isCallerStructRet)
3125     return false;
3126
3127   // An stdcall/thiscall caller is expected to clean up its arguments; the
3128   // callee isn't going to do that.
3129   // FIXME: this is more restrictive than needed. We could produce a tailcall
3130   // when the stack adjustment matches. For example, with a thiscall that takes
3131   // only one argument.
3132   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3133                    CallerCC == CallingConv::X86_ThisCall))
3134     return false;
3135
3136   // Do not sibcall optimize vararg calls unless all arguments are passed via
3137   // registers.
3138   if (isVarArg && !Outs.empty()) {
3139
3140     // Optimizing for varargs on Win64 is unlikely to be safe without
3141     // additional testing.
3142     if (IsCalleeWin64 || IsCallerWin64)
3143       return false;
3144
3145     SmallVector<CCValAssign, 16> ArgLocs;
3146     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3147                    getTargetMachine(), ArgLocs, *DAG.getContext());
3148
3149     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3150     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3151       if (!ArgLocs[i].isRegLoc())
3152         return false;
3153   }
3154
3155   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3156   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3157   // this into a sibcall.
3158   bool Unused = false;
3159   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3160     if (!Ins[i].Used) {
3161       Unused = true;
3162       break;
3163     }
3164   }
3165   if (Unused) {
3166     SmallVector<CCValAssign, 16> RVLocs;
3167     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3168                    getTargetMachine(), RVLocs, *DAG.getContext());
3169     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3170     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3171       CCValAssign &VA = RVLocs[i];
3172       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3173         return false;
3174     }
3175   }
3176
3177   // If the calling conventions do not match, then we'd better make sure the
3178   // results are returned in the same way as what the caller expects.
3179   if (!CCMatch) {
3180     SmallVector<CCValAssign, 16> RVLocs1;
3181     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3182                     getTargetMachine(), RVLocs1, *DAG.getContext());
3183     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3184
3185     SmallVector<CCValAssign, 16> RVLocs2;
3186     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3187                     getTargetMachine(), RVLocs2, *DAG.getContext());
3188     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3189
3190     if (RVLocs1.size() != RVLocs2.size())
3191       return false;
3192     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3193       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3194         return false;
3195       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3196         return false;
3197       if (RVLocs1[i].isRegLoc()) {
3198         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3199           return false;
3200       } else {
3201         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3202           return false;
3203       }
3204     }
3205   }
3206
3207   // If the callee takes no arguments then go on to check the results of the
3208   // call.
3209   if (!Outs.empty()) {
3210     // Check if stack adjustment is needed. For now, do not do this if any
3211     // argument is passed on the stack.
3212     SmallVector<CCValAssign, 16> ArgLocs;
3213     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3214                    getTargetMachine(), ArgLocs, *DAG.getContext());
3215
3216     // Allocate shadow area for Win64
3217     if (IsCalleeWin64)
3218       CCInfo.AllocateStack(32, 8);
3219
3220     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3221     if (CCInfo.getNextStackOffset()) {
3222       MachineFunction &MF = DAG.getMachineFunction();
3223       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3224         return false;
3225
3226       // Check if the arguments are already laid out in the right way as
3227       // the caller's fixed stack objects.
3228       MachineFrameInfo *MFI = MF.getFrameInfo();
3229       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3230       const X86InstrInfo *TII =
3231         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3232       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3233         CCValAssign &VA = ArgLocs[i];
3234         SDValue Arg = OutVals[i];
3235         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3236         if (VA.getLocInfo() == CCValAssign::Indirect)
3237           return false;
3238         if (!VA.isRegLoc()) {
3239           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3240                                    MFI, MRI, TII))
3241             return false;
3242         }
3243       }
3244     }
3245
3246     // If the tailcall address may be in a register, then make sure it's
3247     // possible to register allocate for it. In 32-bit, the call address can
3248     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3249     // callee-saved registers are restored. These happen to be the same
3250     // registers used to pass 'inreg' arguments so watch out for those.
3251     if (!Subtarget->is64Bit() &&
3252         ((!isa<GlobalAddressSDNode>(Callee) &&
3253           !isa<ExternalSymbolSDNode>(Callee)) ||
3254          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3255       unsigned NumInRegs = 0;
3256       // In PIC we need an extra register to formulate the address computation
3257       // for the callee.
3258       unsigned MaxInRegs =
3259           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3260
3261       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3262         CCValAssign &VA = ArgLocs[i];
3263         if (!VA.isRegLoc())
3264           continue;
3265         unsigned Reg = VA.getLocReg();
3266         switch (Reg) {
3267         default: break;
3268         case X86::EAX: case X86::EDX: case X86::ECX:
3269           if (++NumInRegs == MaxInRegs)
3270             return false;
3271           break;
3272         }
3273       }
3274     }
3275   }
3276
3277   return true;
3278 }
3279
3280 FastISel *
3281 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3282                                   const TargetLibraryInfo *libInfo) const {
3283   return X86::createFastISel(funcInfo, libInfo);
3284 }
3285
3286 //===----------------------------------------------------------------------===//
3287 //                           Other Lowering Hooks
3288 //===----------------------------------------------------------------------===//
3289
3290 static bool MayFoldLoad(SDValue Op) {
3291   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3292 }
3293
3294 static bool MayFoldIntoStore(SDValue Op) {
3295   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3296 }
3297
3298 static bool isTargetShuffle(unsigned Opcode) {
3299   switch(Opcode) {
3300   default: return false;
3301   case X86ISD::PSHUFD:
3302   case X86ISD::PSHUFHW:
3303   case X86ISD::PSHUFLW:
3304   case X86ISD::SHUFP:
3305   case X86ISD::PALIGNR:
3306   case X86ISD::MOVLHPS:
3307   case X86ISD::MOVLHPD:
3308   case X86ISD::MOVHLPS:
3309   case X86ISD::MOVLPS:
3310   case X86ISD::MOVLPD:
3311   case X86ISD::MOVSHDUP:
3312   case X86ISD::MOVSLDUP:
3313   case X86ISD::MOVDDUP:
3314   case X86ISD::MOVSS:
3315   case X86ISD::MOVSD:
3316   case X86ISD::UNPCKL:
3317   case X86ISD::UNPCKH:
3318   case X86ISD::VPERMILP:
3319   case X86ISD::VPERM2X128:
3320   case X86ISD::VPERMI:
3321     return true;
3322   }
3323 }
3324
3325 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3326                                     SDValue V1, SelectionDAG &DAG) {
3327   switch(Opc) {
3328   default: llvm_unreachable("Unknown x86 shuffle node");
3329   case X86ISD::MOVSHDUP:
3330   case X86ISD::MOVSLDUP:
3331   case X86ISD::MOVDDUP:
3332     return DAG.getNode(Opc, dl, VT, V1);
3333   }
3334 }
3335
3336 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3337                                     SDValue V1, unsigned TargetMask,
3338                                     SelectionDAG &DAG) {
3339   switch(Opc) {
3340   default: llvm_unreachable("Unknown x86 shuffle node");
3341   case X86ISD::PSHUFD:
3342   case X86ISD::PSHUFHW:
3343   case X86ISD::PSHUFLW:
3344   case X86ISD::VPERMILP:
3345   case X86ISD::VPERMI:
3346     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3347   }
3348 }
3349
3350 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3351                                     SDValue V1, SDValue V2, unsigned TargetMask,
3352                                     SelectionDAG &DAG) {
3353   switch(Opc) {
3354   default: llvm_unreachable("Unknown x86 shuffle node");
3355   case X86ISD::PALIGNR:
3356   case X86ISD::SHUFP:
3357   case X86ISD::VPERM2X128:
3358     return DAG.getNode(Opc, dl, VT, V1, V2,
3359                        DAG.getConstant(TargetMask, MVT::i8));
3360   }
3361 }
3362
3363 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3364                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3365   switch(Opc) {
3366   default: llvm_unreachable("Unknown x86 shuffle node");
3367   case X86ISD::MOVLHPS:
3368   case X86ISD::MOVLHPD:
3369   case X86ISD::MOVHLPS:
3370   case X86ISD::MOVLPS:
3371   case X86ISD::MOVLPD:
3372   case X86ISD::MOVSS:
3373   case X86ISD::MOVSD:
3374   case X86ISD::UNPCKL:
3375   case X86ISD::UNPCKH:
3376     return DAG.getNode(Opc, dl, VT, V1, V2);
3377   }
3378 }
3379
3380 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3381   MachineFunction &MF = DAG.getMachineFunction();
3382   const X86RegisterInfo *RegInfo =
3383     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3384   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3385   int ReturnAddrIndex = FuncInfo->getRAIndex();
3386
3387   if (ReturnAddrIndex == 0) {
3388     // Set up a frame object for the return address.
3389     unsigned SlotSize = RegInfo->getSlotSize();
3390     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3391                                                            -(int64_t)SlotSize,
3392                                                            false);
3393     FuncInfo->setRAIndex(ReturnAddrIndex);
3394   }
3395
3396   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3397 }
3398
3399 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3400                                        bool hasSymbolicDisplacement) {
3401   // Offset should fit into 32 bit immediate field.
3402   if (!isInt<32>(Offset))
3403     return false;
3404
3405   // If we don't have a symbolic displacement - we don't have any extra
3406   // restrictions.
3407   if (!hasSymbolicDisplacement)
3408     return true;
3409
3410   // FIXME: Some tweaks might be needed for medium code model.
3411   if (M != CodeModel::Small && M != CodeModel::Kernel)
3412     return false;
3413
3414   // For small code model we assume that latest object is 16MB before end of 31
3415   // bits boundary. We may also accept pretty large negative constants knowing
3416   // that all objects are in the positive half of address space.
3417   if (M == CodeModel::Small && Offset < 16*1024*1024)
3418     return true;
3419
3420   // For kernel code model we know that all object resist in the negative half
3421   // of 32bits address space. We may not accept negative offsets, since they may
3422   // be just off and we may accept pretty large positive ones.
3423   if (M == CodeModel::Kernel && Offset > 0)
3424     return true;
3425
3426   return false;
3427 }
3428
3429 /// isCalleePop - Determines whether the callee is required to pop its
3430 /// own arguments. Callee pop is necessary to support tail calls.
3431 bool X86::isCalleePop(CallingConv::ID CallingConv,
3432                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3433   if (IsVarArg)
3434     return false;
3435
3436   switch (CallingConv) {
3437   default:
3438     return false;
3439   case CallingConv::X86_StdCall:
3440     return !is64Bit;
3441   case CallingConv::X86_FastCall:
3442     return !is64Bit;
3443   case CallingConv::X86_ThisCall:
3444     return !is64Bit;
3445   case CallingConv::Fast:
3446     return TailCallOpt;
3447   case CallingConv::GHC:
3448     return TailCallOpt;
3449   case CallingConv::HiPE:
3450     return TailCallOpt;
3451   }
3452 }
3453
3454 /// \brief Return true if the condition is an unsigned comparison operation.
3455 static bool isX86CCUnsigned(unsigned X86CC) {
3456   switch (X86CC) {
3457   default: llvm_unreachable("Invalid integer condition!");
3458   case X86::COND_E:     return true;
3459   case X86::COND_G:     return false;
3460   case X86::COND_GE:    return false;
3461   case X86::COND_L:     return false;
3462   case X86::COND_LE:    return false;
3463   case X86::COND_NE:    return true;
3464   case X86::COND_B:     return true;
3465   case X86::COND_A:     return true;
3466   case X86::COND_BE:    return true;
3467   case X86::COND_AE:    return true;
3468   }
3469   llvm_unreachable("covered switch fell through?!");
3470 }
3471
3472 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3473 /// specific condition code, returning the condition code and the LHS/RHS of the
3474 /// comparison to make.
3475 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3476                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3477   if (!isFP) {
3478     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3479       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3480         // X > -1   -> X == 0, jump !sign.
3481         RHS = DAG.getConstant(0, RHS.getValueType());
3482         return X86::COND_NS;
3483       }
3484       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3485         // X < 0   -> X == 0, jump on sign.
3486         return X86::COND_S;
3487       }
3488       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3489         // X < 1   -> X <= 0
3490         RHS = DAG.getConstant(0, RHS.getValueType());
3491         return X86::COND_LE;
3492       }
3493     }
3494
3495     switch (SetCCOpcode) {
3496     default: llvm_unreachable("Invalid integer condition!");
3497     case ISD::SETEQ:  return X86::COND_E;
3498     case ISD::SETGT:  return X86::COND_G;
3499     case ISD::SETGE:  return X86::COND_GE;
3500     case ISD::SETLT:  return X86::COND_L;
3501     case ISD::SETLE:  return X86::COND_LE;
3502     case ISD::SETNE:  return X86::COND_NE;
3503     case ISD::SETULT: return X86::COND_B;
3504     case ISD::SETUGT: return X86::COND_A;
3505     case ISD::SETULE: return X86::COND_BE;
3506     case ISD::SETUGE: return X86::COND_AE;
3507     }
3508   }
3509
3510   // First determine if it is required or is profitable to flip the operands.
3511
3512   // If LHS is a foldable load, but RHS is not, flip the condition.
3513   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3514       !ISD::isNON_EXTLoad(RHS.getNode())) {
3515     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3516     std::swap(LHS, RHS);
3517   }
3518
3519   switch (SetCCOpcode) {
3520   default: break;
3521   case ISD::SETOLT:
3522   case ISD::SETOLE:
3523   case ISD::SETUGT:
3524   case ISD::SETUGE:
3525     std::swap(LHS, RHS);
3526     break;
3527   }
3528
3529   // On a floating point condition, the flags are set as follows:
3530   // ZF  PF  CF   op
3531   //  0 | 0 | 0 | X > Y
3532   //  0 | 0 | 1 | X < Y
3533   //  1 | 0 | 0 | X == Y
3534   //  1 | 1 | 1 | unordered
3535   switch (SetCCOpcode) {
3536   default: llvm_unreachable("Condcode should be pre-legalized away");
3537   case ISD::SETUEQ:
3538   case ISD::SETEQ:   return X86::COND_E;
3539   case ISD::SETOLT:              // flipped
3540   case ISD::SETOGT:
3541   case ISD::SETGT:   return X86::COND_A;
3542   case ISD::SETOLE:              // flipped
3543   case ISD::SETOGE:
3544   case ISD::SETGE:   return X86::COND_AE;
3545   case ISD::SETUGT:              // flipped
3546   case ISD::SETULT:
3547   case ISD::SETLT:   return X86::COND_B;
3548   case ISD::SETUGE:              // flipped
3549   case ISD::SETULE:
3550   case ISD::SETLE:   return X86::COND_BE;
3551   case ISD::SETONE:
3552   case ISD::SETNE:   return X86::COND_NE;
3553   case ISD::SETUO:   return X86::COND_P;
3554   case ISD::SETO:    return X86::COND_NP;
3555   case ISD::SETOEQ:
3556   case ISD::SETUNE:  return X86::COND_INVALID;
3557   }
3558 }
3559
3560 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3561 /// code. Current x86 isa includes the following FP cmov instructions:
3562 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3563 static bool hasFPCMov(unsigned X86CC) {
3564   switch (X86CC) {
3565   default:
3566     return false;
3567   case X86::COND_B:
3568   case X86::COND_BE:
3569   case X86::COND_E:
3570   case X86::COND_P:
3571   case X86::COND_A:
3572   case X86::COND_AE:
3573   case X86::COND_NE:
3574   case X86::COND_NP:
3575     return true;
3576   }
3577 }
3578
3579 /// isFPImmLegal - Returns true if the target can instruction select the
3580 /// specified FP immediate natively. If false, the legalizer will
3581 /// materialize the FP immediate as a load from a constant pool.
3582 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3583   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3584     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3585       return true;
3586   }
3587   return false;
3588 }
3589
3590 /// \brief Returns true if it is beneficial to convert a load of a constant
3591 /// to just the constant itself.
3592 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3593                                                           Type *Ty) const {
3594   assert(Ty->isIntegerTy());
3595
3596   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3597   if (BitSize == 0 || BitSize > 64)
3598     return false;
3599   return true;
3600 }
3601
3602 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3603 /// the specified range (L, H].
3604 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3605   return (Val < 0) || (Val >= Low && Val < Hi);
3606 }
3607
3608 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3609 /// specified value.
3610 static bool isUndefOrEqual(int Val, int CmpVal) {
3611   return (Val < 0 || Val == CmpVal);
3612 }
3613
3614 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3615 /// from position Pos and ending in Pos+Size, falls within the specified
3616 /// sequential range (L, L+Pos]. or is undef.
3617 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3618                                        unsigned Pos, unsigned Size, int Low) {
3619   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3620     if (!isUndefOrEqual(Mask[i], Low))
3621       return false;
3622   return true;
3623 }
3624
3625 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3626 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3627 /// the second operand.
3628 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3629   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3630     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3631   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3632     return (Mask[0] < 2 && Mask[1] < 2);
3633   return false;
3634 }
3635
3636 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3637 /// is suitable for input to PSHUFHW.
3638 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3639   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3640     return false;
3641
3642   // Lower quadword copied in order or undef.
3643   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3644     return false;
3645
3646   // Upper quadword shuffled.
3647   for (unsigned i = 4; i != 8; ++i)
3648     if (!isUndefOrInRange(Mask[i], 4, 8))
3649       return false;
3650
3651   if (VT == MVT::v16i16) {
3652     // Lower quadword copied in order or undef.
3653     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3654       return false;
3655
3656     // Upper quadword shuffled.
3657     for (unsigned i = 12; i != 16; ++i)
3658       if (!isUndefOrInRange(Mask[i], 12, 16))
3659         return false;
3660   }
3661
3662   return true;
3663 }
3664
3665 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3666 /// is suitable for input to PSHUFLW.
3667 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3668   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3669     return false;
3670
3671   // Upper quadword copied in order.
3672   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3673     return false;
3674
3675   // Lower quadword shuffled.
3676   for (unsigned i = 0; i != 4; ++i)
3677     if (!isUndefOrInRange(Mask[i], 0, 4))
3678       return false;
3679
3680   if (VT == MVT::v16i16) {
3681     // Upper quadword copied in order.
3682     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3683       return false;
3684
3685     // Lower quadword shuffled.
3686     for (unsigned i = 8; i != 12; ++i)
3687       if (!isUndefOrInRange(Mask[i], 8, 12))
3688         return false;
3689   }
3690
3691   return true;
3692 }
3693
3694 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3695 /// is suitable for input to PALIGNR.
3696 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3697                           const X86Subtarget *Subtarget) {
3698   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3699       (VT.is256BitVector() && !Subtarget->hasInt256()))
3700     return false;
3701
3702   unsigned NumElts = VT.getVectorNumElements();
3703   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3704   unsigned NumLaneElts = NumElts/NumLanes;
3705
3706   // Do not handle 64-bit element shuffles with palignr.
3707   if (NumLaneElts == 2)
3708     return false;
3709
3710   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3711     unsigned i;
3712     for (i = 0; i != NumLaneElts; ++i) {
3713       if (Mask[i+l] >= 0)
3714         break;
3715     }
3716
3717     // Lane is all undef, go to next lane
3718     if (i == NumLaneElts)
3719       continue;
3720
3721     int Start = Mask[i+l];
3722
3723     // Make sure its in this lane in one of the sources
3724     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3725         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3726       return false;
3727
3728     // If not lane 0, then we must match lane 0
3729     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3730       return false;
3731
3732     // Correct second source to be contiguous with first source
3733     if (Start >= (int)NumElts)
3734       Start -= NumElts - NumLaneElts;
3735
3736     // Make sure we're shifting in the right direction.
3737     if (Start <= (int)(i+l))
3738       return false;
3739
3740     Start -= i;
3741
3742     // Check the rest of the elements to see if they are consecutive.
3743     for (++i; i != NumLaneElts; ++i) {
3744       int Idx = Mask[i+l];
3745
3746       // Make sure its in this lane
3747       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3748           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3749         return false;
3750
3751       // If not lane 0, then we must match lane 0
3752       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3753         return false;
3754
3755       if (Idx >= (int)NumElts)
3756         Idx -= NumElts - NumLaneElts;
3757
3758       if (!isUndefOrEqual(Idx, Start+i))
3759         return false;
3760
3761     }
3762   }
3763
3764   return true;
3765 }
3766
3767 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3768 /// the two vector operands have swapped position.
3769 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3770                                      unsigned NumElems) {
3771   for (unsigned i = 0; i != NumElems; ++i) {
3772     int idx = Mask[i];
3773     if (idx < 0)
3774       continue;
3775     else if (idx < (int)NumElems)
3776       Mask[i] = idx + NumElems;
3777     else
3778       Mask[i] = idx - NumElems;
3779   }
3780 }
3781
3782 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3783 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3784 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3785 /// reverse of what x86 shuffles want.
3786 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3787
3788   unsigned NumElems = VT.getVectorNumElements();
3789   unsigned NumLanes = VT.getSizeInBits()/128;
3790   unsigned NumLaneElems = NumElems/NumLanes;
3791
3792   if (NumLaneElems != 2 && NumLaneElems != 4)
3793     return false;
3794
3795   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3796   bool symetricMaskRequired =
3797     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3798
3799   // VSHUFPSY divides the resulting vector into 4 chunks.
3800   // The sources are also splitted into 4 chunks, and each destination
3801   // chunk must come from a different source chunk.
3802   //
3803   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3804   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3805   //
3806   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3807   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3808   //
3809   // VSHUFPDY divides the resulting vector into 4 chunks.
3810   // The sources are also splitted into 4 chunks, and each destination
3811   // chunk must come from a different source chunk.
3812   //
3813   //  SRC1 =>      X3       X2       X1       X0
3814   //  SRC2 =>      Y3       Y2       Y1       Y0
3815   //
3816   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3817   //
3818   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3819   unsigned HalfLaneElems = NumLaneElems/2;
3820   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3821     for (unsigned i = 0; i != NumLaneElems; ++i) {
3822       int Idx = Mask[i+l];
3823       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3824       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3825         return false;
3826       // For VSHUFPSY, the mask of the second half must be the same as the
3827       // first but with the appropriate offsets. This works in the same way as
3828       // VPERMILPS works with masks.
3829       if (!symetricMaskRequired || Idx < 0)
3830         continue;
3831       if (MaskVal[i] < 0) {
3832         MaskVal[i] = Idx - l;
3833         continue;
3834       }
3835       if ((signed)(Idx - l) != MaskVal[i])
3836         return false;
3837     }
3838   }
3839
3840   return true;
3841 }
3842
3843 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3844 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3845 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3846   if (!VT.is128BitVector())
3847     return false;
3848
3849   unsigned NumElems = VT.getVectorNumElements();
3850
3851   if (NumElems != 4)
3852     return false;
3853
3854   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3855   return isUndefOrEqual(Mask[0], 6) &&
3856          isUndefOrEqual(Mask[1], 7) &&
3857          isUndefOrEqual(Mask[2], 2) &&
3858          isUndefOrEqual(Mask[3], 3);
3859 }
3860
3861 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3862 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3863 /// <2, 3, 2, 3>
3864 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3865   if (!VT.is128BitVector())
3866     return false;
3867
3868   unsigned NumElems = VT.getVectorNumElements();
3869
3870   if (NumElems != 4)
3871     return false;
3872
3873   return isUndefOrEqual(Mask[0], 2) &&
3874          isUndefOrEqual(Mask[1], 3) &&
3875          isUndefOrEqual(Mask[2], 2) &&
3876          isUndefOrEqual(Mask[3], 3);
3877 }
3878
3879 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3880 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3881 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3882   if (!VT.is128BitVector())
3883     return false;
3884
3885   unsigned NumElems = VT.getVectorNumElements();
3886
3887   if (NumElems != 2 && NumElems != 4)
3888     return false;
3889
3890   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3891     if (!isUndefOrEqual(Mask[i], i + NumElems))
3892       return false;
3893
3894   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3895     if (!isUndefOrEqual(Mask[i], i))
3896       return false;
3897
3898   return true;
3899 }
3900
3901 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3902 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3903 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3904   if (!VT.is128BitVector())
3905     return false;
3906
3907   unsigned NumElems = VT.getVectorNumElements();
3908
3909   if (NumElems != 2 && NumElems != 4)
3910     return false;
3911
3912   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3913     if (!isUndefOrEqual(Mask[i], i))
3914       return false;
3915
3916   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3917     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3918       return false;
3919
3920   return true;
3921 }
3922
3923 //
3924 // Some special combinations that can be optimized.
3925 //
3926 static
3927 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3928                                SelectionDAG &DAG) {
3929   MVT VT = SVOp->getSimpleValueType(0);
3930   SDLoc dl(SVOp);
3931
3932   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3933     return SDValue();
3934
3935   ArrayRef<int> Mask = SVOp->getMask();
3936
3937   // These are the special masks that may be optimized.
3938   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3939   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3940   bool MatchEvenMask = true;
3941   bool MatchOddMask  = true;
3942   for (int i=0; i<8; ++i) {
3943     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3944       MatchEvenMask = false;
3945     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3946       MatchOddMask = false;
3947   }
3948
3949   if (!MatchEvenMask && !MatchOddMask)
3950     return SDValue();
3951
3952   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3953
3954   SDValue Op0 = SVOp->getOperand(0);
3955   SDValue Op1 = SVOp->getOperand(1);
3956
3957   if (MatchEvenMask) {
3958     // Shift the second operand right to 32 bits.
3959     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3960     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3961   } else {
3962     // Shift the first operand left to 32 bits.
3963     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3964     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3965   }
3966   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3967   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3968 }
3969
3970 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3971 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3972 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3973                          bool HasInt256, bool V2IsSplat = false) {
3974
3975   assert(VT.getSizeInBits() >= 128 &&
3976          "Unsupported vector type for unpckl");
3977
3978   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3979   unsigned NumLanes;
3980   unsigned NumOf256BitLanes;
3981   unsigned NumElts = VT.getVectorNumElements();
3982   if (VT.is256BitVector()) {
3983     if (NumElts != 4 && NumElts != 8 &&
3984         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3985     return false;
3986     NumLanes = 2;
3987     NumOf256BitLanes = 1;
3988   } else if (VT.is512BitVector()) {
3989     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3990            "Unsupported vector type for unpckh");
3991     NumLanes = 2;
3992     NumOf256BitLanes = 2;
3993   } else {
3994     NumLanes = 1;
3995     NumOf256BitLanes = 1;
3996   }
3997
3998   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
3999   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4000
4001   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4002     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4003       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4004         int BitI  = Mask[l256*NumEltsInStride+l+i];
4005         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4006         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4007           return false;
4008         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4009           return false;
4010         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4011           return false;
4012       }
4013     }
4014   }
4015   return true;
4016 }
4017
4018 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4019 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4020 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4021                          bool HasInt256, bool V2IsSplat = false) {
4022   assert(VT.getSizeInBits() >= 128 &&
4023          "Unsupported vector type for unpckh");
4024
4025   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4026   unsigned NumLanes;
4027   unsigned NumOf256BitLanes;
4028   unsigned NumElts = VT.getVectorNumElements();
4029   if (VT.is256BitVector()) {
4030     if (NumElts != 4 && NumElts != 8 &&
4031         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4032     return false;
4033     NumLanes = 2;
4034     NumOf256BitLanes = 1;
4035   } else if (VT.is512BitVector()) {
4036     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4037            "Unsupported vector type for unpckh");
4038     NumLanes = 2;
4039     NumOf256BitLanes = 2;
4040   } else {
4041     NumLanes = 1;
4042     NumOf256BitLanes = 1;
4043   }
4044
4045   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4046   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4047
4048   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4049     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4050       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4051         int BitI  = Mask[l256*NumEltsInStride+l+i];
4052         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4053         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4054           return false;
4055         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4056           return false;
4057         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4058           return false;
4059       }
4060     }
4061   }
4062   return true;
4063 }
4064
4065 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4066 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4067 /// <0, 0, 1, 1>
4068 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4069   unsigned NumElts = VT.getVectorNumElements();
4070   bool Is256BitVec = VT.is256BitVector();
4071
4072   if (VT.is512BitVector())
4073     return false;
4074   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4075          "Unsupported vector type for unpckh");
4076
4077   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4078       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4079     return false;
4080
4081   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4082   // FIXME: Need a better way to get rid of this, there's no latency difference
4083   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4084   // the former later. We should also remove the "_undef" special mask.
4085   if (NumElts == 4 && Is256BitVec)
4086     return false;
4087
4088   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4089   // independently on 128-bit lanes.
4090   unsigned NumLanes = VT.getSizeInBits()/128;
4091   unsigned NumLaneElts = NumElts/NumLanes;
4092
4093   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4094     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4095       int BitI  = Mask[l+i];
4096       int BitI1 = Mask[l+i+1];
4097
4098       if (!isUndefOrEqual(BitI, j))
4099         return false;
4100       if (!isUndefOrEqual(BitI1, j))
4101         return false;
4102     }
4103   }
4104
4105   return true;
4106 }
4107
4108 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4109 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4110 /// <2, 2, 3, 3>
4111 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4112   unsigned NumElts = VT.getVectorNumElements();
4113
4114   if (VT.is512BitVector())
4115     return false;
4116
4117   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4118          "Unsupported vector type for unpckh");
4119
4120   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4121       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4122     return false;
4123
4124   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4125   // independently on 128-bit lanes.
4126   unsigned NumLanes = VT.getSizeInBits()/128;
4127   unsigned NumLaneElts = NumElts/NumLanes;
4128
4129   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4130     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4131       int BitI  = Mask[l+i];
4132       int BitI1 = Mask[l+i+1];
4133       if (!isUndefOrEqual(BitI, j))
4134         return false;
4135       if (!isUndefOrEqual(BitI1, j))
4136         return false;
4137     }
4138   }
4139   return true;
4140 }
4141
4142 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4143 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4144 /// MOVSD, and MOVD, i.e. setting the lowest element.
4145 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4146   if (VT.getVectorElementType().getSizeInBits() < 32)
4147     return false;
4148   if (!VT.is128BitVector())
4149     return false;
4150
4151   unsigned NumElts = VT.getVectorNumElements();
4152
4153   if (!isUndefOrEqual(Mask[0], NumElts))
4154     return false;
4155
4156   for (unsigned i = 1; i != NumElts; ++i)
4157     if (!isUndefOrEqual(Mask[i], i))
4158       return false;
4159
4160   return true;
4161 }
4162
4163 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4164 /// as permutations between 128-bit chunks or halves. As an example: this
4165 /// shuffle bellow:
4166 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4167 /// The first half comes from the second half of V1 and the second half from the
4168 /// the second half of V2.
4169 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4170   if (!HasFp256 || !VT.is256BitVector())
4171     return false;
4172
4173   // The shuffle result is divided into half A and half B. In total the two
4174   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4175   // B must come from C, D, E or F.
4176   unsigned HalfSize = VT.getVectorNumElements()/2;
4177   bool MatchA = false, MatchB = false;
4178
4179   // Check if A comes from one of C, D, E, F.
4180   for (unsigned Half = 0; Half != 4; ++Half) {
4181     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4182       MatchA = true;
4183       break;
4184     }
4185   }
4186
4187   // Check if B comes from one of C, D, E, F.
4188   for (unsigned Half = 0; Half != 4; ++Half) {
4189     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4190       MatchB = true;
4191       break;
4192     }
4193   }
4194
4195   return MatchA && MatchB;
4196 }
4197
4198 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4199 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4200 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4201   MVT VT = SVOp->getSimpleValueType(0);
4202
4203   unsigned HalfSize = VT.getVectorNumElements()/2;
4204
4205   unsigned FstHalf = 0, SndHalf = 0;
4206   for (unsigned i = 0; i < HalfSize; ++i) {
4207     if (SVOp->getMaskElt(i) > 0) {
4208       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4209       break;
4210     }
4211   }
4212   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4213     if (SVOp->getMaskElt(i) > 0) {
4214       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4215       break;
4216     }
4217   }
4218
4219   return (FstHalf | (SndHalf << 4));
4220 }
4221
4222 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4223 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4224   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4225   if (EltSize < 32)
4226     return false;
4227
4228   unsigned NumElts = VT.getVectorNumElements();
4229   Imm8 = 0;
4230   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4231     for (unsigned i = 0; i != NumElts; ++i) {
4232       if (Mask[i] < 0)
4233         continue;
4234       Imm8 |= Mask[i] << (i*2);
4235     }
4236     return true;
4237   }
4238
4239   unsigned LaneSize = 4;
4240   SmallVector<int, 4> MaskVal(LaneSize, -1);
4241
4242   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4243     for (unsigned i = 0; i != LaneSize; ++i) {
4244       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4245         return false;
4246       if (Mask[i+l] < 0)
4247         continue;
4248       if (MaskVal[i] < 0) {
4249         MaskVal[i] = Mask[i+l] - l;
4250         Imm8 |= MaskVal[i] << (i*2);
4251         continue;
4252       }
4253       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4254         return false;
4255     }
4256   }
4257   return true;
4258 }
4259
4260 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4261 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4262 /// Note that VPERMIL mask matching is different depending whether theunderlying
4263 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4264 /// to the same elements of the low, but to the higher half of the source.
4265 /// In VPERMILPD the two lanes could be shuffled independently of each other
4266 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4267 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4268   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4269   if (VT.getSizeInBits() < 256 || EltSize < 32)
4270     return false;
4271   bool symetricMaskRequired = (EltSize == 32);
4272   unsigned NumElts = VT.getVectorNumElements();
4273
4274   unsigned NumLanes = VT.getSizeInBits()/128;
4275   unsigned LaneSize = NumElts/NumLanes;
4276   // 2 or 4 elements in one lane
4277
4278   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4279   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4280     for (unsigned i = 0; i != LaneSize; ++i) {
4281       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4282         return false;
4283       if (symetricMaskRequired) {
4284         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4285           ExpectedMaskVal[i] = Mask[i+l] - l;
4286           continue;
4287         }
4288         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4289           return false;
4290       }
4291     }
4292   }
4293   return true;
4294 }
4295
4296 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4297 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4298 /// element of vector 2 and the other elements to come from vector 1 in order.
4299 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4300                                bool V2IsSplat = false, bool V2IsUndef = false) {
4301   if (!VT.is128BitVector())
4302     return false;
4303
4304   unsigned NumOps = VT.getVectorNumElements();
4305   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4306     return false;
4307
4308   if (!isUndefOrEqual(Mask[0], 0))
4309     return false;
4310
4311   for (unsigned i = 1; i != NumOps; ++i)
4312     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4313           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4314           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4315       return false;
4316
4317   return true;
4318 }
4319
4320 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4321 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4322 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4323 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4324                            const X86Subtarget *Subtarget) {
4325   if (!Subtarget->hasSSE3())
4326     return false;
4327
4328   unsigned NumElems = VT.getVectorNumElements();
4329
4330   if ((VT.is128BitVector() && NumElems != 4) ||
4331       (VT.is256BitVector() && NumElems != 8) ||
4332       (VT.is512BitVector() && NumElems != 16))
4333     return false;
4334
4335   // "i+1" is the value the indexed mask element must have
4336   for (unsigned i = 0; i != NumElems; i += 2)
4337     if (!isUndefOrEqual(Mask[i], i+1) ||
4338         !isUndefOrEqual(Mask[i+1], i+1))
4339       return false;
4340
4341   return true;
4342 }
4343
4344 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4345 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4346 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4347 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4348                            const X86Subtarget *Subtarget) {
4349   if (!Subtarget->hasSSE3())
4350     return false;
4351
4352   unsigned NumElems = VT.getVectorNumElements();
4353
4354   if ((VT.is128BitVector() && NumElems != 4) ||
4355       (VT.is256BitVector() && NumElems != 8) ||
4356       (VT.is512BitVector() && NumElems != 16))
4357     return false;
4358
4359   // "i" is the value the indexed mask element must have
4360   for (unsigned i = 0; i != NumElems; i += 2)
4361     if (!isUndefOrEqual(Mask[i], i) ||
4362         !isUndefOrEqual(Mask[i+1], i))
4363       return false;
4364
4365   return true;
4366 }
4367
4368 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4369 /// specifies a shuffle of elements that is suitable for input to 256-bit
4370 /// version of MOVDDUP.
4371 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4372   if (!HasFp256 || !VT.is256BitVector())
4373     return false;
4374
4375   unsigned NumElts = VT.getVectorNumElements();
4376   if (NumElts != 4)
4377     return false;
4378
4379   for (unsigned i = 0; i != NumElts/2; ++i)
4380     if (!isUndefOrEqual(Mask[i], 0))
4381       return false;
4382   for (unsigned i = NumElts/2; i != NumElts; ++i)
4383     if (!isUndefOrEqual(Mask[i], NumElts/2))
4384       return false;
4385   return true;
4386 }
4387
4388 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4389 /// specifies a shuffle of elements that is suitable for input to 128-bit
4390 /// version of MOVDDUP.
4391 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4392   if (!VT.is128BitVector())
4393     return false;
4394
4395   unsigned e = VT.getVectorNumElements() / 2;
4396   for (unsigned i = 0; i != e; ++i)
4397     if (!isUndefOrEqual(Mask[i], i))
4398       return false;
4399   for (unsigned i = 0; i != e; ++i)
4400     if (!isUndefOrEqual(Mask[e+i], i))
4401       return false;
4402   return true;
4403 }
4404
4405 /// isVEXTRACTIndex - Return true if the specified
4406 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4407 /// suitable for instruction that extract 128 or 256 bit vectors
4408 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4409   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4410   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4411     return false;
4412
4413   // The index should be aligned on a vecWidth-bit boundary.
4414   uint64_t Index =
4415     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4416
4417   MVT VT = N->getSimpleValueType(0);
4418   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4419   bool Result = (Index * ElSize) % vecWidth == 0;
4420
4421   return Result;
4422 }
4423
4424 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4425 /// operand specifies a subvector insert that is suitable for input to
4426 /// insertion of 128 or 256-bit subvectors
4427 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4428   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4429   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4430     return false;
4431   // The index should be aligned on a vecWidth-bit boundary.
4432   uint64_t Index =
4433     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4434
4435   MVT VT = N->getSimpleValueType(0);
4436   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4437   bool Result = (Index * ElSize) % vecWidth == 0;
4438
4439   return Result;
4440 }
4441
4442 bool X86::isVINSERT128Index(SDNode *N) {
4443   return isVINSERTIndex(N, 128);
4444 }
4445
4446 bool X86::isVINSERT256Index(SDNode *N) {
4447   return isVINSERTIndex(N, 256);
4448 }
4449
4450 bool X86::isVEXTRACT128Index(SDNode *N) {
4451   return isVEXTRACTIndex(N, 128);
4452 }
4453
4454 bool X86::isVEXTRACT256Index(SDNode *N) {
4455   return isVEXTRACTIndex(N, 256);
4456 }
4457
4458 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4459 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4460 /// Handles 128-bit and 256-bit.
4461 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4462   MVT VT = N->getSimpleValueType(0);
4463
4464   assert((VT.getSizeInBits() >= 128) &&
4465          "Unsupported vector type for PSHUF/SHUFP");
4466
4467   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4468   // independently on 128-bit lanes.
4469   unsigned NumElts = VT.getVectorNumElements();
4470   unsigned NumLanes = VT.getSizeInBits()/128;
4471   unsigned NumLaneElts = NumElts/NumLanes;
4472
4473   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4474          "Only supports 2, 4 or 8 elements per lane");
4475
4476   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4477   unsigned Mask = 0;
4478   for (unsigned i = 0; i != NumElts; ++i) {
4479     int Elt = N->getMaskElt(i);
4480     if (Elt < 0) continue;
4481     Elt &= NumLaneElts - 1;
4482     unsigned ShAmt = (i << Shift) % 8;
4483     Mask |= Elt << ShAmt;
4484   }
4485
4486   return Mask;
4487 }
4488
4489 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4490 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4491 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4492   MVT VT = N->getSimpleValueType(0);
4493
4494   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4495          "Unsupported vector type for PSHUFHW");
4496
4497   unsigned NumElts = VT.getVectorNumElements();
4498
4499   unsigned Mask = 0;
4500   for (unsigned l = 0; l != NumElts; l += 8) {
4501     // 8 nodes per lane, but we only care about the last 4.
4502     for (unsigned i = 0; i < 4; ++i) {
4503       int Elt = N->getMaskElt(l+i+4);
4504       if (Elt < 0) continue;
4505       Elt &= 0x3; // only 2-bits.
4506       Mask |= Elt << (i * 2);
4507     }
4508   }
4509
4510   return Mask;
4511 }
4512
4513 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4514 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4515 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4516   MVT VT = N->getSimpleValueType(0);
4517
4518   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4519          "Unsupported vector type for PSHUFHW");
4520
4521   unsigned NumElts = VT.getVectorNumElements();
4522
4523   unsigned Mask = 0;
4524   for (unsigned l = 0; l != NumElts; l += 8) {
4525     // 8 nodes per lane, but we only care about the first 4.
4526     for (unsigned i = 0; i < 4; ++i) {
4527       int Elt = N->getMaskElt(l+i);
4528       if (Elt < 0) continue;
4529       Elt &= 0x3; // only 2-bits
4530       Mask |= Elt << (i * 2);
4531     }
4532   }
4533
4534   return Mask;
4535 }
4536
4537 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4538 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4539 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4540   MVT VT = SVOp->getSimpleValueType(0);
4541   unsigned EltSize = VT.is512BitVector() ? 1 :
4542     VT.getVectorElementType().getSizeInBits() >> 3;
4543
4544   unsigned NumElts = VT.getVectorNumElements();
4545   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4546   unsigned NumLaneElts = NumElts/NumLanes;
4547
4548   int Val = 0;
4549   unsigned i;
4550   for (i = 0; i != NumElts; ++i) {
4551     Val = SVOp->getMaskElt(i);
4552     if (Val >= 0)
4553       break;
4554   }
4555   if (Val >= (int)NumElts)
4556     Val -= NumElts - NumLaneElts;
4557
4558   assert(Val - i > 0 && "PALIGNR imm should be positive");
4559   return (Val - i) * EltSize;
4560 }
4561
4562 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4563   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4564   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4565     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4566
4567   uint64_t Index =
4568     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4569
4570   MVT VecVT = N->getOperand(0).getSimpleValueType();
4571   MVT ElVT = VecVT.getVectorElementType();
4572
4573   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4574   return Index / NumElemsPerChunk;
4575 }
4576
4577 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4578   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4579   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4580     llvm_unreachable("Illegal insert subvector for VINSERT");
4581
4582   uint64_t Index =
4583     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4584
4585   MVT VecVT = N->getSimpleValueType(0);
4586   MVT ElVT = VecVT.getVectorElementType();
4587
4588   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4589   return Index / NumElemsPerChunk;
4590 }
4591
4592 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4593 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4594 /// and VINSERTI128 instructions.
4595 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4596   return getExtractVEXTRACTImmediate(N, 128);
4597 }
4598
4599 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4600 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4601 /// and VINSERTI64x4 instructions.
4602 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4603   return getExtractVEXTRACTImmediate(N, 256);
4604 }
4605
4606 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4607 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4608 /// and VINSERTI128 instructions.
4609 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4610   return getInsertVINSERTImmediate(N, 128);
4611 }
4612
4613 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4614 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4615 /// and VINSERTI64x4 instructions.
4616 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4617   return getInsertVINSERTImmediate(N, 256);
4618 }
4619
4620 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4621 /// constant +0.0.
4622 bool X86::isZeroNode(SDValue Elt) {
4623   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4624     return CN->isNullValue();
4625   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4626     return CFP->getValueAPF().isPosZero();
4627   return false;
4628 }
4629
4630 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4631 /// their permute mask.
4632 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4633                                     SelectionDAG &DAG) {
4634   MVT VT = SVOp->getSimpleValueType(0);
4635   unsigned NumElems = VT.getVectorNumElements();
4636   SmallVector<int, 8> MaskVec;
4637
4638   for (unsigned i = 0; i != NumElems; ++i) {
4639     int Idx = SVOp->getMaskElt(i);
4640     if (Idx >= 0) {
4641       if (Idx < (int)NumElems)
4642         Idx += NumElems;
4643       else
4644         Idx -= NumElems;
4645     }
4646     MaskVec.push_back(Idx);
4647   }
4648   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4649                               SVOp->getOperand(0), &MaskVec[0]);
4650 }
4651
4652 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4653 /// match movhlps. The lower half elements should come from upper half of
4654 /// V1 (and in order), and the upper half elements should come from the upper
4655 /// half of V2 (and in order).
4656 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4657   if (!VT.is128BitVector())
4658     return false;
4659   if (VT.getVectorNumElements() != 4)
4660     return false;
4661   for (unsigned i = 0, e = 2; i != e; ++i)
4662     if (!isUndefOrEqual(Mask[i], i+2))
4663       return false;
4664   for (unsigned i = 2; i != 4; ++i)
4665     if (!isUndefOrEqual(Mask[i], i+4))
4666       return false;
4667   return true;
4668 }
4669
4670 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4671 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4672 /// required.
4673 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4674   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4675     return false;
4676   N = N->getOperand(0).getNode();
4677   if (!ISD::isNON_EXTLoad(N))
4678     return false;
4679   if (LD)
4680     *LD = cast<LoadSDNode>(N);
4681   return true;
4682 }
4683
4684 // Test whether the given value is a vector value which will be legalized
4685 // into a load.
4686 static bool WillBeConstantPoolLoad(SDNode *N) {
4687   if (N->getOpcode() != ISD::BUILD_VECTOR)
4688     return false;
4689
4690   // Check for any non-constant elements.
4691   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4692     switch (N->getOperand(i).getNode()->getOpcode()) {
4693     case ISD::UNDEF:
4694     case ISD::ConstantFP:
4695     case ISD::Constant:
4696       break;
4697     default:
4698       return false;
4699     }
4700
4701   // Vectors of all-zeros and all-ones are materialized with special
4702   // instructions rather than being loaded.
4703   return !ISD::isBuildVectorAllZeros(N) &&
4704          !ISD::isBuildVectorAllOnes(N);
4705 }
4706
4707 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4708 /// match movlp{s|d}. The lower half elements should come from lower half of
4709 /// V1 (and in order), and the upper half elements should come from the upper
4710 /// half of V2 (and in order). And since V1 will become the source of the
4711 /// MOVLP, it must be either a vector load or a scalar load to vector.
4712 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4713                                ArrayRef<int> Mask, MVT VT) {
4714   if (!VT.is128BitVector())
4715     return false;
4716
4717   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4718     return false;
4719   // Is V2 is a vector load, don't do this transformation. We will try to use
4720   // load folding shufps op.
4721   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4722     return false;
4723
4724   unsigned NumElems = VT.getVectorNumElements();
4725
4726   if (NumElems != 2 && NumElems != 4)
4727     return false;
4728   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4729     if (!isUndefOrEqual(Mask[i], i))
4730       return false;
4731   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4732     if (!isUndefOrEqual(Mask[i], i+NumElems))
4733       return false;
4734   return true;
4735 }
4736
4737 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4738 /// all the same.
4739 static bool isSplatVector(SDNode *N) {
4740   if (N->getOpcode() != ISD::BUILD_VECTOR)
4741     return false;
4742
4743   SDValue SplatValue = N->getOperand(0);
4744   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4745     if (N->getOperand(i) != SplatValue)
4746       return false;
4747   return true;
4748 }
4749
4750 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4751 /// to an zero vector.
4752 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4753 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4754   SDValue V1 = N->getOperand(0);
4755   SDValue V2 = N->getOperand(1);
4756   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4757   for (unsigned i = 0; i != NumElems; ++i) {
4758     int Idx = N->getMaskElt(i);
4759     if (Idx >= (int)NumElems) {
4760       unsigned Opc = V2.getOpcode();
4761       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4762         continue;
4763       if (Opc != ISD::BUILD_VECTOR ||
4764           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4765         return false;
4766     } else if (Idx >= 0) {
4767       unsigned Opc = V1.getOpcode();
4768       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4769         continue;
4770       if (Opc != ISD::BUILD_VECTOR ||
4771           !X86::isZeroNode(V1.getOperand(Idx)))
4772         return false;
4773     }
4774   }
4775   return true;
4776 }
4777
4778 /// getZeroVector - Returns a vector of specified type with all zero elements.
4779 ///
4780 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4781                              SelectionDAG &DAG, SDLoc dl) {
4782   assert(VT.isVector() && "Expected a vector type");
4783
4784   // Always build SSE zero vectors as <4 x i32> bitcasted
4785   // to their dest type. This ensures they get CSE'd.
4786   SDValue Vec;
4787   if (VT.is128BitVector()) {  // SSE
4788     if (Subtarget->hasSSE2()) {  // SSE2
4789       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4790       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4791     } else { // SSE1
4792       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4793       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4794     }
4795   } else if (VT.is256BitVector()) { // AVX
4796     if (Subtarget->hasInt256()) { // AVX2
4797       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4798       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4799       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4800                         array_lengthof(Ops));
4801     } else {
4802       // 256-bit logic and arithmetic instructions in AVX are all
4803       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4804       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4805       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4806       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4807                         array_lengthof(Ops));
4808     }
4809   } else if (VT.is512BitVector()) { // AVX-512
4810       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4811       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4812                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4813       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4814   } else if (VT.getScalarType() == MVT::i1) {
4815     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4816     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4817     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4818                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4819     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4820                        Ops, VT.getVectorNumElements());
4821   } else
4822     llvm_unreachable("Unexpected vector type");
4823
4824   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4825 }
4826
4827 /// getOnesVector - Returns a vector of specified type with all bits set.
4828 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4829 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4830 /// Then bitcast to their original type, ensuring they get CSE'd.
4831 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4832                              SDLoc dl) {
4833   assert(VT.isVector() && "Expected a vector type");
4834
4835   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4836   SDValue Vec;
4837   if (VT.is256BitVector()) {
4838     if (HasInt256) { // AVX2
4839       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4840       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4841                         array_lengthof(Ops));
4842     } else { // AVX
4843       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4844       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4845     }
4846   } else if (VT.is128BitVector()) {
4847     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4848   } else
4849     llvm_unreachable("Unexpected vector type");
4850
4851   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4852 }
4853
4854 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4855 /// that point to V2 points to its first element.
4856 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4857   for (unsigned i = 0; i != NumElems; ++i) {
4858     if (Mask[i] > (int)NumElems) {
4859       Mask[i] = NumElems;
4860     }
4861   }
4862 }
4863
4864 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4865 /// operation of specified width.
4866 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4867                        SDValue V2) {
4868   unsigned NumElems = VT.getVectorNumElements();
4869   SmallVector<int, 8> Mask;
4870   Mask.push_back(NumElems);
4871   for (unsigned i = 1; i != NumElems; ++i)
4872     Mask.push_back(i);
4873   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4874 }
4875
4876 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4877 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4878                           SDValue V2) {
4879   unsigned NumElems = VT.getVectorNumElements();
4880   SmallVector<int, 8> Mask;
4881   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4882     Mask.push_back(i);
4883     Mask.push_back(i + NumElems);
4884   }
4885   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4886 }
4887
4888 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4889 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4890                           SDValue V2) {
4891   unsigned NumElems = VT.getVectorNumElements();
4892   SmallVector<int, 8> Mask;
4893   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4894     Mask.push_back(i + Half);
4895     Mask.push_back(i + NumElems + Half);
4896   }
4897   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4898 }
4899
4900 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4901 // a generic shuffle instruction because the target has no such instructions.
4902 // Generate shuffles which repeat i16 and i8 several times until they can be
4903 // represented by v4f32 and then be manipulated by target suported shuffles.
4904 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4905   MVT VT = V.getSimpleValueType();
4906   int NumElems = VT.getVectorNumElements();
4907   SDLoc dl(V);
4908
4909   while (NumElems > 4) {
4910     if (EltNo < NumElems/2) {
4911       V = getUnpackl(DAG, dl, VT, V, V);
4912     } else {
4913       V = getUnpackh(DAG, dl, VT, V, V);
4914       EltNo -= NumElems/2;
4915     }
4916     NumElems >>= 1;
4917   }
4918   return V;
4919 }
4920
4921 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4922 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4923   MVT VT = V.getSimpleValueType();
4924   SDLoc dl(V);
4925
4926   if (VT.is128BitVector()) {
4927     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4928     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4929     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4930                              &SplatMask[0]);
4931   } else if (VT.is256BitVector()) {
4932     // To use VPERMILPS to splat scalars, the second half of indicies must
4933     // refer to the higher part, which is a duplication of the lower one,
4934     // because VPERMILPS can only handle in-lane permutations.
4935     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4936                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4937
4938     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4939     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4940                              &SplatMask[0]);
4941   } else
4942     llvm_unreachable("Vector size not supported");
4943
4944   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4945 }
4946
4947 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4948 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4949   MVT SrcVT = SV->getSimpleValueType(0);
4950   SDValue V1 = SV->getOperand(0);
4951   SDLoc dl(SV);
4952
4953   int EltNo = SV->getSplatIndex();
4954   int NumElems = SrcVT.getVectorNumElements();
4955   bool Is256BitVec = SrcVT.is256BitVector();
4956
4957   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4958          "Unknown how to promote splat for type");
4959
4960   // Extract the 128-bit part containing the splat element and update
4961   // the splat element index when it refers to the higher register.
4962   if (Is256BitVec) {
4963     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4964     if (EltNo >= NumElems/2)
4965       EltNo -= NumElems/2;
4966   }
4967
4968   // All i16 and i8 vector types can't be used directly by a generic shuffle
4969   // instruction because the target has no such instruction. Generate shuffles
4970   // which repeat i16 and i8 several times until they fit in i32, and then can
4971   // be manipulated by target suported shuffles.
4972   MVT EltVT = SrcVT.getVectorElementType();
4973   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4974     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4975
4976   // Recreate the 256-bit vector and place the same 128-bit vector
4977   // into the low and high part. This is necessary because we want
4978   // to use VPERM* to shuffle the vectors
4979   if (Is256BitVec) {
4980     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4981   }
4982
4983   return getLegalSplat(DAG, V1, EltNo);
4984 }
4985
4986 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4987 /// vector of zero or undef vector.  This produces a shuffle where the low
4988 /// element of V2 is swizzled into the zero/undef vector, landing at element
4989 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4990 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4991                                            bool IsZero,
4992                                            const X86Subtarget *Subtarget,
4993                                            SelectionDAG &DAG) {
4994   MVT VT = V2.getSimpleValueType();
4995   SDValue V1 = IsZero
4996     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4997   unsigned NumElems = VT.getVectorNumElements();
4998   SmallVector<int, 16> MaskVec;
4999   for (unsigned i = 0; i != NumElems; ++i)
5000     // If this is the insertion idx, put the low elt of V2 here.
5001     MaskVec.push_back(i == Idx ? NumElems : i);
5002   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5003 }
5004
5005 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5006 /// target specific opcode. Returns true if the Mask could be calculated.
5007 /// Sets IsUnary to true if only uses one source.
5008 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5009                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5010   unsigned NumElems = VT.getVectorNumElements();
5011   SDValue ImmN;
5012
5013   IsUnary = false;
5014   switch(N->getOpcode()) {
5015   case X86ISD::SHUFP:
5016     ImmN = N->getOperand(N->getNumOperands()-1);
5017     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5018     break;
5019   case X86ISD::UNPCKH:
5020     DecodeUNPCKHMask(VT, Mask);
5021     break;
5022   case X86ISD::UNPCKL:
5023     DecodeUNPCKLMask(VT, Mask);
5024     break;
5025   case X86ISD::MOVHLPS:
5026     DecodeMOVHLPSMask(NumElems, Mask);
5027     break;
5028   case X86ISD::MOVLHPS:
5029     DecodeMOVLHPSMask(NumElems, Mask);
5030     break;
5031   case X86ISD::PALIGNR:
5032     ImmN = N->getOperand(N->getNumOperands()-1);
5033     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5034     break;
5035   case X86ISD::PSHUFD:
5036   case X86ISD::VPERMILP:
5037     ImmN = N->getOperand(N->getNumOperands()-1);
5038     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5039     IsUnary = true;
5040     break;
5041   case X86ISD::PSHUFHW:
5042     ImmN = N->getOperand(N->getNumOperands()-1);
5043     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5044     IsUnary = true;
5045     break;
5046   case X86ISD::PSHUFLW:
5047     ImmN = N->getOperand(N->getNumOperands()-1);
5048     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5049     IsUnary = true;
5050     break;
5051   case X86ISD::VPERMI:
5052     ImmN = N->getOperand(N->getNumOperands()-1);
5053     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5054     IsUnary = true;
5055     break;
5056   case X86ISD::MOVSS:
5057   case X86ISD::MOVSD: {
5058     // The index 0 always comes from the first element of the second source,
5059     // this is why MOVSS and MOVSD are used in the first place. The other
5060     // elements come from the other positions of the first source vector
5061     Mask.push_back(NumElems);
5062     for (unsigned i = 1; i != NumElems; ++i) {
5063       Mask.push_back(i);
5064     }
5065     break;
5066   }
5067   case X86ISD::VPERM2X128:
5068     ImmN = N->getOperand(N->getNumOperands()-1);
5069     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5070     if (Mask.empty()) return false;
5071     break;
5072   case X86ISD::MOVDDUP:
5073   case X86ISD::MOVLHPD:
5074   case X86ISD::MOVLPD:
5075   case X86ISD::MOVLPS:
5076   case X86ISD::MOVSHDUP:
5077   case X86ISD::MOVSLDUP:
5078     // Not yet implemented
5079     return false;
5080   default: llvm_unreachable("unknown target shuffle node");
5081   }
5082
5083   return true;
5084 }
5085
5086 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5087 /// element of the result of the vector shuffle.
5088 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5089                                    unsigned Depth) {
5090   if (Depth == 6)
5091     return SDValue();  // Limit search depth.
5092
5093   SDValue V = SDValue(N, 0);
5094   EVT VT = V.getValueType();
5095   unsigned Opcode = V.getOpcode();
5096
5097   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5098   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5099     int Elt = SV->getMaskElt(Index);
5100
5101     if (Elt < 0)
5102       return DAG.getUNDEF(VT.getVectorElementType());
5103
5104     unsigned NumElems = VT.getVectorNumElements();
5105     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5106                                          : SV->getOperand(1);
5107     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5108   }
5109
5110   // Recurse into target specific vector shuffles to find scalars.
5111   if (isTargetShuffle(Opcode)) {
5112     MVT ShufVT = V.getSimpleValueType();
5113     unsigned NumElems = ShufVT.getVectorNumElements();
5114     SmallVector<int, 16> ShuffleMask;
5115     bool IsUnary;
5116
5117     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5118       return SDValue();
5119
5120     int Elt = ShuffleMask[Index];
5121     if (Elt < 0)
5122       return DAG.getUNDEF(ShufVT.getVectorElementType());
5123
5124     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5125                                          : N->getOperand(1);
5126     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5127                                Depth+1);
5128   }
5129
5130   // Actual nodes that may contain scalar elements
5131   if (Opcode == ISD::BITCAST) {
5132     V = V.getOperand(0);
5133     EVT SrcVT = V.getValueType();
5134     unsigned NumElems = VT.getVectorNumElements();
5135
5136     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5137       return SDValue();
5138   }
5139
5140   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5141     return (Index == 0) ? V.getOperand(0)
5142                         : DAG.getUNDEF(VT.getVectorElementType());
5143
5144   if (V.getOpcode() == ISD::BUILD_VECTOR)
5145     return V.getOperand(Index);
5146
5147   return SDValue();
5148 }
5149
5150 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5151 /// shuffle operation which come from a consecutively from a zero. The
5152 /// search can start in two different directions, from left or right.
5153 /// We count undefs as zeros until PreferredNum is reached.
5154 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5155                                          unsigned NumElems, bool ZerosFromLeft,
5156                                          SelectionDAG &DAG,
5157                                          unsigned PreferredNum = -1U) {
5158   unsigned NumZeros = 0;
5159   for (unsigned i = 0; i != NumElems; ++i) {
5160     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5161     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5162     if (!Elt.getNode())
5163       break;
5164
5165     if (X86::isZeroNode(Elt))
5166       ++NumZeros;
5167     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5168       NumZeros = std::min(NumZeros + 1, PreferredNum);
5169     else
5170       break;
5171   }
5172
5173   return NumZeros;
5174 }
5175
5176 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5177 /// correspond consecutively to elements from one of the vector operands,
5178 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5179 static
5180 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5181                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5182                               unsigned NumElems, unsigned &OpNum) {
5183   bool SeenV1 = false;
5184   bool SeenV2 = false;
5185
5186   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5187     int Idx = SVOp->getMaskElt(i);
5188     // Ignore undef indicies
5189     if (Idx < 0)
5190       continue;
5191
5192     if (Idx < (int)NumElems)
5193       SeenV1 = true;
5194     else
5195       SeenV2 = true;
5196
5197     // Only accept consecutive elements from the same vector
5198     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5199       return false;
5200   }
5201
5202   OpNum = SeenV1 ? 0 : 1;
5203   return true;
5204 }
5205
5206 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5207 /// logical left shift of a vector.
5208 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5209                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5210   unsigned NumElems =
5211     SVOp->getSimpleValueType(0).getVectorNumElements();
5212   unsigned NumZeros = getNumOfConsecutiveZeros(
5213       SVOp, NumElems, false /* check zeros from right */, DAG,
5214       SVOp->getMaskElt(0));
5215   unsigned OpSrc;
5216
5217   if (!NumZeros)
5218     return false;
5219
5220   // Considering the elements in the mask that are not consecutive zeros,
5221   // check if they consecutively come from only one of the source vectors.
5222   //
5223   //               V1 = {X, A, B, C}     0
5224   //                         \  \  \    /
5225   //   vector_shuffle V1, V2 <1, 2, 3, X>
5226   //
5227   if (!isShuffleMaskConsecutive(SVOp,
5228             0,                   // Mask Start Index
5229             NumElems-NumZeros,   // Mask End Index(exclusive)
5230             NumZeros,            // Where to start looking in the src vector
5231             NumElems,            // Number of elements in vector
5232             OpSrc))              // Which source operand ?
5233     return false;
5234
5235   isLeft = false;
5236   ShAmt = NumZeros;
5237   ShVal = SVOp->getOperand(OpSrc);
5238   return true;
5239 }
5240
5241 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5242 /// logical left shift of a vector.
5243 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5244                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5245   unsigned NumElems =
5246     SVOp->getSimpleValueType(0).getVectorNumElements();
5247   unsigned NumZeros = getNumOfConsecutiveZeros(
5248       SVOp, NumElems, true /* check zeros from left */, DAG,
5249       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5250   unsigned OpSrc;
5251
5252   if (!NumZeros)
5253     return false;
5254
5255   // Considering the elements in the mask that are not consecutive zeros,
5256   // check if they consecutively come from only one of the source vectors.
5257   //
5258   //                           0    { A, B, X, X } = V2
5259   //                          / \    /  /
5260   //   vector_shuffle V1, V2 <X, X, 4, 5>
5261   //
5262   if (!isShuffleMaskConsecutive(SVOp,
5263             NumZeros,     // Mask Start Index
5264             NumElems,     // Mask End Index(exclusive)
5265             0,            // Where to start looking in the src vector
5266             NumElems,     // Number of elements in vector
5267             OpSrc))       // Which source operand ?
5268     return false;
5269
5270   isLeft = true;
5271   ShAmt = NumZeros;
5272   ShVal = SVOp->getOperand(OpSrc);
5273   return true;
5274 }
5275
5276 /// isVectorShift - Returns true if the shuffle can be implemented as a
5277 /// logical left or right shift of a vector.
5278 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5279                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5280   // Although the logic below support any bitwidth size, there are no
5281   // shift instructions which handle more than 128-bit vectors.
5282   if (!SVOp->getSimpleValueType(0).is128BitVector())
5283     return false;
5284
5285   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5286       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5287     return true;
5288
5289   return false;
5290 }
5291
5292 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5293 ///
5294 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5295                                        unsigned NumNonZero, unsigned NumZero,
5296                                        SelectionDAG &DAG,
5297                                        const X86Subtarget* Subtarget,
5298                                        const TargetLowering &TLI) {
5299   if (NumNonZero > 8)
5300     return SDValue();
5301
5302   SDLoc dl(Op);
5303   SDValue V(0, 0);
5304   bool First = true;
5305   for (unsigned i = 0; i < 16; ++i) {
5306     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5307     if (ThisIsNonZero && First) {
5308       if (NumZero)
5309         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5310       else
5311         V = DAG.getUNDEF(MVT::v8i16);
5312       First = false;
5313     }
5314
5315     if ((i & 1) != 0) {
5316       SDValue ThisElt(0, 0), LastElt(0, 0);
5317       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5318       if (LastIsNonZero) {
5319         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5320                               MVT::i16, Op.getOperand(i-1));
5321       }
5322       if (ThisIsNonZero) {
5323         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5324         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5325                               ThisElt, DAG.getConstant(8, MVT::i8));
5326         if (LastIsNonZero)
5327           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5328       } else
5329         ThisElt = LastElt;
5330
5331       if (ThisElt.getNode())
5332         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5333                         DAG.getIntPtrConstant(i/2));
5334     }
5335   }
5336
5337   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5338 }
5339
5340 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5341 ///
5342 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5343                                      unsigned NumNonZero, unsigned NumZero,
5344                                      SelectionDAG &DAG,
5345                                      const X86Subtarget* Subtarget,
5346                                      const TargetLowering &TLI) {
5347   if (NumNonZero > 4)
5348     return SDValue();
5349
5350   SDLoc dl(Op);
5351   SDValue V(0, 0);
5352   bool First = true;
5353   for (unsigned i = 0; i < 8; ++i) {
5354     bool isNonZero = (NonZeros & (1 << i)) != 0;
5355     if (isNonZero) {
5356       if (First) {
5357         if (NumZero)
5358           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5359         else
5360           V = DAG.getUNDEF(MVT::v8i16);
5361         First = false;
5362       }
5363       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5364                       MVT::v8i16, V, Op.getOperand(i),
5365                       DAG.getIntPtrConstant(i));
5366     }
5367   }
5368
5369   return V;
5370 }
5371
5372 /// getVShift - Return a vector logical shift node.
5373 ///
5374 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5375                          unsigned NumBits, SelectionDAG &DAG,
5376                          const TargetLowering &TLI, SDLoc dl) {
5377   assert(VT.is128BitVector() && "Unknown type for VShift");
5378   EVT ShVT = MVT::v2i64;
5379   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5380   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5381   return DAG.getNode(ISD::BITCAST, dl, VT,
5382                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5383                              DAG.getConstant(NumBits,
5384                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5385 }
5386
5387 static SDValue
5388 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5389
5390   // Check if the scalar load can be widened into a vector load. And if
5391   // the address is "base + cst" see if the cst can be "absorbed" into
5392   // the shuffle mask.
5393   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5394     SDValue Ptr = LD->getBasePtr();
5395     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5396       return SDValue();
5397     EVT PVT = LD->getValueType(0);
5398     if (PVT != MVT::i32 && PVT != MVT::f32)
5399       return SDValue();
5400
5401     int FI = -1;
5402     int64_t Offset = 0;
5403     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5404       FI = FINode->getIndex();
5405       Offset = 0;
5406     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5407                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5408       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5409       Offset = Ptr.getConstantOperandVal(1);
5410       Ptr = Ptr.getOperand(0);
5411     } else {
5412       return SDValue();
5413     }
5414
5415     // FIXME: 256-bit vector instructions don't require a strict alignment,
5416     // improve this code to support it better.
5417     unsigned RequiredAlign = VT.getSizeInBits()/8;
5418     SDValue Chain = LD->getChain();
5419     // Make sure the stack object alignment is at least 16 or 32.
5420     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5421     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5422       if (MFI->isFixedObjectIndex(FI)) {
5423         // Can't change the alignment. FIXME: It's possible to compute
5424         // the exact stack offset and reference FI + adjust offset instead.
5425         // If someone *really* cares about this. That's the way to implement it.
5426         return SDValue();
5427       } else {
5428         MFI->setObjectAlignment(FI, RequiredAlign);
5429       }
5430     }
5431
5432     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5433     // Ptr + (Offset & ~15).
5434     if (Offset < 0)
5435       return SDValue();
5436     if ((Offset % RequiredAlign) & 3)
5437       return SDValue();
5438     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5439     if (StartOffset)
5440       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5441                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5442
5443     int EltNo = (Offset - StartOffset) >> 2;
5444     unsigned NumElems = VT.getVectorNumElements();
5445
5446     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5447     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5448                              LD->getPointerInfo().getWithOffset(StartOffset),
5449                              false, false, false, 0);
5450
5451     SmallVector<int, 8> Mask;
5452     for (unsigned i = 0; i != NumElems; ++i)
5453       Mask.push_back(EltNo);
5454
5455     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5456   }
5457
5458   return SDValue();
5459 }
5460
5461 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5462 /// vector of type 'VT', see if the elements can be replaced by a single large
5463 /// load which has the same value as a build_vector whose operands are 'elts'.
5464 ///
5465 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5466 ///
5467 /// FIXME: we'd also like to handle the case where the last elements are zero
5468 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5469 /// There's even a handy isZeroNode for that purpose.
5470 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5471                                         SDLoc &DL, SelectionDAG &DAG,
5472                                         bool isAfterLegalize) {
5473   EVT EltVT = VT.getVectorElementType();
5474   unsigned NumElems = Elts.size();
5475
5476   LoadSDNode *LDBase = NULL;
5477   unsigned LastLoadedElt = -1U;
5478
5479   // For each element in the initializer, see if we've found a load or an undef.
5480   // If we don't find an initial load element, or later load elements are
5481   // non-consecutive, bail out.
5482   for (unsigned i = 0; i < NumElems; ++i) {
5483     SDValue Elt = Elts[i];
5484
5485     if (!Elt.getNode() ||
5486         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5487       return SDValue();
5488     if (!LDBase) {
5489       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5490         return SDValue();
5491       LDBase = cast<LoadSDNode>(Elt.getNode());
5492       LastLoadedElt = i;
5493       continue;
5494     }
5495     if (Elt.getOpcode() == ISD::UNDEF)
5496       continue;
5497
5498     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5499     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5500       return SDValue();
5501     LastLoadedElt = i;
5502   }
5503
5504   // If we have found an entire vector of loads and undefs, then return a large
5505   // load of the entire vector width starting at the base pointer.  If we found
5506   // consecutive loads for the low half, generate a vzext_load node.
5507   if (LastLoadedElt == NumElems - 1) {
5508
5509     if (isAfterLegalize &&
5510         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5511       return SDValue();
5512
5513     SDValue NewLd = SDValue();
5514
5515     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5516       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5517                           LDBase->getPointerInfo(),
5518                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5519                           LDBase->isInvariant(), 0);
5520     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5521                         LDBase->getPointerInfo(),
5522                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5523                         LDBase->isInvariant(), LDBase->getAlignment());
5524
5525     if (LDBase->hasAnyUseOfValue(1)) {
5526       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5527                                      SDValue(LDBase, 1),
5528                                      SDValue(NewLd.getNode(), 1));
5529       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5530       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5531                              SDValue(NewLd.getNode(), 1));
5532     }
5533
5534     return NewLd;
5535   }
5536   if (NumElems == 4 && LastLoadedElt == 1 &&
5537       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5538     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5539     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5540     SDValue ResNode =
5541         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5542                                 array_lengthof(Ops), MVT::i64,
5543                                 LDBase->getPointerInfo(),
5544                                 LDBase->getAlignment(),
5545                                 false/*isVolatile*/, true/*ReadMem*/,
5546                                 false/*WriteMem*/);
5547
5548     // Make sure the newly-created LOAD is in the same position as LDBase in
5549     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5550     // update uses of LDBase's output chain to use the TokenFactor.
5551     if (LDBase->hasAnyUseOfValue(1)) {
5552       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5553                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5554       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5555       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5556                              SDValue(ResNode.getNode(), 1));
5557     }
5558
5559     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5560   }
5561   return SDValue();
5562 }
5563
5564 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5565 /// to generate a splat value for the following cases:
5566 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5567 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5568 /// a scalar load, or a constant.
5569 /// The VBROADCAST node is returned when a pattern is found,
5570 /// or SDValue() otherwise.
5571 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5572                                     SelectionDAG &DAG) {
5573   if (!Subtarget->hasFp256())
5574     return SDValue();
5575
5576   MVT VT = Op.getSimpleValueType();
5577   SDLoc dl(Op);
5578
5579   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5580          "Unsupported vector type for broadcast.");
5581
5582   SDValue Ld;
5583   bool ConstSplatVal;
5584
5585   switch (Op.getOpcode()) {
5586     default:
5587       // Unknown pattern found.
5588       return SDValue();
5589
5590     case ISD::BUILD_VECTOR: {
5591       // The BUILD_VECTOR node must be a splat.
5592       if (!isSplatVector(Op.getNode()))
5593         return SDValue();
5594
5595       Ld = Op.getOperand(0);
5596       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5597                      Ld.getOpcode() == ISD::ConstantFP);
5598
5599       // The suspected load node has several users. Make sure that all
5600       // of its users are from the BUILD_VECTOR node.
5601       // Constants may have multiple users.
5602       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5603         return SDValue();
5604       break;
5605     }
5606
5607     case ISD::VECTOR_SHUFFLE: {
5608       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5609
5610       // Shuffles must have a splat mask where the first element is
5611       // broadcasted.
5612       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5613         return SDValue();
5614
5615       SDValue Sc = Op.getOperand(0);
5616       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5617           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5618
5619         if (!Subtarget->hasInt256())
5620           return SDValue();
5621
5622         // Use the register form of the broadcast instruction available on AVX2.
5623         if (VT.getSizeInBits() >= 256)
5624           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5625         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5626       }
5627
5628       Ld = Sc.getOperand(0);
5629       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5630                        Ld.getOpcode() == ISD::ConstantFP);
5631
5632       // The scalar_to_vector node and the suspected
5633       // load node must have exactly one user.
5634       // Constants may have multiple users.
5635
5636       // AVX-512 has register version of the broadcast
5637       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5638         Ld.getValueType().getSizeInBits() >= 32;
5639       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5640           !hasRegVer))
5641         return SDValue();
5642       break;
5643     }
5644   }
5645
5646   bool IsGE256 = (VT.getSizeInBits() >= 256);
5647
5648   // Handle the broadcasting a single constant scalar from the constant pool
5649   // into a vector. On Sandybridge it is still better to load a constant vector
5650   // from the constant pool and not to broadcast it from a scalar.
5651   if (ConstSplatVal && Subtarget->hasInt256()) {
5652     EVT CVT = Ld.getValueType();
5653     assert(!CVT.isVector() && "Must not broadcast a vector type");
5654     unsigned ScalarSize = CVT.getSizeInBits();
5655
5656     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5657       const Constant *C = 0;
5658       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5659         C = CI->getConstantIntValue();
5660       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5661         C = CF->getConstantFPValue();
5662
5663       assert(C && "Invalid constant type");
5664
5665       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5666       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5667       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5668       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5669                        MachinePointerInfo::getConstantPool(),
5670                        false, false, false, Alignment);
5671
5672       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5673     }
5674   }
5675
5676   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5677   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5678
5679   // Handle AVX2 in-register broadcasts.
5680   if (!IsLoad && Subtarget->hasInt256() &&
5681       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5682     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5683
5684   // The scalar source must be a normal load.
5685   if (!IsLoad)
5686     return SDValue();
5687
5688   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5689     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5690
5691   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5692   // double since there is no vbroadcastsd xmm
5693   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5694     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5695       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5696   }
5697
5698   // Unsupported broadcast.
5699   return SDValue();
5700 }
5701
5702 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5703   MVT VT = Op.getSimpleValueType();
5704
5705   // Skip if insert_vec_elt is not supported.
5706   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5707   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5708     return SDValue();
5709
5710   SDLoc DL(Op);
5711   unsigned NumElems = Op.getNumOperands();
5712
5713   SDValue VecIn1;
5714   SDValue VecIn2;
5715   SmallVector<unsigned, 4> InsertIndices;
5716   SmallVector<int, 8> Mask(NumElems, -1);
5717
5718   for (unsigned i = 0; i != NumElems; ++i) {
5719     unsigned Opc = Op.getOperand(i).getOpcode();
5720
5721     if (Opc == ISD::UNDEF)
5722       continue;
5723
5724     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5725       // Quit if more than 1 elements need inserting.
5726       if (InsertIndices.size() > 1)
5727         return SDValue();
5728
5729       InsertIndices.push_back(i);
5730       continue;
5731     }
5732
5733     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5734     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5735
5736     // Quit if extracted from vector of different type.
5737     if (ExtractedFromVec.getValueType() != VT)
5738       return SDValue();
5739
5740     // Quit if non-constant index.
5741     if (!isa<ConstantSDNode>(ExtIdx))
5742       return SDValue();
5743
5744     if (VecIn1.getNode() == 0)
5745       VecIn1 = ExtractedFromVec;
5746     else if (VecIn1 != ExtractedFromVec) {
5747       if (VecIn2.getNode() == 0)
5748         VecIn2 = ExtractedFromVec;
5749       else if (VecIn2 != ExtractedFromVec)
5750         // Quit if more than 2 vectors to shuffle
5751         return SDValue();
5752     }
5753
5754     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5755
5756     if (ExtractedFromVec == VecIn1)
5757       Mask[i] = Idx;
5758     else if (ExtractedFromVec == VecIn2)
5759       Mask[i] = Idx + NumElems;
5760   }
5761
5762   if (VecIn1.getNode() == 0)
5763     return SDValue();
5764
5765   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5766   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5767   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5768     unsigned Idx = InsertIndices[i];
5769     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5770                      DAG.getIntPtrConstant(Idx));
5771   }
5772
5773   return NV;
5774 }
5775
5776 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5777 SDValue
5778 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5779
5780   MVT VT = Op.getSimpleValueType();
5781   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5782          "Unexpected type in LowerBUILD_VECTORvXi1!");
5783
5784   SDLoc dl(Op);
5785   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5786     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5787     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5788                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5789     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5790                        Ops, VT.getVectorNumElements());
5791   }
5792
5793   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5794     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5795     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5796                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5797     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5798                        Ops, VT.getVectorNumElements());
5799   }
5800
5801   bool AllContants = true;
5802   uint64_t Immediate = 0;
5803   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5804     SDValue In = Op.getOperand(idx);
5805     if (In.getOpcode() == ISD::UNDEF)
5806       continue;
5807     if (!isa<ConstantSDNode>(In)) {
5808       AllContants = false;
5809       break;
5810     }
5811     if (cast<ConstantSDNode>(In)->getZExtValue())
5812       Immediate |= (1ULL << idx);
5813   }
5814
5815   if (AllContants) {
5816     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5817       DAG.getConstant(Immediate, MVT::i16));
5818     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5819                        DAG.getIntPtrConstant(0));
5820   }
5821
5822   // Splat vector (with undefs)
5823   SDValue In = Op.getOperand(0);
5824   for (unsigned i = 1, e = Op.getNumOperands(); i != e; ++i) {
5825     if (Op.getOperand(i) != In && Op.getOperand(i).getOpcode() != ISD::UNDEF)
5826       llvm_unreachable("Unsupported predicate operation");
5827   }
5828
5829   SDValue EFLAGS, X86CC;
5830   if (In.getOpcode() == ISD::SETCC) {
5831     SDValue Op0 = In.getOperand(0);
5832     SDValue Op1 = In.getOperand(1);
5833     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5834     bool isFP = Op1.getValueType().isFloatingPoint();
5835     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5836
5837     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5838
5839     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5840     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5841     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5842   } else if (In.getOpcode() == X86ISD::SETCC) {
5843     X86CC = In.getOperand(0);
5844     EFLAGS = In.getOperand(1);
5845   } else {
5846     // The algorithm:
5847     //   Bit1 = In & 0x1
5848     //   if (Bit1 != 0)
5849     //     ZF = 0
5850     //   else
5851     //     ZF = 1
5852     //   if (ZF == 0)
5853     //     res = allOnes ### CMOVNE -1, %res
5854     //   else
5855     //     res = allZero
5856     MVT InVT = In.getSimpleValueType();
5857     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5858     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5859     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5860   }
5861
5862   if (VT == MVT::v16i1) {
5863     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5864     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5865     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5866           Cst0, Cst1, X86CC, EFLAGS);
5867     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5868   }
5869
5870   if (VT == MVT::v8i1) {
5871     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5872     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5873     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5874           Cst0, Cst1, X86CC, EFLAGS);
5875     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5876     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5877   }
5878   llvm_unreachable("Unsupported predicate operation");
5879 }
5880
5881 SDValue
5882 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5883   SDLoc dl(Op);
5884
5885   MVT VT = Op.getSimpleValueType();
5886   MVT ExtVT = VT.getVectorElementType();
5887   unsigned NumElems = Op.getNumOperands();
5888
5889   // Generate vectors for predicate vectors.
5890   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5891     return LowerBUILD_VECTORvXi1(Op, DAG);
5892
5893   // Vectors containing all zeros can be matched by pxor and xorps later
5894   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5895     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5896     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5897     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5898       return Op;
5899
5900     return getZeroVector(VT, Subtarget, DAG, dl);
5901   }
5902
5903   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5904   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5905   // vpcmpeqd on 256-bit vectors.
5906   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5907     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5908       return Op;
5909
5910     if (!VT.is512BitVector())
5911       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5912   }
5913
5914   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5915   if (Broadcast.getNode())
5916     return Broadcast;
5917
5918   unsigned EVTBits = ExtVT.getSizeInBits();
5919
5920   unsigned NumZero  = 0;
5921   unsigned NumNonZero = 0;
5922   unsigned NonZeros = 0;
5923   bool IsAllConstants = true;
5924   SmallSet<SDValue, 8> Values;
5925   for (unsigned i = 0; i < NumElems; ++i) {
5926     SDValue Elt = Op.getOperand(i);
5927     if (Elt.getOpcode() == ISD::UNDEF)
5928       continue;
5929     Values.insert(Elt);
5930     if (Elt.getOpcode() != ISD::Constant &&
5931         Elt.getOpcode() != ISD::ConstantFP)
5932       IsAllConstants = false;
5933     if (X86::isZeroNode(Elt))
5934       NumZero++;
5935     else {
5936       NonZeros |= (1 << i);
5937       NumNonZero++;
5938     }
5939   }
5940
5941   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5942   if (NumNonZero == 0)
5943     return DAG.getUNDEF(VT);
5944
5945   // Special case for single non-zero, non-undef, element.
5946   if (NumNonZero == 1) {
5947     unsigned Idx = countTrailingZeros(NonZeros);
5948     SDValue Item = Op.getOperand(Idx);
5949
5950     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5951     // the value are obviously zero, truncate the value to i32 and do the
5952     // insertion that way.  Only do this if the value is non-constant or if the
5953     // value is a constant being inserted into element 0.  It is cheaper to do
5954     // a constant pool load than it is to do a movd + shuffle.
5955     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5956         (!IsAllConstants || Idx == 0)) {
5957       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5958         // Handle SSE only.
5959         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5960         EVT VecVT = MVT::v4i32;
5961         unsigned VecElts = 4;
5962
5963         // Truncate the value (which may itself be a constant) to i32, and
5964         // convert it to a vector with movd (S2V+shuffle to zero extend).
5965         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5966         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5967         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5968
5969         // Now we have our 32-bit value zero extended in the low element of
5970         // a vector.  If Idx != 0, swizzle it into place.
5971         if (Idx != 0) {
5972           SmallVector<int, 4> Mask;
5973           Mask.push_back(Idx);
5974           for (unsigned i = 1; i != VecElts; ++i)
5975             Mask.push_back(i);
5976           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5977                                       &Mask[0]);
5978         }
5979         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5980       }
5981     }
5982
5983     // If we have a constant or non-constant insertion into the low element of
5984     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5985     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5986     // depending on what the source datatype is.
5987     if (Idx == 0) {
5988       if (NumZero == 0)
5989         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5990
5991       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5992           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5993         if (VT.is256BitVector() || VT.is512BitVector()) {
5994           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5995           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5996                              Item, DAG.getIntPtrConstant(0));
5997         }
5998         assert(VT.is128BitVector() && "Expected an SSE value type!");
5999         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6000         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6001         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6002       }
6003
6004       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6005         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6006         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6007         if (VT.is256BitVector()) {
6008           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6009           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6010         } else {
6011           assert(VT.is128BitVector() && "Expected an SSE value type!");
6012           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6013         }
6014         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6015       }
6016     }
6017
6018     // Is it a vector logical left shift?
6019     if (NumElems == 2 && Idx == 1 &&
6020         X86::isZeroNode(Op.getOperand(0)) &&
6021         !X86::isZeroNode(Op.getOperand(1))) {
6022       unsigned NumBits = VT.getSizeInBits();
6023       return getVShift(true, VT,
6024                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6025                                    VT, Op.getOperand(1)),
6026                        NumBits/2, DAG, *this, dl);
6027     }
6028
6029     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6030       return SDValue();
6031
6032     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6033     // is a non-constant being inserted into an element other than the low one,
6034     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6035     // movd/movss) to move this into the low element, then shuffle it into
6036     // place.
6037     if (EVTBits == 32) {
6038       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6039
6040       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6041       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6042       SmallVector<int, 8> MaskVec;
6043       for (unsigned i = 0; i != NumElems; ++i)
6044         MaskVec.push_back(i == Idx ? 0 : 1);
6045       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6046     }
6047   }
6048
6049   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6050   if (Values.size() == 1) {
6051     if (EVTBits == 32) {
6052       // Instead of a shuffle like this:
6053       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6054       // Check if it's possible to issue this instead.
6055       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6056       unsigned Idx = countTrailingZeros(NonZeros);
6057       SDValue Item = Op.getOperand(Idx);
6058       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6059         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6060     }
6061     return SDValue();
6062   }
6063
6064   // A vector full of immediates; various special cases are already
6065   // handled, so this is best done with a single constant-pool load.
6066   if (IsAllConstants)
6067     return SDValue();
6068
6069   // For AVX-length vectors, build the individual 128-bit pieces and use
6070   // shuffles to put them in place.
6071   if (VT.is256BitVector()) {
6072     SmallVector<SDValue, 32> V;
6073     for (unsigned i = 0; i != NumElems; ++i)
6074       V.push_back(Op.getOperand(i));
6075
6076     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6077
6078     // Build both the lower and upper subvector.
6079     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6080     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6081                                 NumElems/2);
6082
6083     // Recreate the wider vector with the lower and upper part.
6084     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6085   }
6086
6087   // Let legalizer expand 2-wide build_vectors.
6088   if (EVTBits == 64) {
6089     if (NumNonZero == 1) {
6090       // One half is zero or undef.
6091       unsigned Idx = countTrailingZeros(NonZeros);
6092       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6093                                  Op.getOperand(Idx));
6094       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6095     }
6096     return SDValue();
6097   }
6098
6099   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6100   if (EVTBits == 8 && NumElems == 16) {
6101     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6102                                         Subtarget, *this);
6103     if (V.getNode()) return V;
6104   }
6105
6106   if (EVTBits == 16 && NumElems == 8) {
6107     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6108                                       Subtarget, *this);
6109     if (V.getNode()) return V;
6110   }
6111
6112   // If element VT is == 32 bits, turn it into a number of shuffles.
6113   SmallVector<SDValue, 8> V(NumElems);
6114   if (NumElems == 4 && NumZero > 0) {
6115     for (unsigned i = 0; i < 4; ++i) {
6116       bool isZero = !(NonZeros & (1 << i));
6117       if (isZero)
6118         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6119       else
6120         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6121     }
6122
6123     for (unsigned i = 0; i < 2; ++i) {
6124       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6125         default: break;
6126         case 0:
6127           V[i] = V[i*2];  // Must be a zero vector.
6128           break;
6129         case 1:
6130           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6131           break;
6132         case 2:
6133           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6134           break;
6135         case 3:
6136           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6137           break;
6138       }
6139     }
6140
6141     bool Reverse1 = (NonZeros & 0x3) == 2;
6142     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6143     int MaskVec[] = {
6144       Reverse1 ? 1 : 0,
6145       Reverse1 ? 0 : 1,
6146       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6147       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6148     };
6149     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6150   }
6151
6152   if (Values.size() > 1 && VT.is128BitVector()) {
6153     // Check for a build vector of consecutive loads.
6154     for (unsigned i = 0; i < NumElems; ++i)
6155       V[i] = Op.getOperand(i);
6156
6157     // Check for elements which are consecutive loads.
6158     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6159     if (LD.getNode())
6160       return LD;
6161
6162     // Check for a build vector from mostly shuffle plus few inserting.
6163     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6164     if (Sh.getNode())
6165       return Sh;
6166
6167     // For SSE 4.1, use insertps to put the high elements into the low element.
6168     if (getSubtarget()->hasSSE41()) {
6169       SDValue Result;
6170       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6171         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6172       else
6173         Result = DAG.getUNDEF(VT);
6174
6175       for (unsigned i = 1; i < NumElems; ++i) {
6176         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6177         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6178                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6179       }
6180       return Result;
6181     }
6182
6183     // Otherwise, expand into a number of unpckl*, start by extending each of
6184     // our (non-undef) elements to the full vector width with the element in the
6185     // bottom slot of the vector (which generates no code for SSE).
6186     for (unsigned i = 0; i < NumElems; ++i) {
6187       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6188         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6189       else
6190         V[i] = DAG.getUNDEF(VT);
6191     }
6192
6193     // Next, we iteratively mix elements, e.g. for v4f32:
6194     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6195     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6196     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6197     unsigned EltStride = NumElems >> 1;
6198     while (EltStride != 0) {
6199       for (unsigned i = 0; i < EltStride; ++i) {
6200         // If V[i+EltStride] is undef and this is the first round of mixing,
6201         // then it is safe to just drop this shuffle: V[i] is already in the
6202         // right place, the one element (since it's the first round) being
6203         // inserted as undef can be dropped.  This isn't safe for successive
6204         // rounds because they will permute elements within both vectors.
6205         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6206             EltStride == NumElems/2)
6207           continue;
6208
6209         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6210       }
6211       EltStride >>= 1;
6212     }
6213     return V[0];
6214   }
6215   return SDValue();
6216 }
6217
6218 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6219 // to create 256-bit vectors from two other 128-bit ones.
6220 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6221   SDLoc dl(Op);
6222   MVT ResVT = Op.getSimpleValueType();
6223
6224   assert((ResVT.is256BitVector() ||
6225           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6226
6227   SDValue V1 = Op.getOperand(0);
6228   SDValue V2 = Op.getOperand(1);
6229   unsigned NumElems = ResVT.getVectorNumElements();
6230   if(ResVT.is256BitVector())
6231     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6232
6233   if (Op.getNumOperands() == 4) {
6234     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6235                                 ResVT.getVectorNumElements()/2);
6236     SDValue V3 = Op.getOperand(2);
6237     SDValue V4 = Op.getOperand(3);
6238     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6239       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6240   }
6241   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6242 }
6243
6244 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6245   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6246   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6247          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6248           Op.getNumOperands() == 4)));
6249
6250   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6251   // from two other 128-bit ones.
6252
6253   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6254   return LowerAVXCONCAT_VECTORS(Op, DAG);
6255 }
6256
6257 // Try to lower a shuffle node into a simple blend instruction.
6258 static SDValue
6259 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6260                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6261   SDValue V1 = SVOp->getOperand(0);
6262   SDValue V2 = SVOp->getOperand(1);
6263   SDLoc dl(SVOp);
6264   MVT VT = SVOp->getSimpleValueType(0);
6265   MVT EltVT = VT.getVectorElementType();
6266   unsigned NumElems = VT.getVectorNumElements();
6267
6268   // There is no blend with immediate in AVX-512.
6269   if (VT.is512BitVector())
6270     return SDValue();
6271
6272   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6273     return SDValue();
6274   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6275     return SDValue();
6276
6277   // Check the mask for BLEND and build the value.
6278   unsigned MaskValue = 0;
6279   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6280   unsigned NumLanes = (NumElems-1)/8 + 1;
6281   unsigned NumElemsInLane = NumElems / NumLanes;
6282
6283   // Blend for v16i16 should be symetric for the both lanes.
6284   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6285
6286     int SndLaneEltIdx = (NumLanes == 2) ?
6287       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6288     int EltIdx = SVOp->getMaskElt(i);
6289
6290     if ((EltIdx < 0 || EltIdx == (int)i) &&
6291         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6292       continue;
6293
6294     if (((unsigned)EltIdx == (i + NumElems)) &&
6295         (SndLaneEltIdx < 0 ||
6296          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6297       MaskValue |= (1<<i);
6298     else
6299       return SDValue();
6300   }
6301
6302   // Convert i32 vectors to floating point if it is not AVX2.
6303   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6304   MVT BlendVT = VT;
6305   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6306     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6307                                NumElems);
6308     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6309     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6310   }
6311
6312   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6313                             DAG.getConstant(MaskValue, MVT::i32));
6314   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6315 }
6316
6317 // v8i16 shuffles - Prefer shuffles in the following order:
6318 // 1. [all]   pshuflw, pshufhw, optional move
6319 // 2. [ssse3] 1 x pshufb
6320 // 3. [ssse3] 2 x pshufb + 1 x por
6321 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6322 static SDValue
6323 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6324                          SelectionDAG &DAG) {
6325   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6326   SDValue V1 = SVOp->getOperand(0);
6327   SDValue V2 = SVOp->getOperand(1);
6328   SDLoc dl(SVOp);
6329   SmallVector<int, 8> MaskVals;
6330
6331   // Determine if more than 1 of the words in each of the low and high quadwords
6332   // of the result come from the same quadword of one of the two inputs.  Undef
6333   // mask values count as coming from any quadword, for better codegen.
6334   unsigned LoQuad[] = { 0, 0, 0, 0 };
6335   unsigned HiQuad[] = { 0, 0, 0, 0 };
6336   std::bitset<4> InputQuads;
6337   for (unsigned i = 0; i < 8; ++i) {
6338     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6339     int EltIdx = SVOp->getMaskElt(i);
6340     MaskVals.push_back(EltIdx);
6341     if (EltIdx < 0) {
6342       ++Quad[0];
6343       ++Quad[1];
6344       ++Quad[2];
6345       ++Quad[3];
6346       continue;
6347     }
6348     ++Quad[EltIdx / 4];
6349     InputQuads.set(EltIdx / 4);
6350   }
6351
6352   int BestLoQuad = -1;
6353   unsigned MaxQuad = 1;
6354   for (unsigned i = 0; i < 4; ++i) {
6355     if (LoQuad[i] > MaxQuad) {
6356       BestLoQuad = i;
6357       MaxQuad = LoQuad[i];
6358     }
6359   }
6360
6361   int BestHiQuad = -1;
6362   MaxQuad = 1;
6363   for (unsigned i = 0; i < 4; ++i) {
6364     if (HiQuad[i] > MaxQuad) {
6365       BestHiQuad = i;
6366       MaxQuad = HiQuad[i];
6367     }
6368   }
6369
6370   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6371   // of the two input vectors, shuffle them into one input vector so only a
6372   // single pshufb instruction is necessary. If There are more than 2 input
6373   // quads, disable the next transformation since it does not help SSSE3.
6374   bool V1Used = InputQuads[0] || InputQuads[1];
6375   bool V2Used = InputQuads[2] || InputQuads[3];
6376   if (Subtarget->hasSSSE3()) {
6377     if (InputQuads.count() == 2 && V1Used && V2Used) {
6378       BestLoQuad = InputQuads[0] ? 0 : 1;
6379       BestHiQuad = InputQuads[2] ? 2 : 3;
6380     }
6381     if (InputQuads.count() > 2) {
6382       BestLoQuad = -1;
6383       BestHiQuad = -1;
6384     }
6385   }
6386
6387   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6388   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6389   // words from all 4 input quadwords.
6390   SDValue NewV;
6391   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6392     int MaskV[] = {
6393       BestLoQuad < 0 ? 0 : BestLoQuad,
6394       BestHiQuad < 0 ? 1 : BestHiQuad
6395     };
6396     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6397                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6398                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6399     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6400
6401     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6402     // source words for the shuffle, to aid later transformations.
6403     bool AllWordsInNewV = true;
6404     bool InOrder[2] = { true, true };
6405     for (unsigned i = 0; i != 8; ++i) {
6406       int idx = MaskVals[i];
6407       if (idx != (int)i)
6408         InOrder[i/4] = false;
6409       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6410         continue;
6411       AllWordsInNewV = false;
6412       break;
6413     }
6414
6415     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6416     if (AllWordsInNewV) {
6417       for (int i = 0; i != 8; ++i) {
6418         int idx = MaskVals[i];
6419         if (idx < 0)
6420           continue;
6421         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6422         if ((idx != i) && idx < 4)
6423           pshufhw = false;
6424         if ((idx != i) && idx > 3)
6425           pshuflw = false;
6426       }
6427       V1 = NewV;
6428       V2Used = false;
6429       BestLoQuad = 0;
6430       BestHiQuad = 1;
6431     }
6432
6433     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6434     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6435     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6436       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6437       unsigned TargetMask = 0;
6438       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6439                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6440       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6441       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6442                              getShufflePSHUFLWImmediate(SVOp);
6443       V1 = NewV.getOperand(0);
6444       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6445     }
6446   }
6447
6448   // Promote splats to a larger type which usually leads to more efficient code.
6449   // FIXME: Is this true if pshufb is available?
6450   if (SVOp->isSplat())
6451     return PromoteSplat(SVOp, DAG);
6452
6453   // If we have SSSE3, and all words of the result are from 1 input vector,
6454   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6455   // is present, fall back to case 4.
6456   if (Subtarget->hasSSSE3()) {
6457     SmallVector<SDValue,16> pshufbMask;
6458
6459     // If we have elements from both input vectors, set the high bit of the
6460     // shuffle mask element to zero out elements that come from V2 in the V1
6461     // mask, and elements that come from V1 in the V2 mask, so that the two
6462     // results can be OR'd together.
6463     bool TwoInputs = V1Used && V2Used;
6464     for (unsigned i = 0; i != 8; ++i) {
6465       int EltIdx = MaskVals[i] * 2;
6466       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6467       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6468       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6469       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6470     }
6471     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6472     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6473                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6474                                  MVT::v16i8, &pshufbMask[0], 16));
6475     if (!TwoInputs)
6476       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6477
6478     // Calculate the shuffle mask for the second input, shuffle it, and
6479     // OR it with the first shuffled input.
6480     pshufbMask.clear();
6481     for (unsigned i = 0; i != 8; ++i) {
6482       int EltIdx = MaskVals[i] * 2;
6483       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6484       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6485       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6486       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6487     }
6488     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6489     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6490                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6491                                  MVT::v16i8, &pshufbMask[0], 16));
6492     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6493     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6494   }
6495
6496   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6497   // and update MaskVals with new element order.
6498   std::bitset<8> InOrder;
6499   if (BestLoQuad >= 0) {
6500     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6501     for (int i = 0; i != 4; ++i) {
6502       int idx = MaskVals[i];
6503       if (idx < 0) {
6504         InOrder.set(i);
6505       } else if ((idx / 4) == BestLoQuad) {
6506         MaskV[i] = idx & 3;
6507         InOrder.set(i);
6508       }
6509     }
6510     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6511                                 &MaskV[0]);
6512
6513     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6514       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6515       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6516                                   NewV.getOperand(0),
6517                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6518     }
6519   }
6520
6521   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6522   // and update MaskVals with the new element order.
6523   if (BestHiQuad >= 0) {
6524     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6525     for (unsigned i = 4; i != 8; ++i) {
6526       int idx = MaskVals[i];
6527       if (idx < 0) {
6528         InOrder.set(i);
6529       } else if ((idx / 4) == BestHiQuad) {
6530         MaskV[i] = (idx & 3) + 4;
6531         InOrder.set(i);
6532       }
6533     }
6534     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6535                                 &MaskV[0]);
6536
6537     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6538       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6539       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6540                                   NewV.getOperand(0),
6541                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6542     }
6543   }
6544
6545   // In case BestHi & BestLo were both -1, which means each quadword has a word
6546   // from each of the four input quadwords, calculate the InOrder bitvector now
6547   // before falling through to the insert/extract cleanup.
6548   if (BestLoQuad == -1 && BestHiQuad == -1) {
6549     NewV = V1;
6550     for (int i = 0; i != 8; ++i)
6551       if (MaskVals[i] < 0 || MaskVals[i] == i)
6552         InOrder.set(i);
6553   }
6554
6555   // The other elements are put in the right place using pextrw and pinsrw.
6556   for (unsigned i = 0; i != 8; ++i) {
6557     if (InOrder[i])
6558       continue;
6559     int EltIdx = MaskVals[i];
6560     if (EltIdx < 0)
6561       continue;
6562     SDValue ExtOp = (EltIdx < 8) ?
6563       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6564                   DAG.getIntPtrConstant(EltIdx)) :
6565       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6566                   DAG.getIntPtrConstant(EltIdx - 8));
6567     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6568                        DAG.getIntPtrConstant(i));
6569   }
6570   return NewV;
6571 }
6572
6573 // v16i8 shuffles - Prefer shuffles in the following order:
6574 // 1. [ssse3] 1 x pshufb
6575 // 2. [ssse3] 2 x pshufb + 1 x por
6576 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6577 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6578                                         const X86Subtarget* Subtarget,
6579                                         SelectionDAG &DAG) {
6580   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6581   SDValue V1 = SVOp->getOperand(0);
6582   SDValue V2 = SVOp->getOperand(1);
6583   SDLoc dl(SVOp);
6584   ArrayRef<int> MaskVals = SVOp->getMask();
6585
6586   // Promote splats to a larger type which usually leads to more efficient code.
6587   // FIXME: Is this true if pshufb is available?
6588   if (SVOp->isSplat())
6589     return PromoteSplat(SVOp, DAG);
6590
6591   // If we have SSSE3, case 1 is generated when all result bytes come from
6592   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6593   // present, fall back to case 3.
6594
6595   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6596   if (Subtarget->hasSSSE3()) {
6597     SmallVector<SDValue,16> pshufbMask;
6598
6599     // If all result elements are from one input vector, then only translate
6600     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6601     //
6602     // Otherwise, we have elements from both input vectors, and must zero out
6603     // elements that come from V2 in the first mask, and V1 in the second mask
6604     // so that we can OR them together.
6605     for (unsigned i = 0; i != 16; ++i) {
6606       int EltIdx = MaskVals[i];
6607       if (EltIdx < 0 || EltIdx >= 16)
6608         EltIdx = 0x80;
6609       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6610     }
6611     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6612                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6613                                  MVT::v16i8, &pshufbMask[0], 16));
6614
6615     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6616     // the 2nd operand if it's undefined or zero.
6617     if (V2.getOpcode() == ISD::UNDEF ||
6618         ISD::isBuildVectorAllZeros(V2.getNode()))
6619       return V1;
6620
6621     // Calculate the shuffle mask for the second input, shuffle it, and
6622     // OR it with the first shuffled input.
6623     pshufbMask.clear();
6624     for (unsigned i = 0; i != 16; ++i) {
6625       int EltIdx = MaskVals[i];
6626       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6627       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6628     }
6629     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6630                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6631                                  MVT::v16i8, &pshufbMask[0], 16));
6632     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6633   }
6634
6635   // No SSSE3 - Calculate in place words and then fix all out of place words
6636   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6637   // the 16 different words that comprise the two doublequadword input vectors.
6638   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6639   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6640   SDValue NewV = V1;
6641   for (int i = 0; i != 8; ++i) {
6642     int Elt0 = MaskVals[i*2];
6643     int Elt1 = MaskVals[i*2+1];
6644
6645     // This word of the result is all undef, skip it.
6646     if (Elt0 < 0 && Elt1 < 0)
6647       continue;
6648
6649     // This word of the result is already in the correct place, skip it.
6650     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6651       continue;
6652
6653     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6654     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6655     SDValue InsElt;
6656
6657     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6658     // using a single extract together, load it and store it.
6659     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6660       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6661                            DAG.getIntPtrConstant(Elt1 / 2));
6662       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6663                         DAG.getIntPtrConstant(i));
6664       continue;
6665     }
6666
6667     // If Elt1 is defined, extract it from the appropriate source.  If the
6668     // source byte is not also odd, shift the extracted word left 8 bits
6669     // otherwise clear the bottom 8 bits if we need to do an or.
6670     if (Elt1 >= 0) {
6671       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6672                            DAG.getIntPtrConstant(Elt1 / 2));
6673       if ((Elt1 & 1) == 0)
6674         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6675                              DAG.getConstant(8,
6676                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6677       else if (Elt0 >= 0)
6678         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6679                              DAG.getConstant(0xFF00, MVT::i16));
6680     }
6681     // If Elt0 is defined, extract it from the appropriate source.  If the
6682     // source byte is not also even, shift the extracted word right 8 bits. If
6683     // Elt1 was also defined, OR the extracted values together before
6684     // inserting them in the result.
6685     if (Elt0 >= 0) {
6686       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6687                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6688       if ((Elt0 & 1) != 0)
6689         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6690                               DAG.getConstant(8,
6691                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6692       else if (Elt1 >= 0)
6693         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6694                              DAG.getConstant(0x00FF, MVT::i16));
6695       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6696                          : InsElt0;
6697     }
6698     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6699                        DAG.getIntPtrConstant(i));
6700   }
6701   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6702 }
6703
6704 // v32i8 shuffles - Translate to VPSHUFB if possible.
6705 static
6706 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6707                                  const X86Subtarget *Subtarget,
6708                                  SelectionDAG &DAG) {
6709   MVT VT = SVOp->getSimpleValueType(0);
6710   SDValue V1 = SVOp->getOperand(0);
6711   SDValue V2 = SVOp->getOperand(1);
6712   SDLoc dl(SVOp);
6713   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6714
6715   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6716   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6717   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6718
6719   // VPSHUFB may be generated if
6720   // (1) one of input vector is undefined or zeroinitializer.
6721   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6722   // And (2) the mask indexes don't cross the 128-bit lane.
6723   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6724       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6725     return SDValue();
6726
6727   if (V1IsAllZero && !V2IsAllZero) {
6728     CommuteVectorShuffleMask(MaskVals, 32);
6729     V1 = V2;
6730   }
6731   SmallVector<SDValue, 32> pshufbMask;
6732   for (unsigned i = 0; i != 32; i++) {
6733     int EltIdx = MaskVals[i];
6734     if (EltIdx < 0 || EltIdx >= 32)
6735       EltIdx = 0x80;
6736     else {
6737       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6738         // Cross lane is not allowed.
6739         return SDValue();
6740       EltIdx &= 0xf;
6741     }
6742     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6743   }
6744   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6745                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6746                                   MVT::v32i8, &pshufbMask[0], 32));
6747 }
6748
6749 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6750 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6751 /// done when every pair / quad of shuffle mask elements point to elements in
6752 /// the right sequence. e.g.
6753 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6754 static
6755 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6756                                  SelectionDAG &DAG) {
6757   MVT VT = SVOp->getSimpleValueType(0);
6758   SDLoc dl(SVOp);
6759   unsigned NumElems = VT.getVectorNumElements();
6760   MVT NewVT;
6761   unsigned Scale;
6762   switch (VT.SimpleTy) {
6763   default: llvm_unreachable("Unexpected!");
6764   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6765   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6766   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6767   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6768   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6769   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6770   }
6771
6772   SmallVector<int, 8> MaskVec;
6773   for (unsigned i = 0; i != NumElems; i += Scale) {
6774     int StartIdx = -1;
6775     for (unsigned j = 0; j != Scale; ++j) {
6776       int EltIdx = SVOp->getMaskElt(i+j);
6777       if (EltIdx < 0)
6778         continue;
6779       if (StartIdx < 0)
6780         StartIdx = (EltIdx / Scale);
6781       if (EltIdx != (int)(StartIdx*Scale + j))
6782         return SDValue();
6783     }
6784     MaskVec.push_back(StartIdx);
6785   }
6786
6787   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6788   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6789   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6790 }
6791
6792 /// getVZextMovL - Return a zero-extending vector move low node.
6793 ///
6794 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6795                             SDValue SrcOp, SelectionDAG &DAG,
6796                             const X86Subtarget *Subtarget, SDLoc dl) {
6797   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6798     LoadSDNode *LD = NULL;
6799     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6800       LD = dyn_cast<LoadSDNode>(SrcOp);
6801     if (!LD) {
6802       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6803       // instead.
6804       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6805       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6806           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6807           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6808           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6809         // PR2108
6810         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6811         return DAG.getNode(ISD::BITCAST, dl, VT,
6812                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6813                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6814                                                    OpVT,
6815                                                    SrcOp.getOperand(0)
6816                                                           .getOperand(0))));
6817       }
6818     }
6819   }
6820
6821   return DAG.getNode(ISD::BITCAST, dl, VT,
6822                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6823                                  DAG.getNode(ISD::BITCAST, dl,
6824                                              OpVT, SrcOp)));
6825 }
6826
6827 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6828 /// which could not be matched by any known target speficic shuffle
6829 static SDValue
6830 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6831
6832   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6833   if (NewOp.getNode())
6834     return NewOp;
6835
6836   MVT VT = SVOp->getSimpleValueType(0);
6837
6838   unsigned NumElems = VT.getVectorNumElements();
6839   unsigned NumLaneElems = NumElems / 2;
6840
6841   SDLoc dl(SVOp);
6842   MVT EltVT = VT.getVectorElementType();
6843   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6844   SDValue Output[2];
6845
6846   SmallVector<int, 16> Mask;
6847   for (unsigned l = 0; l < 2; ++l) {
6848     // Build a shuffle mask for the output, discovering on the fly which
6849     // input vectors to use as shuffle operands (recorded in InputUsed).
6850     // If building a suitable shuffle vector proves too hard, then bail
6851     // out with UseBuildVector set.
6852     bool UseBuildVector = false;
6853     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6854     unsigned LaneStart = l * NumLaneElems;
6855     for (unsigned i = 0; i != NumLaneElems; ++i) {
6856       // The mask element.  This indexes into the input.
6857       int Idx = SVOp->getMaskElt(i+LaneStart);
6858       if (Idx < 0) {
6859         // the mask element does not index into any input vector.
6860         Mask.push_back(-1);
6861         continue;
6862       }
6863
6864       // The input vector this mask element indexes into.
6865       int Input = Idx / NumLaneElems;
6866
6867       // Turn the index into an offset from the start of the input vector.
6868       Idx -= Input * NumLaneElems;
6869
6870       // Find or create a shuffle vector operand to hold this input.
6871       unsigned OpNo;
6872       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6873         if (InputUsed[OpNo] == Input)
6874           // This input vector is already an operand.
6875           break;
6876         if (InputUsed[OpNo] < 0) {
6877           // Create a new operand for this input vector.
6878           InputUsed[OpNo] = Input;
6879           break;
6880         }
6881       }
6882
6883       if (OpNo >= array_lengthof(InputUsed)) {
6884         // More than two input vectors used!  Give up on trying to create a
6885         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6886         UseBuildVector = true;
6887         break;
6888       }
6889
6890       // Add the mask index for the new shuffle vector.
6891       Mask.push_back(Idx + OpNo * NumLaneElems);
6892     }
6893
6894     if (UseBuildVector) {
6895       SmallVector<SDValue, 16> SVOps;
6896       for (unsigned i = 0; i != NumLaneElems; ++i) {
6897         // The mask element.  This indexes into the input.
6898         int Idx = SVOp->getMaskElt(i+LaneStart);
6899         if (Idx < 0) {
6900           SVOps.push_back(DAG.getUNDEF(EltVT));
6901           continue;
6902         }
6903
6904         // The input vector this mask element indexes into.
6905         int Input = Idx / NumElems;
6906
6907         // Turn the index into an offset from the start of the input vector.
6908         Idx -= Input * NumElems;
6909
6910         // Extract the vector element by hand.
6911         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6912                                     SVOp->getOperand(Input),
6913                                     DAG.getIntPtrConstant(Idx)));
6914       }
6915
6916       // Construct the output using a BUILD_VECTOR.
6917       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6918                               SVOps.size());
6919     } else if (InputUsed[0] < 0) {
6920       // No input vectors were used! The result is undefined.
6921       Output[l] = DAG.getUNDEF(NVT);
6922     } else {
6923       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6924                                         (InputUsed[0] % 2) * NumLaneElems,
6925                                         DAG, dl);
6926       // If only one input was used, use an undefined vector for the other.
6927       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6928         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6929                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6930       // At least one input vector was used. Create a new shuffle vector.
6931       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6932     }
6933
6934     Mask.clear();
6935   }
6936
6937   // Concatenate the result back
6938   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6939 }
6940
6941 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6942 /// 4 elements, and match them with several different shuffle types.
6943 static SDValue
6944 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6945   SDValue V1 = SVOp->getOperand(0);
6946   SDValue V2 = SVOp->getOperand(1);
6947   SDLoc dl(SVOp);
6948   MVT VT = SVOp->getSimpleValueType(0);
6949
6950   assert(VT.is128BitVector() && "Unsupported vector size");
6951
6952   std::pair<int, int> Locs[4];
6953   int Mask1[] = { -1, -1, -1, -1 };
6954   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6955
6956   unsigned NumHi = 0;
6957   unsigned NumLo = 0;
6958   for (unsigned i = 0; i != 4; ++i) {
6959     int Idx = PermMask[i];
6960     if (Idx < 0) {
6961       Locs[i] = std::make_pair(-1, -1);
6962     } else {
6963       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6964       if (Idx < 4) {
6965         Locs[i] = std::make_pair(0, NumLo);
6966         Mask1[NumLo] = Idx;
6967         NumLo++;
6968       } else {
6969         Locs[i] = std::make_pair(1, NumHi);
6970         if (2+NumHi < 4)
6971           Mask1[2+NumHi] = Idx;
6972         NumHi++;
6973       }
6974     }
6975   }
6976
6977   if (NumLo <= 2 && NumHi <= 2) {
6978     // If no more than two elements come from either vector. This can be
6979     // implemented with two shuffles. First shuffle gather the elements.
6980     // The second shuffle, which takes the first shuffle as both of its
6981     // vector operands, put the elements into the right order.
6982     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6983
6984     int Mask2[] = { -1, -1, -1, -1 };
6985
6986     for (unsigned i = 0; i != 4; ++i)
6987       if (Locs[i].first != -1) {
6988         unsigned Idx = (i < 2) ? 0 : 4;
6989         Idx += Locs[i].first * 2 + Locs[i].second;
6990         Mask2[i] = Idx;
6991       }
6992
6993     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6994   }
6995
6996   if (NumLo == 3 || NumHi == 3) {
6997     // Otherwise, we must have three elements from one vector, call it X, and
6998     // one element from the other, call it Y.  First, use a shufps to build an
6999     // intermediate vector with the one element from Y and the element from X
7000     // that will be in the same half in the final destination (the indexes don't
7001     // matter). Then, use a shufps to build the final vector, taking the half
7002     // containing the element from Y from the intermediate, and the other half
7003     // from X.
7004     if (NumHi == 3) {
7005       // Normalize it so the 3 elements come from V1.
7006       CommuteVectorShuffleMask(PermMask, 4);
7007       std::swap(V1, V2);
7008     }
7009
7010     // Find the element from V2.
7011     unsigned HiIndex;
7012     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7013       int Val = PermMask[HiIndex];
7014       if (Val < 0)
7015         continue;
7016       if (Val >= 4)
7017         break;
7018     }
7019
7020     Mask1[0] = PermMask[HiIndex];
7021     Mask1[1] = -1;
7022     Mask1[2] = PermMask[HiIndex^1];
7023     Mask1[3] = -1;
7024     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7025
7026     if (HiIndex >= 2) {
7027       Mask1[0] = PermMask[0];
7028       Mask1[1] = PermMask[1];
7029       Mask1[2] = HiIndex & 1 ? 6 : 4;
7030       Mask1[3] = HiIndex & 1 ? 4 : 6;
7031       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7032     }
7033
7034     Mask1[0] = HiIndex & 1 ? 2 : 0;
7035     Mask1[1] = HiIndex & 1 ? 0 : 2;
7036     Mask1[2] = PermMask[2];
7037     Mask1[3] = PermMask[3];
7038     if (Mask1[2] >= 0)
7039       Mask1[2] += 4;
7040     if (Mask1[3] >= 0)
7041       Mask1[3] += 4;
7042     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7043   }
7044
7045   // Break it into (shuffle shuffle_hi, shuffle_lo).
7046   int LoMask[] = { -1, -1, -1, -1 };
7047   int HiMask[] = { -1, -1, -1, -1 };
7048
7049   int *MaskPtr = LoMask;
7050   unsigned MaskIdx = 0;
7051   unsigned LoIdx = 0;
7052   unsigned HiIdx = 2;
7053   for (unsigned i = 0; i != 4; ++i) {
7054     if (i == 2) {
7055       MaskPtr = HiMask;
7056       MaskIdx = 1;
7057       LoIdx = 0;
7058       HiIdx = 2;
7059     }
7060     int Idx = PermMask[i];
7061     if (Idx < 0) {
7062       Locs[i] = std::make_pair(-1, -1);
7063     } else if (Idx < 4) {
7064       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7065       MaskPtr[LoIdx] = Idx;
7066       LoIdx++;
7067     } else {
7068       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7069       MaskPtr[HiIdx] = Idx;
7070       HiIdx++;
7071     }
7072   }
7073
7074   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7075   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7076   int MaskOps[] = { -1, -1, -1, -1 };
7077   for (unsigned i = 0; i != 4; ++i)
7078     if (Locs[i].first != -1)
7079       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7080   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7081 }
7082
7083 static bool MayFoldVectorLoad(SDValue V) {
7084   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7085     V = V.getOperand(0);
7086
7087   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7088     V = V.getOperand(0);
7089   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7090       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7091     // BUILD_VECTOR (load), undef
7092     V = V.getOperand(0);
7093
7094   return MayFoldLoad(V);
7095 }
7096
7097 static
7098 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7099   MVT VT = Op.getSimpleValueType();
7100
7101   // Canonizalize to v2f64.
7102   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7103   return DAG.getNode(ISD::BITCAST, dl, VT,
7104                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7105                                           V1, DAG));
7106 }
7107
7108 static
7109 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7110                         bool HasSSE2) {
7111   SDValue V1 = Op.getOperand(0);
7112   SDValue V2 = Op.getOperand(1);
7113   MVT VT = Op.getSimpleValueType();
7114
7115   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7116
7117   if (HasSSE2 && VT == MVT::v2f64)
7118     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7119
7120   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7121   return DAG.getNode(ISD::BITCAST, dl, VT,
7122                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7123                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7124                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7125 }
7126
7127 static
7128 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7129   SDValue V1 = Op.getOperand(0);
7130   SDValue V2 = Op.getOperand(1);
7131   MVT VT = Op.getSimpleValueType();
7132
7133   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7134          "unsupported shuffle type");
7135
7136   if (V2.getOpcode() == ISD::UNDEF)
7137     V2 = V1;
7138
7139   // v4i32 or v4f32
7140   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7141 }
7142
7143 static
7144 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7145   SDValue V1 = Op.getOperand(0);
7146   SDValue V2 = Op.getOperand(1);
7147   MVT VT = Op.getSimpleValueType();
7148   unsigned NumElems = VT.getVectorNumElements();
7149
7150   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7151   // operand of these instructions is only memory, so check if there's a
7152   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7153   // same masks.
7154   bool CanFoldLoad = false;
7155
7156   // Trivial case, when V2 comes from a load.
7157   if (MayFoldVectorLoad(V2))
7158     CanFoldLoad = true;
7159
7160   // When V1 is a load, it can be folded later into a store in isel, example:
7161   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7162   //    turns into:
7163   //  (MOVLPSmr addr:$src1, VR128:$src2)
7164   // So, recognize this potential and also use MOVLPS or MOVLPD
7165   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7166     CanFoldLoad = true;
7167
7168   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7169   if (CanFoldLoad) {
7170     if (HasSSE2 && NumElems == 2)
7171       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7172
7173     if (NumElems == 4)
7174       // If we don't care about the second element, proceed to use movss.
7175       if (SVOp->getMaskElt(1) != -1)
7176         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7177   }
7178
7179   // movl and movlp will both match v2i64, but v2i64 is never matched by
7180   // movl earlier because we make it strict to avoid messing with the movlp load
7181   // folding logic (see the code above getMOVLP call). Match it here then,
7182   // this is horrible, but will stay like this until we move all shuffle
7183   // matching to x86 specific nodes. Note that for the 1st condition all
7184   // types are matched with movsd.
7185   if (HasSSE2) {
7186     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7187     // as to remove this logic from here, as much as possible
7188     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7189       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7190     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7191   }
7192
7193   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7194
7195   // Invert the operand order and use SHUFPS to match it.
7196   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7197                               getShuffleSHUFImmediate(SVOp), DAG);
7198 }
7199
7200 // Reduce a vector shuffle to zext.
7201 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7202                                     SelectionDAG &DAG) {
7203   // PMOVZX is only available from SSE41.
7204   if (!Subtarget->hasSSE41())
7205     return SDValue();
7206
7207   MVT VT = Op.getSimpleValueType();
7208
7209   // Only AVX2 support 256-bit vector integer extending.
7210   if (!Subtarget->hasInt256() && VT.is256BitVector())
7211     return SDValue();
7212
7213   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7214   SDLoc DL(Op);
7215   SDValue V1 = Op.getOperand(0);
7216   SDValue V2 = Op.getOperand(1);
7217   unsigned NumElems = VT.getVectorNumElements();
7218
7219   // Extending is an unary operation and the element type of the source vector
7220   // won't be equal to or larger than i64.
7221   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7222       VT.getVectorElementType() == MVT::i64)
7223     return SDValue();
7224
7225   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7226   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7227   while ((1U << Shift) < NumElems) {
7228     if (SVOp->getMaskElt(1U << Shift) == 1)
7229       break;
7230     Shift += 1;
7231     // The maximal ratio is 8, i.e. from i8 to i64.
7232     if (Shift > 3)
7233       return SDValue();
7234   }
7235
7236   // Check the shuffle mask.
7237   unsigned Mask = (1U << Shift) - 1;
7238   for (unsigned i = 0; i != NumElems; ++i) {
7239     int EltIdx = SVOp->getMaskElt(i);
7240     if ((i & Mask) != 0 && EltIdx != -1)
7241       return SDValue();
7242     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7243       return SDValue();
7244   }
7245
7246   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7247   MVT NeVT = MVT::getIntegerVT(NBits);
7248   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7249
7250   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7251     return SDValue();
7252
7253   // Simplify the operand as it's prepared to be fed into shuffle.
7254   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7255   if (V1.getOpcode() == ISD::BITCAST &&
7256       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7257       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7258       V1.getOperand(0).getOperand(0)
7259         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7260     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7261     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7262     ConstantSDNode *CIdx =
7263       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7264     // If it's foldable, i.e. normal load with single use, we will let code
7265     // selection to fold it. Otherwise, we will short the conversion sequence.
7266     if (CIdx && CIdx->getZExtValue() == 0 &&
7267         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7268       MVT FullVT = V.getSimpleValueType();
7269       MVT V1VT = V1.getSimpleValueType();
7270       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7271         // The "ext_vec_elt" node is wider than the result node.
7272         // In this case we should extract subvector from V.
7273         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7274         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7275         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7276                                         FullVT.getVectorNumElements()/Ratio);
7277         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7278                         DAG.getIntPtrConstant(0));
7279       }
7280       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7281     }
7282   }
7283
7284   return DAG.getNode(ISD::BITCAST, DL, VT,
7285                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7286 }
7287
7288 static SDValue
7289 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7290                        SelectionDAG &DAG) {
7291   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7292   MVT VT = Op.getSimpleValueType();
7293   SDLoc dl(Op);
7294   SDValue V1 = Op.getOperand(0);
7295   SDValue V2 = Op.getOperand(1);
7296
7297   if (isZeroShuffle(SVOp))
7298     return getZeroVector(VT, Subtarget, DAG, dl);
7299
7300   // Handle splat operations
7301   if (SVOp->isSplat()) {
7302     // Use vbroadcast whenever the splat comes from a foldable load
7303     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7304     if (Broadcast.getNode())
7305       return Broadcast;
7306   }
7307
7308   // Check integer expanding shuffles.
7309   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7310   if (NewOp.getNode())
7311     return NewOp;
7312
7313   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7314   // do it!
7315   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7316       VT == MVT::v16i16 || VT == MVT::v32i8) {
7317     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7318     if (NewOp.getNode())
7319       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7320   } else if ((VT == MVT::v4i32 ||
7321              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7322     // FIXME: Figure out a cleaner way to do this.
7323     // Try to make use of movq to zero out the top part.
7324     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7325       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7326       if (NewOp.getNode()) {
7327         MVT NewVT = NewOp.getSimpleValueType();
7328         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7329                                NewVT, true, false))
7330           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7331                               DAG, Subtarget, dl);
7332       }
7333     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7334       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7335       if (NewOp.getNode()) {
7336         MVT NewVT = NewOp.getSimpleValueType();
7337         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7338           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7339                               DAG, Subtarget, dl);
7340       }
7341     }
7342   }
7343   return SDValue();
7344 }
7345
7346 SDValue
7347 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7348   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7349   SDValue V1 = Op.getOperand(0);
7350   SDValue V2 = Op.getOperand(1);
7351   MVT VT = Op.getSimpleValueType();
7352   SDLoc dl(Op);
7353   unsigned NumElems = VT.getVectorNumElements();
7354   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7355   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7356   bool V1IsSplat = false;
7357   bool V2IsSplat = false;
7358   bool HasSSE2 = Subtarget->hasSSE2();
7359   bool HasFp256    = Subtarget->hasFp256();
7360   bool HasInt256   = Subtarget->hasInt256();
7361   MachineFunction &MF = DAG.getMachineFunction();
7362   bool OptForSize = MF.getFunction()->getAttributes().
7363     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7364
7365   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7366
7367   if (V1IsUndef && V2IsUndef)
7368     return DAG.getUNDEF(VT);
7369
7370   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7371
7372   // Vector shuffle lowering takes 3 steps:
7373   //
7374   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7375   //    narrowing and commutation of operands should be handled.
7376   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7377   //    shuffle nodes.
7378   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7379   //    so the shuffle can be broken into other shuffles and the legalizer can
7380   //    try the lowering again.
7381   //
7382   // The general idea is that no vector_shuffle operation should be left to
7383   // be matched during isel, all of them must be converted to a target specific
7384   // node here.
7385
7386   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7387   // narrowing and commutation of operands should be handled. The actual code
7388   // doesn't include all of those, work in progress...
7389   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7390   if (NewOp.getNode())
7391     return NewOp;
7392
7393   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7394
7395   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7396   // unpckh_undef). Only use pshufd if speed is more important than size.
7397   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7398     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7399   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7400     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7401
7402   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7403       V2IsUndef && MayFoldVectorLoad(V1))
7404     return getMOVDDup(Op, dl, V1, DAG);
7405
7406   if (isMOVHLPS_v_undef_Mask(M, VT))
7407     return getMOVHighToLow(Op, dl, DAG);
7408
7409   // Use to match splats
7410   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7411       (VT == MVT::v2f64 || VT == MVT::v2i64))
7412     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7413
7414   if (isPSHUFDMask(M, VT)) {
7415     // The actual implementation will match the mask in the if above and then
7416     // during isel it can match several different instructions, not only pshufd
7417     // as its name says, sad but true, emulate the behavior for now...
7418     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7419       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7420
7421     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7422
7423     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7424       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7425
7426     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7427       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7428                                   DAG);
7429
7430     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7431                                 TargetMask, DAG);
7432   }
7433
7434   if (isPALIGNRMask(M, VT, Subtarget))
7435     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7436                                 getShufflePALIGNRImmediate(SVOp),
7437                                 DAG);
7438
7439   // Check if this can be converted into a logical shift.
7440   bool isLeft = false;
7441   unsigned ShAmt = 0;
7442   SDValue ShVal;
7443   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7444   if (isShift && ShVal.hasOneUse()) {
7445     // If the shifted value has multiple uses, it may be cheaper to use
7446     // v_set0 + movlhps or movhlps, etc.
7447     MVT EltVT = VT.getVectorElementType();
7448     ShAmt *= EltVT.getSizeInBits();
7449     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7450   }
7451
7452   if (isMOVLMask(M, VT)) {
7453     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7454       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7455     if (!isMOVLPMask(M, VT)) {
7456       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7457         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7458
7459       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7460         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7461     }
7462   }
7463
7464   // FIXME: fold these into legal mask.
7465   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7466     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7467
7468   if (isMOVHLPSMask(M, VT))
7469     return getMOVHighToLow(Op, dl, DAG);
7470
7471   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7472     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7473
7474   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7475     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7476
7477   if (isMOVLPMask(M, VT))
7478     return getMOVLP(Op, dl, DAG, HasSSE2);
7479
7480   if (ShouldXformToMOVHLPS(M, VT) ||
7481       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7482     return CommuteVectorShuffle(SVOp, DAG);
7483
7484   if (isShift) {
7485     // No better options. Use a vshldq / vsrldq.
7486     MVT EltVT = VT.getVectorElementType();
7487     ShAmt *= EltVT.getSizeInBits();
7488     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7489   }
7490
7491   bool Commuted = false;
7492   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7493   // 1,1,1,1 -> v8i16 though.
7494   V1IsSplat = isSplatVector(V1.getNode());
7495   V2IsSplat = isSplatVector(V2.getNode());
7496
7497   // Canonicalize the splat or undef, if present, to be on the RHS.
7498   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7499     CommuteVectorShuffleMask(M, NumElems);
7500     std::swap(V1, V2);
7501     std::swap(V1IsSplat, V2IsSplat);
7502     Commuted = true;
7503   }
7504
7505   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7506     // Shuffling low element of v1 into undef, just return v1.
7507     if (V2IsUndef)
7508       return V1;
7509     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7510     // the instruction selector will not match, so get a canonical MOVL with
7511     // swapped operands to undo the commute.
7512     return getMOVL(DAG, dl, VT, V2, V1);
7513   }
7514
7515   if (isUNPCKLMask(M, VT, HasInt256))
7516     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7517
7518   if (isUNPCKHMask(M, VT, HasInt256))
7519     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7520
7521   if (V2IsSplat) {
7522     // Normalize mask so all entries that point to V2 points to its first
7523     // element then try to match unpck{h|l} again. If match, return a
7524     // new vector_shuffle with the corrected mask.p
7525     SmallVector<int, 8> NewMask(M.begin(), M.end());
7526     NormalizeMask(NewMask, NumElems);
7527     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7528       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7529     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7530       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7531   }
7532
7533   if (Commuted) {
7534     // Commute is back and try unpck* again.
7535     // FIXME: this seems wrong.
7536     CommuteVectorShuffleMask(M, NumElems);
7537     std::swap(V1, V2);
7538     std::swap(V1IsSplat, V2IsSplat);
7539     Commuted = false;
7540
7541     if (isUNPCKLMask(M, VT, HasInt256))
7542       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7543
7544     if (isUNPCKHMask(M, VT, HasInt256))
7545       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7546   }
7547
7548   // Normalize the node to match x86 shuffle ops if needed
7549   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7550     return CommuteVectorShuffle(SVOp, DAG);
7551
7552   // The checks below are all present in isShuffleMaskLegal, but they are
7553   // inlined here right now to enable us to directly emit target specific
7554   // nodes, and remove one by one until they don't return Op anymore.
7555
7556   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7557       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7558     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7559       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7560   }
7561
7562   if (isPSHUFHWMask(M, VT, HasInt256))
7563     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7564                                 getShufflePSHUFHWImmediate(SVOp),
7565                                 DAG);
7566
7567   if (isPSHUFLWMask(M, VT, HasInt256))
7568     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7569                                 getShufflePSHUFLWImmediate(SVOp),
7570                                 DAG);
7571
7572   if (isSHUFPMask(M, VT))
7573     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7574                                 getShuffleSHUFImmediate(SVOp), DAG);
7575
7576   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7577     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7578   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7579     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7580
7581   //===--------------------------------------------------------------------===//
7582   // Generate target specific nodes for 128 or 256-bit shuffles only
7583   // supported in the AVX instruction set.
7584   //
7585
7586   // Handle VMOVDDUPY permutations
7587   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7588     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7589
7590   // Handle VPERMILPS/D* permutations
7591   if (isVPERMILPMask(M, VT)) {
7592     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7593       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7594                                   getShuffleSHUFImmediate(SVOp), DAG);
7595     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7596                                 getShuffleSHUFImmediate(SVOp), DAG);
7597   }
7598
7599   // Handle VPERM2F128/VPERM2I128 permutations
7600   if (isVPERM2X128Mask(M, VT, HasFp256))
7601     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7602                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7603
7604   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7605   if (BlendOp.getNode())
7606     return BlendOp;
7607
7608   unsigned Imm8;
7609   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7610     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7611
7612   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7613       VT.is512BitVector()) {
7614     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7615     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7616     SmallVector<SDValue, 16> permclMask;
7617     for (unsigned i = 0; i != NumElems; ++i) {
7618       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7619     }
7620
7621     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7622                                 &permclMask[0], NumElems);
7623     if (V2IsUndef)
7624       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7625       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7626                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7627     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7628                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7629   }
7630
7631   //===--------------------------------------------------------------------===//
7632   // Since no target specific shuffle was selected for this generic one,
7633   // lower it into other known shuffles. FIXME: this isn't true yet, but
7634   // this is the plan.
7635   //
7636
7637   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7638   if (VT == MVT::v8i16) {
7639     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7640     if (NewOp.getNode())
7641       return NewOp;
7642   }
7643
7644   if (VT == MVT::v16i8) {
7645     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7646     if (NewOp.getNode())
7647       return NewOp;
7648   }
7649
7650   if (VT == MVT::v32i8) {
7651     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7652     if (NewOp.getNode())
7653       return NewOp;
7654   }
7655
7656   // Handle all 128-bit wide vectors with 4 elements, and match them with
7657   // several different shuffle types.
7658   if (NumElems == 4 && VT.is128BitVector())
7659     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7660
7661   // Handle general 256-bit shuffles
7662   if (VT.is256BitVector())
7663     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7664
7665   return SDValue();
7666 }
7667
7668 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7669   MVT VT = Op.getSimpleValueType();
7670   SDLoc dl(Op);
7671
7672   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7673     return SDValue();
7674
7675   if (VT.getSizeInBits() == 8) {
7676     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7677                                   Op.getOperand(0), Op.getOperand(1));
7678     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7679                                   DAG.getValueType(VT));
7680     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7681   }
7682
7683   if (VT.getSizeInBits() == 16) {
7684     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7685     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7686     if (Idx == 0)
7687       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7688                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7689                                      DAG.getNode(ISD::BITCAST, dl,
7690                                                  MVT::v4i32,
7691                                                  Op.getOperand(0)),
7692                                      Op.getOperand(1)));
7693     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7694                                   Op.getOperand(0), Op.getOperand(1));
7695     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7696                                   DAG.getValueType(VT));
7697     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7698   }
7699
7700   if (VT == MVT::f32) {
7701     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7702     // the result back to FR32 register. It's only worth matching if the
7703     // result has a single use which is a store or a bitcast to i32.  And in
7704     // the case of a store, it's not worth it if the index is a constant 0,
7705     // because a MOVSSmr can be used instead, which is smaller and faster.
7706     if (!Op.hasOneUse())
7707       return SDValue();
7708     SDNode *User = *Op.getNode()->use_begin();
7709     if ((User->getOpcode() != ISD::STORE ||
7710          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7711           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7712         (User->getOpcode() != ISD::BITCAST ||
7713          User->getValueType(0) != MVT::i32))
7714       return SDValue();
7715     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7716                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7717                                               Op.getOperand(0)),
7718                                               Op.getOperand(1));
7719     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7720   }
7721
7722   if (VT == MVT::i32 || VT == MVT::i64) {
7723     // ExtractPS/pextrq works with constant index.
7724     if (isa<ConstantSDNode>(Op.getOperand(1)))
7725       return Op;
7726   }
7727   return SDValue();
7728 }
7729
7730 /// Extract one bit from mask vector, like v16i1 or v8i1.
7731 /// AVX-512 feature.
7732 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) {
7733   SDValue Vec = Op.getOperand(0);
7734   SDLoc dl(Vec);
7735   MVT VecVT = Vec.getSimpleValueType();
7736   SDValue Idx = Op.getOperand(1);
7737   MVT EltVT = Op.getSimpleValueType();
7738
7739   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7740
7741   // variable index can't be handled in mask registers,
7742   // extend vector to VR512
7743   if (!isa<ConstantSDNode>(Idx)) {
7744     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7745     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7746     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7747                               ExtVT.getVectorElementType(), Ext, Idx);
7748     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7749   }
7750
7751   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7752   if (IdxVal) {
7753     unsigned MaxSift = VecVT.getSizeInBits() - 1;
7754     Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7755                       DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7756     Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7757                       DAG.getConstant(MaxSift, MVT::i8));
7758   }
7759   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i1, Vec,
7760                        DAG.getIntPtrConstant(0));
7761 }
7762
7763 SDValue
7764 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7765                                            SelectionDAG &DAG) const {
7766   SDLoc dl(Op);
7767   SDValue Vec = Op.getOperand(0);
7768   MVT VecVT = Vec.getSimpleValueType();
7769   SDValue Idx = Op.getOperand(1);
7770
7771   if (Op.getSimpleValueType() == MVT::i1)
7772     return ExtractBitFromMaskVector(Op, DAG);
7773
7774   if (!isa<ConstantSDNode>(Idx)) {
7775     if (VecVT.is512BitVector() ||
7776         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7777          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7778
7779       MVT MaskEltVT =
7780         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7781       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7782                                     MaskEltVT.getSizeInBits());
7783
7784       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7785       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7786                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7787                                 Idx, DAG.getConstant(0, getPointerTy()));
7788       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7789       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7790                         Perm, DAG.getConstant(0, getPointerTy()));
7791     }
7792     return SDValue();
7793   }
7794
7795   // If this is a 256-bit vector result, first extract the 128-bit vector and
7796   // then extract the element from the 128-bit vector.
7797   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7798
7799     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7800     // Get the 128-bit vector.
7801     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7802     MVT EltVT = VecVT.getVectorElementType();
7803
7804     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7805
7806     //if (IdxVal >= NumElems/2)
7807     //  IdxVal -= NumElems/2;
7808     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7809     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7810                        DAG.getConstant(IdxVal, MVT::i32));
7811   }
7812
7813   assert(VecVT.is128BitVector() && "Unexpected vector length");
7814
7815   if (Subtarget->hasSSE41()) {
7816     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7817     if (Res.getNode())
7818       return Res;
7819   }
7820
7821   MVT VT = Op.getSimpleValueType();
7822   // TODO: handle v16i8.
7823   if (VT.getSizeInBits() == 16) {
7824     SDValue Vec = Op.getOperand(0);
7825     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7826     if (Idx == 0)
7827       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7828                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7829                                      DAG.getNode(ISD::BITCAST, dl,
7830                                                  MVT::v4i32, Vec),
7831                                      Op.getOperand(1)));
7832     // Transform it so it match pextrw which produces a 32-bit result.
7833     MVT EltVT = MVT::i32;
7834     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7835                                   Op.getOperand(0), Op.getOperand(1));
7836     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7837                                   DAG.getValueType(VT));
7838     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7839   }
7840
7841   if (VT.getSizeInBits() == 32) {
7842     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7843     if (Idx == 0)
7844       return Op;
7845
7846     // SHUFPS the element to the lowest double word, then movss.
7847     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7848     MVT VVT = Op.getOperand(0).getSimpleValueType();
7849     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7850                                        DAG.getUNDEF(VVT), Mask);
7851     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7852                        DAG.getIntPtrConstant(0));
7853   }
7854
7855   if (VT.getSizeInBits() == 64) {
7856     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7857     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7858     //        to match extract_elt for f64.
7859     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7860     if (Idx == 0)
7861       return Op;
7862
7863     // UNPCKHPD the element to the lowest double word, then movsd.
7864     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7865     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7866     int Mask[2] = { 1, -1 };
7867     MVT VVT = Op.getOperand(0).getSimpleValueType();
7868     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7869                                        DAG.getUNDEF(VVT), Mask);
7870     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7871                        DAG.getIntPtrConstant(0));
7872   }
7873
7874   return SDValue();
7875 }
7876
7877 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7878   MVT VT = Op.getSimpleValueType();
7879   MVT EltVT = VT.getVectorElementType();
7880   SDLoc dl(Op);
7881
7882   SDValue N0 = Op.getOperand(0);
7883   SDValue N1 = Op.getOperand(1);
7884   SDValue N2 = Op.getOperand(2);
7885
7886   if (!VT.is128BitVector())
7887     return SDValue();
7888
7889   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7890       isa<ConstantSDNode>(N2)) {
7891     unsigned Opc;
7892     if (VT == MVT::v8i16)
7893       Opc = X86ISD::PINSRW;
7894     else if (VT == MVT::v16i8)
7895       Opc = X86ISD::PINSRB;
7896     else
7897       Opc = X86ISD::PINSRB;
7898
7899     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7900     // argument.
7901     if (N1.getValueType() != MVT::i32)
7902       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7903     if (N2.getValueType() != MVT::i32)
7904       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7905     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7906   }
7907
7908   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7909     // Bits [7:6] of the constant are the source select.  This will always be
7910     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7911     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7912     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7913     // Bits [5:4] of the constant are the destination select.  This is the
7914     //  value of the incoming immediate.
7915     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7916     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7917     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7918     // Create this as a scalar to vector..
7919     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7920     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7921   }
7922
7923   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7924     // PINSR* works with constant index.
7925     return Op;
7926   }
7927   return SDValue();
7928 }
7929
7930 SDValue
7931 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7932   MVT VT = Op.getSimpleValueType();
7933   MVT EltVT = VT.getVectorElementType();
7934
7935   SDLoc dl(Op);
7936   SDValue N0 = Op.getOperand(0);
7937   SDValue N1 = Op.getOperand(1);
7938   SDValue N2 = Op.getOperand(2);
7939
7940   // If this is a 256-bit vector result, first extract the 128-bit vector,
7941   // insert the element into the extracted half and then place it back.
7942   if (VT.is256BitVector() || VT.is512BitVector()) {
7943     if (!isa<ConstantSDNode>(N2))
7944       return SDValue();
7945
7946     // Get the desired 128-bit vector half.
7947     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7948     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7949
7950     // Insert the element into the desired half.
7951     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7952     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7953
7954     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7955                     DAG.getConstant(IdxIn128, MVT::i32));
7956
7957     // Insert the changed part back to the 256-bit vector
7958     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7959   }
7960
7961   if (Subtarget->hasSSE41())
7962     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7963
7964   if (EltVT == MVT::i8)
7965     return SDValue();
7966
7967   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7968     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7969     // as its second argument.
7970     if (N1.getValueType() != MVT::i32)
7971       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7972     if (N2.getValueType() != MVT::i32)
7973       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7974     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7975   }
7976   return SDValue();
7977 }
7978
7979 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7980   SDLoc dl(Op);
7981   MVT OpVT = Op.getSimpleValueType();
7982
7983   // If this is a 256-bit vector result, first insert into a 128-bit
7984   // vector and then insert into the 256-bit vector.
7985   if (!OpVT.is128BitVector()) {
7986     // Insert into a 128-bit vector.
7987     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7988     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7989                                  OpVT.getVectorNumElements() / SizeFactor);
7990
7991     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7992
7993     // Insert the 128-bit vector.
7994     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7995   }
7996
7997   if (OpVT == MVT::v1i64 &&
7998       Op.getOperand(0).getValueType() == MVT::i64)
7999     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8000
8001   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8002   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8003   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8004                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8005 }
8006
8007 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8008 // a simple subregister reference or explicit instructions to grab
8009 // upper bits of a vector.
8010 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8011                                       SelectionDAG &DAG) {
8012   SDLoc dl(Op);
8013   SDValue In =  Op.getOperand(0);
8014   SDValue Idx = Op.getOperand(1);
8015   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8016   MVT ResVT   = Op.getSimpleValueType();
8017   MVT InVT    = In.getSimpleValueType();
8018
8019   if (Subtarget->hasFp256()) {
8020     if (ResVT.is128BitVector() &&
8021         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8022         isa<ConstantSDNode>(Idx)) {
8023       return Extract128BitVector(In, IdxVal, DAG, dl);
8024     }
8025     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8026         isa<ConstantSDNode>(Idx)) {
8027       return Extract256BitVector(In, IdxVal, DAG, dl);
8028     }
8029   }
8030   return SDValue();
8031 }
8032
8033 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8034 // simple superregister reference or explicit instructions to insert
8035 // the upper bits of a vector.
8036 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8037                                      SelectionDAG &DAG) {
8038   if (Subtarget->hasFp256()) {
8039     SDLoc dl(Op.getNode());
8040     SDValue Vec = Op.getNode()->getOperand(0);
8041     SDValue SubVec = Op.getNode()->getOperand(1);
8042     SDValue Idx = Op.getNode()->getOperand(2);
8043
8044     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8045          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8046         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8047         isa<ConstantSDNode>(Idx)) {
8048       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8049       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8050     }
8051
8052     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8053         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8054         isa<ConstantSDNode>(Idx)) {
8055       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8056       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8057     }
8058   }
8059   return SDValue();
8060 }
8061
8062 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8063 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8064 // one of the above mentioned nodes. It has to be wrapped because otherwise
8065 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8066 // be used to form addressing mode. These wrapped nodes will be selected
8067 // into MOV32ri.
8068 SDValue
8069 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8070   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8071
8072   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8073   // global base reg.
8074   unsigned char OpFlag = 0;
8075   unsigned WrapperKind = X86ISD::Wrapper;
8076   CodeModel::Model M = getTargetMachine().getCodeModel();
8077
8078   if (Subtarget->isPICStyleRIPRel() &&
8079       (M == CodeModel::Small || M == CodeModel::Kernel))
8080     WrapperKind = X86ISD::WrapperRIP;
8081   else if (Subtarget->isPICStyleGOT())
8082     OpFlag = X86II::MO_GOTOFF;
8083   else if (Subtarget->isPICStyleStubPIC())
8084     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8085
8086   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8087                                              CP->getAlignment(),
8088                                              CP->getOffset(), OpFlag);
8089   SDLoc DL(CP);
8090   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8091   // With PIC, the address is actually $g + Offset.
8092   if (OpFlag) {
8093     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8094                          DAG.getNode(X86ISD::GlobalBaseReg,
8095                                      SDLoc(), getPointerTy()),
8096                          Result);
8097   }
8098
8099   return Result;
8100 }
8101
8102 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8103   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8104
8105   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8106   // global base reg.
8107   unsigned char OpFlag = 0;
8108   unsigned WrapperKind = X86ISD::Wrapper;
8109   CodeModel::Model M = getTargetMachine().getCodeModel();
8110
8111   if (Subtarget->isPICStyleRIPRel() &&
8112       (M == CodeModel::Small || M == CodeModel::Kernel))
8113     WrapperKind = X86ISD::WrapperRIP;
8114   else if (Subtarget->isPICStyleGOT())
8115     OpFlag = X86II::MO_GOTOFF;
8116   else if (Subtarget->isPICStyleStubPIC())
8117     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8118
8119   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8120                                           OpFlag);
8121   SDLoc DL(JT);
8122   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8123
8124   // With PIC, the address is actually $g + Offset.
8125   if (OpFlag)
8126     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8127                          DAG.getNode(X86ISD::GlobalBaseReg,
8128                                      SDLoc(), getPointerTy()),
8129                          Result);
8130
8131   return Result;
8132 }
8133
8134 SDValue
8135 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8136   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8137
8138   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8139   // global base reg.
8140   unsigned char OpFlag = 0;
8141   unsigned WrapperKind = X86ISD::Wrapper;
8142   CodeModel::Model M = getTargetMachine().getCodeModel();
8143
8144   if (Subtarget->isPICStyleRIPRel() &&
8145       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8146     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8147       OpFlag = X86II::MO_GOTPCREL;
8148     WrapperKind = X86ISD::WrapperRIP;
8149   } else if (Subtarget->isPICStyleGOT()) {
8150     OpFlag = X86II::MO_GOT;
8151   } else if (Subtarget->isPICStyleStubPIC()) {
8152     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8153   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8154     OpFlag = X86II::MO_DARWIN_NONLAZY;
8155   }
8156
8157   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8158
8159   SDLoc DL(Op);
8160   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8161
8162   // With PIC, the address is actually $g + Offset.
8163   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8164       !Subtarget->is64Bit()) {
8165     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8166                          DAG.getNode(X86ISD::GlobalBaseReg,
8167                                      SDLoc(), getPointerTy()),
8168                          Result);
8169   }
8170
8171   // For symbols that require a load from a stub to get the address, emit the
8172   // load.
8173   if (isGlobalStubReference(OpFlag))
8174     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8175                          MachinePointerInfo::getGOT(), false, false, false, 0);
8176
8177   return Result;
8178 }
8179
8180 SDValue
8181 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8182   // Create the TargetBlockAddressAddress node.
8183   unsigned char OpFlags =
8184     Subtarget->ClassifyBlockAddressReference();
8185   CodeModel::Model M = getTargetMachine().getCodeModel();
8186   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8187   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8188   SDLoc dl(Op);
8189   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8190                                              OpFlags);
8191
8192   if (Subtarget->isPICStyleRIPRel() &&
8193       (M == CodeModel::Small || M == CodeModel::Kernel))
8194     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8195   else
8196     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8197
8198   // With PIC, the address is actually $g + Offset.
8199   if (isGlobalRelativeToPICBase(OpFlags)) {
8200     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8201                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8202                          Result);
8203   }
8204
8205   return Result;
8206 }
8207
8208 SDValue
8209 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8210                                       int64_t Offset, SelectionDAG &DAG) const {
8211   // Create the TargetGlobalAddress node, folding in the constant
8212   // offset if it is legal.
8213   unsigned char OpFlags =
8214     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8215   CodeModel::Model M = getTargetMachine().getCodeModel();
8216   SDValue Result;
8217   if (OpFlags == X86II::MO_NO_FLAG &&
8218       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8219     // A direct static reference to a global.
8220     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8221     Offset = 0;
8222   } else {
8223     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8224   }
8225
8226   if (Subtarget->isPICStyleRIPRel() &&
8227       (M == CodeModel::Small || M == CodeModel::Kernel))
8228     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8229   else
8230     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8231
8232   // With PIC, the address is actually $g + Offset.
8233   if (isGlobalRelativeToPICBase(OpFlags)) {
8234     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8235                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8236                          Result);
8237   }
8238
8239   // For globals that require a load from a stub to get the address, emit the
8240   // load.
8241   if (isGlobalStubReference(OpFlags))
8242     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8243                          MachinePointerInfo::getGOT(), false, false, false, 0);
8244
8245   // If there was a non-zero offset that we didn't fold, create an explicit
8246   // addition for it.
8247   if (Offset != 0)
8248     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8249                          DAG.getConstant(Offset, getPointerTy()));
8250
8251   return Result;
8252 }
8253
8254 SDValue
8255 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8256   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8257   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8258   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8259 }
8260
8261 static SDValue
8262 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8263            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8264            unsigned char OperandFlags, bool LocalDynamic = false) {
8265   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8266   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8267   SDLoc dl(GA);
8268   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8269                                            GA->getValueType(0),
8270                                            GA->getOffset(),
8271                                            OperandFlags);
8272
8273   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8274                                            : X86ISD::TLSADDR;
8275
8276   if (InFlag) {
8277     SDValue Ops[] = { Chain,  TGA, *InFlag };
8278     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8279   } else {
8280     SDValue Ops[]  = { Chain, TGA };
8281     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8282   }
8283
8284   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8285   MFI->setAdjustsStack(true);
8286
8287   SDValue Flag = Chain.getValue(1);
8288   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8289 }
8290
8291 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8292 static SDValue
8293 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8294                                 const EVT PtrVT) {
8295   SDValue InFlag;
8296   SDLoc dl(GA);  // ? function entry point might be better
8297   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8298                                    DAG.getNode(X86ISD::GlobalBaseReg,
8299                                                SDLoc(), PtrVT), InFlag);
8300   InFlag = Chain.getValue(1);
8301
8302   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8303 }
8304
8305 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8306 static SDValue
8307 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8308                                 const EVT PtrVT) {
8309   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8310                     X86::RAX, X86II::MO_TLSGD);
8311 }
8312
8313 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8314                                            SelectionDAG &DAG,
8315                                            const EVT PtrVT,
8316                                            bool is64Bit) {
8317   SDLoc dl(GA);
8318
8319   // Get the start address of the TLS block for this module.
8320   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8321       .getInfo<X86MachineFunctionInfo>();
8322   MFI->incNumLocalDynamicTLSAccesses();
8323
8324   SDValue Base;
8325   if (is64Bit) {
8326     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8327                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8328   } else {
8329     SDValue InFlag;
8330     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8331         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8332     InFlag = Chain.getValue(1);
8333     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8334                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8335   }
8336
8337   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8338   // of Base.
8339
8340   // Build x@dtpoff.
8341   unsigned char OperandFlags = X86II::MO_DTPOFF;
8342   unsigned WrapperKind = X86ISD::Wrapper;
8343   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8344                                            GA->getValueType(0),
8345                                            GA->getOffset(), OperandFlags);
8346   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8347
8348   // Add x@dtpoff with the base.
8349   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8350 }
8351
8352 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8353 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8354                                    const EVT PtrVT, TLSModel::Model model,
8355                                    bool is64Bit, bool isPIC) {
8356   SDLoc dl(GA);
8357
8358   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8359   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8360                                                          is64Bit ? 257 : 256));
8361
8362   SDValue ThreadPointer =
8363       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8364                   MachinePointerInfo(Ptr), false, false, false, 0);
8365
8366   unsigned char OperandFlags = 0;
8367   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8368   // initialexec.
8369   unsigned WrapperKind = X86ISD::Wrapper;
8370   if (model == TLSModel::LocalExec) {
8371     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8372   } else if (model == TLSModel::InitialExec) {
8373     if (is64Bit) {
8374       OperandFlags = X86II::MO_GOTTPOFF;
8375       WrapperKind = X86ISD::WrapperRIP;
8376     } else {
8377       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8378     }
8379   } else {
8380     llvm_unreachable("Unexpected model");
8381   }
8382
8383   // emit "addl x@ntpoff,%eax" (local exec)
8384   // or "addl x@indntpoff,%eax" (initial exec)
8385   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8386   SDValue TGA =
8387       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8388                                  GA->getOffset(), OperandFlags);
8389   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8390
8391   if (model == TLSModel::InitialExec) {
8392     if (isPIC && !is64Bit) {
8393       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8394                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8395                            Offset);
8396     }
8397
8398     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8399                          MachinePointerInfo::getGOT(), false, false, false, 0);
8400   }
8401
8402   // The address of the thread local variable is the add of the thread
8403   // pointer with the offset of the variable.
8404   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8405 }
8406
8407 SDValue
8408 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8409
8410   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8411   const GlobalValue *GV = GA->getGlobal();
8412
8413   if (Subtarget->isTargetELF()) {
8414     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8415
8416     switch (model) {
8417       case TLSModel::GeneralDynamic:
8418         if (Subtarget->is64Bit())
8419           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8420         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8421       case TLSModel::LocalDynamic:
8422         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8423                                            Subtarget->is64Bit());
8424       case TLSModel::InitialExec:
8425       case TLSModel::LocalExec:
8426         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8427                                    Subtarget->is64Bit(),
8428                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8429     }
8430     llvm_unreachable("Unknown TLS model.");
8431   }
8432
8433   if (Subtarget->isTargetDarwin()) {
8434     // Darwin only has one model of TLS.  Lower to that.
8435     unsigned char OpFlag = 0;
8436     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8437                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8438
8439     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8440     // global base reg.
8441     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8442                   !Subtarget->is64Bit();
8443     if (PIC32)
8444       OpFlag = X86II::MO_TLVP_PIC_BASE;
8445     else
8446       OpFlag = X86II::MO_TLVP;
8447     SDLoc DL(Op);
8448     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8449                                                 GA->getValueType(0),
8450                                                 GA->getOffset(), OpFlag);
8451     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8452
8453     // With PIC32, the address is actually $g + Offset.
8454     if (PIC32)
8455       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8456                            DAG.getNode(X86ISD::GlobalBaseReg,
8457                                        SDLoc(), getPointerTy()),
8458                            Offset);
8459
8460     // Lowering the machine isd will make sure everything is in the right
8461     // location.
8462     SDValue Chain = DAG.getEntryNode();
8463     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8464     SDValue Args[] = { Chain, Offset };
8465     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8466
8467     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8468     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8469     MFI->setAdjustsStack(true);
8470
8471     // And our return value (tls address) is in the standard call return value
8472     // location.
8473     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8474     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8475                               Chain.getValue(1));
8476   }
8477
8478   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8479     // Just use the implicit TLS architecture
8480     // Need to generate someting similar to:
8481     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8482     //                                  ; from TEB
8483     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8484     //   mov     rcx, qword [rdx+rcx*8]
8485     //   mov     eax, .tls$:tlsvar
8486     //   [rax+rcx] contains the address
8487     // Windows 64bit: gs:0x58
8488     // Windows 32bit: fs:__tls_array
8489
8490     // If GV is an alias then use the aliasee for determining
8491     // thread-localness.
8492     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8493       GV = GA->resolveAliasedGlobal(false);
8494     SDLoc dl(GA);
8495     SDValue Chain = DAG.getEntryNode();
8496
8497     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8498     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8499     // use its literal value of 0x2C.
8500     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8501                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8502                                                              256)
8503                                         : Type::getInt32PtrTy(*DAG.getContext(),
8504                                                               257));
8505
8506     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8507       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8508         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8509
8510     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8511                                         MachinePointerInfo(Ptr),
8512                                         false, false, false, 0);
8513
8514     // Load the _tls_index variable
8515     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8516     if (Subtarget->is64Bit())
8517       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8518                            IDX, MachinePointerInfo(), MVT::i32,
8519                            false, false, 0);
8520     else
8521       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8522                         false, false, false, 0);
8523
8524     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8525                                     getPointerTy());
8526     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8527
8528     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8529     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8530                       false, false, false, 0);
8531
8532     // Get the offset of start of .tls section
8533     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8534                                              GA->getValueType(0),
8535                                              GA->getOffset(), X86II::MO_SECREL);
8536     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8537
8538     // The address of the thread local variable is the add of the thread
8539     // pointer with the offset of the variable.
8540     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8541   }
8542
8543   llvm_unreachable("TLS not implemented for this target.");
8544 }
8545
8546 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8547 /// and take a 2 x i32 value to shift plus a shift amount.
8548 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8549   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8550   MVT VT = Op.getSimpleValueType();
8551   unsigned VTBits = VT.getSizeInBits();
8552   SDLoc dl(Op);
8553   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8554   SDValue ShOpLo = Op.getOperand(0);
8555   SDValue ShOpHi = Op.getOperand(1);
8556   SDValue ShAmt  = Op.getOperand(2);
8557   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8558   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8559   // during isel.
8560   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8561                                   DAG.getConstant(VTBits - 1, MVT::i8));
8562   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8563                                      DAG.getConstant(VTBits - 1, MVT::i8))
8564                        : DAG.getConstant(0, VT);
8565
8566   SDValue Tmp2, Tmp3;
8567   if (Op.getOpcode() == ISD::SHL_PARTS) {
8568     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8569     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8570   } else {
8571     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8572     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8573   }
8574
8575   // If the shift amount is larger or equal than the width of a part we can't
8576   // rely on the results of shld/shrd. Insert a test and select the appropriate
8577   // values for large shift amounts.
8578   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8579                                 DAG.getConstant(VTBits, MVT::i8));
8580   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8581                              AndNode, DAG.getConstant(0, MVT::i8));
8582
8583   SDValue Hi, Lo;
8584   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8585   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8586   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8587
8588   if (Op.getOpcode() == ISD::SHL_PARTS) {
8589     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8590     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8591   } else {
8592     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8593     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8594   }
8595
8596   SDValue Ops[2] = { Lo, Hi };
8597   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8598 }
8599
8600 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8601                                            SelectionDAG &DAG) const {
8602   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8603
8604   if (SrcVT.isVector())
8605     return SDValue();
8606
8607   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8608          "Unknown SINT_TO_FP to lower!");
8609
8610   // These are really Legal; return the operand so the caller accepts it as
8611   // Legal.
8612   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8613     return Op;
8614   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8615       Subtarget->is64Bit()) {
8616     return Op;
8617   }
8618
8619   SDLoc dl(Op);
8620   unsigned Size = SrcVT.getSizeInBits()/8;
8621   MachineFunction &MF = DAG.getMachineFunction();
8622   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8623   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8624   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8625                                StackSlot,
8626                                MachinePointerInfo::getFixedStack(SSFI),
8627                                false, false, 0);
8628   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8629 }
8630
8631 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8632                                      SDValue StackSlot,
8633                                      SelectionDAG &DAG) const {
8634   // Build the FILD
8635   SDLoc DL(Op);
8636   SDVTList Tys;
8637   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8638   if (useSSE)
8639     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8640   else
8641     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8642
8643   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8644
8645   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8646   MachineMemOperand *MMO;
8647   if (FI) {
8648     int SSFI = FI->getIndex();
8649     MMO =
8650       DAG.getMachineFunction()
8651       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8652                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8653   } else {
8654     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8655     StackSlot = StackSlot.getOperand(1);
8656   }
8657   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8658   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8659                                            X86ISD::FILD, DL,
8660                                            Tys, Ops, array_lengthof(Ops),
8661                                            SrcVT, MMO);
8662
8663   if (useSSE) {
8664     Chain = Result.getValue(1);
8665     SDValue InFlag = Result.getValue(2);
8666
8667     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8668     // shouldn't be necessary except that RFP cannot be live across
8669     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8670     MachineFunction &MF = DAG.getMachineFunction();
8671     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8672     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8673     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8674     Tys = DAG.getVTList(MVT::Other);
8675     SDValue Ops[] = {
8676       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8677     };
8678     MachineMemOperand *MMO =
8679       DAG.getMachineFunction()
8680       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8681                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8682
8683     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8684                                     Ops, array_lengthof(Ops),
8685                                     Op.getValueType(), MMO);
8686     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8687                          MachinePointerInfo::getFixedStack(SSFI),
8688                          false, false, false, 0);
8689   }
8690
8691   return Result;
8692 }
8693
8694 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8695 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8696                                                SelectionDAG &DAG) const {
8697   // This algorithm is not obvious. Here it is what we're trying to output:
8698   /*
8699      movq       %rax,  %xmm0
8700      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8701      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8702      #ifdef __SSE3__
8703        haddpd   %xmm0, %xmm0
8704      #else
8705        pshufd   $0x4e, %xmm0, %xmm1
8706        addpd    %xmm1, %xmm0
8707      #endif
8708   */
8709
8710   SDLoc dl(Op);
8711   LLVMContext *Context = DAG.getContext();
8712
8713   // Build some magic constants.
8714   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8715   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8716   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8717
8718   SmallVector<Constant*,2> CV1;
8719   CV1.push_back(
8720     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8721                                       APInt(64, 0x4330000000000000ULL))));
8722   CV1.push_back(
8723     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8724                                       APInt(64, 0x4530000000000000ULL))));
8725   Constant *C1 = ConstantVector::get(CV1);
8726   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8727
8728   // Load the 64-bit value into an XMM register.
8729   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8730                             Op.getOperand(0));
8731   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8732                               MachinePointerInfo::getConstantPool(),
8733                               false, false, false, 16);
8734   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8735                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8736                               CLod0);
8737
8738   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8739                               MachinePointerInfo::getConstantPool(),
8740                               false, false, false, 16);
8741   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8742   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8743   SDValue Result;
8744
8745   if (Subtarget->hasSSE3()) {
8746     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8747     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8748   } else {
8749     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8750     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8751                                            S2F, 0x4E, DAG);
8752     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8753                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8754                          Sub);
8755   }
8756
8757   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8758                      DAG.getIntPtrConstant(0));
8759 }
8760
8761 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8762 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8763                                                SelectionDAG &DAG) const {
8764   SDLoc dl(Op);
8765   // FP constant to bias correct the final result.
8766   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8767                                    MVT::f64);
8768
8769   // Load the 32-bit value into an XMM register.
8770   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8771                              Op.getOperand(0));
8772
8773   // Zero out the upper parts of the register.
8774   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8775
8776   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8777                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8778                      DAG.getIntPtrConstant(0));
8779
8780   // Or the load with the bias.
8781   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8782                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8783                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8784                                                    MVT::v2f64, Load)),
8785                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8786                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8787                                                    MVT::v2f64, Bias)));
8788   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8789                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8790                    DAG.getIntPtrConstant(0));
8791
8792   // Subtract the bias.
8793   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8794
8795   // Handle final rounding.
8796   EVT DestVT = Op.getValueType();
8797
8798   if (DestVT.bitsLT(MVT::f64))
8799     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8800                        DAG.getIntPtrConstant(0));
8801   if (DestVT.bitsGT(MVT::f64))
8802     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8803
8804   // Handle final rounding.
8805   return Sub;
8806 }
8807
8808 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8809                                                SelectionDAG &DAG) const {
8810   SDValue N0 = Op.getOperand(0);
8811   MVT SVT = N0.getSimpleValueType();
8812   SDLoc dl(Op);
8813
8814   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8815           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8816          "Custom UINT_TO_FP is not supported!");
8817
8818   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8819   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8820                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8821 }
8822
8823 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8824                                            SelectionDAG &DAG) const {
8825   SDValue N0 = Op.getOperand(0);
8826   SDLoc dl(Op);
8827
8828   if (Op.getValueType().isVector())
8829     return lowerUINT_TO_FP_vec(Op, DAG);
8830
8831   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8832   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8833   // the optimization here.
8834   if (DAG.SignBitIsZero(N0))
8835     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8836
8837   MVT SrcVT = N0.getSimpleValueType();
8838   MVT DstVT = Op.getSimpleValueType();
8839   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8840     return LowerUINT_TO_FP_i64(Op, DAG);
8841   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8842     return LowerUINT_TO_FP_i32(Op, DAG);
8843   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8844     return SDValue();
8845
8846   // Make a 64-bit buffer, and use it to build an FILD.
8847   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8848   if (SrcVT == MVT::i32) {
8849     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8850     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8851                                      getPointerTy(), StackSlot, WordOff);
8852     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8853                                   StackSlot, MachinePointerInfo(),
8854                                   false, false, 0);
8855     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8856                                   OffsetSlot, MachinePointerInfo(),
8857                                   false, false, 0);
8858     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8859     return Fild;
8860   }
8861
8862   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8863   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8864                                StackSlot, MachinePointerInfo(),
8865                                false, false, 0);
8866   // For i64 source, we need to add the appropriate power of 2 if the input
8867   // was negative.  This is the same as the optimization in
8868   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8869   // we must be careful to do the computation in x87 extended precision, not
8870   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8871   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8872   MachineMemOperand *MMO =
8873     DAG.getMachineFunction()
8874     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8875                           MachineMemOperand::MOLoad, 8, 8);
8876
8877   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8878   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8879   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8880                                          array_lengthof(Ops), MVT::i64, MMO);
8881
8882   APInt FF(32, 0x5F800000ULL);
8883
8884   // Check whether the sign bit is set.
8885   SDValue SignSet = DAG.getSetCC(dl,
8886                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8887                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8888                                  ISD::SETLT);
8889
8890   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8891   SDValue FudgePtr = DAG.getConstantPool(
8892                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8893                                          getPointerTy());
8894
8895   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8896   SDValue Zero = DAG.getIntPtrConstant(0);
8897   SDValue Four = DAG.getIntPtrConstant(4);
8898   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8899                                Zero, Four);
8900   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8901
8902   // Load the value out, extending it from f32 to f80.
8903   // FIXME: Avoid the extend by constructing the right constant pool?
8904   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8905                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8906                                  MVT::f32, false, false, 4);
8907   // Extend everything to 80 bits to force it to be done on x87.
8908   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8909   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8910 }
8911
8912 std::pair<SDValue,SDValue>
8913 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8914                                     bool IsSigned, bool IsReplace) const {
8915   SDLoc DL(Op);
8916
8917   EVT DstTy = Op.getValueType();
8918
8919   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8920     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8921     DstTy = MVT::i64;
8922   }
8923
8924   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8925          DstTy.getSimpleVT() >= MVT::i16 &&
8926          "Unknown FP_TO_INT to lower!");
8927
8928   // These are really Legal.
8929   if (DstTy == MVT::i32 &&
8930       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8931     return std::make_pair(SDValue(), SDValue());
8932   if (Subtarget->is64Bit() &&
8933       DstTy == MVT::i64 &&
8934       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8935     return std::make_pair(SDValue(), SDValue());
8936
8937   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8938   // stack slot, or into the FTOL runtime function.
8939   MachineFunction &MF = DAG.getMachineFunction();
8940   unsigned MemSize = DstTy.getSizeInBits()/8;
8941   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8942   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8943
8944   unsigned Opc;
8945   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8946     Opc = X86ISD::WIN_FTOL;
8947   else
8948     switch (DstTy.getSimpleVT().SimpleTy) {
8949     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8950     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8951     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8952     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8953     }
8954
8955   SDValue Chain = DAG.getEntryNode();
8956   SDValue Value = Op.getOperand(0);
8957   EVT TheVT = Op.getOperand(0).getValueType();
8958   // FIXME This causes a redundant load/store if the SSE-class value is already
8959   // in memory, such as if it is on the callstack.
8960   if (isScalarFPTypeInSSEReg(TheVT)) {
8961     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8962     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8963                          MachinePointerInfo::getFixedStack(SSFI),
8964                          false, false, 0);
8965     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8966     SDValue Ops[] = {
8967       Chain, StackSlot, DAG.getValueType(TheVT)
8968     };
8969
8970     MachineMemOperand *MMO =
8971       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8972                               MachineMemOperand::MOLoad, MemSize, MemSize);
8973     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8974                                     array_lengthof(Ops), DstTy, MMO);
8975     Chain = Value.getValue(1);
8976     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8977     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8978   }
8979
8980   MachineMemOperand *MMO =
8981     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8982                             MachineMemOperand::MOStore, MemSize, MemSize);
8983
8984   if (Opc != X86ISD::WIN_FTOL) {
8985     // Build the FP_TO_INT*_IN_MEM
8986     SDValue Ops[] = { Chain, Value, StackSlot };
8987     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8988                                            Ops, array_lengthof(Ops), DstTy,
8989                                            MMO);
8990     return std::make_pair(FIST, StackSlot);
8991   } else {
8992     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8993       DAG.getVTList(MVT::Other, MVT::Glue),
8994       Chain, Value);
8995     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8996       MVT::i32, ftol.getValue(1));
8997     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8998       MVT::i32, eax.getValue(2));
8999     SDValue Ops[] = { eax, edx };
9000     SDValue pair = IsReplace
9001       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9002       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9003     return std::make_pair(pair, SDValue());
9004   }
9005 }
9006
9007 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9008                               const X86Subtarget *Subtarget) {
9009   MVT VT = Op->getSimpleValueType(0);
9010   SDValue In = Op->getOperand(0);
9011   MVT InVT = In.getSimpleValueType();
9012   SDLoc dl(Op);
9013
9014   // Optimize vectors in AVX mode:
9015   //
9016   //   v8i16 -> v8i32
9017   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9018   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9019   //   Concat upper and lower parts.
9020   //
9021   //   v4i32 -> v4i64
9022   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9023   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9024   //   Concat upper and lower parts.
9025   //
9026
9027   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9028       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9029       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9030     return SDValue();
9031
9032   if (Subtarget->hasInt256())
9033     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
9034
9035   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9036   SDValue Undef = DAG.getUNDEF(InVT);
9037   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9038   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9039   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9040
9041   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9042                              VT.getVectorNumElements()/2);
9043
9044   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9045   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9046
9047   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9048 }
9049
9050 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9051                                         SelectionDAG &DAG) {
9052   MVT VT = Op->getSimpleValueType(0);
9053   SDValue In = Op->getOperand(0);
9054   MVT InVT = In.getSimpleValueType();
9055   SDLoc DL(Op);
9056   unsigned int NumElts = VT.getVectorNumElements();
9057   if (NumElts != 8 && NumElts != 16)
9058     return SDValue();
9059
9060   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9061     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9062
9063   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9065   // Now we have only mask extension
9066   assert(InVT.getVectorElementType() == MVT::i1);
9067   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9068   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9069   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9070   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9071   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9072                            MachinePointerInfo::getConstantPool(),
9073                            false, false, false, Alignment);
9074
9075   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9076   if (VT.is512BitVector())
9077     return Brcst;
9078   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9079 }
9080
9081 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9082                                SelectionDAG &DAG) {
9083   if (Subtarget->hasFp256()) {
9084     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9085     if (Res.getNode())
9086       return Res;
9087   }
9088
9089   return SDValue();
9090 }
9091
9092 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9093                                 SelectionDAG &DAG) {
9094   SDLoc DL(Op);
9095   MVT VT = Op.getSimpleValueType();
9096   SDValue In = Op.getOperand(0);
9097   MVT SVT = In.getSimpleValueType();
9098
9099   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9100     return LowerZERO_EXTEND_AVX512(Op, DAG);
9101
9102   if (Subtarget->hasFp256()) {
9103     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9104     if (Res.getNode())
9105       return Res;
9106   }
9107
9108   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9109          VT.getVectorNumElements() != SVT.getVectorNumElements());
9110   return SDValue();
9111 }
9112
9113 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9114   SDLoc DL(Op);
9115   MVT VT = Op.getSimpleValueType();
9116   SDValue In = Op.getOperand(0);
9117   MVT InVT = In.getSimpleValueType();
9118
9119   if (VT == MVT::i1) {
9120     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9121            "Invalid scalar TRUNCATE operation");
9122     if (InVT == MVT::i32)
9123       return SDValue();
9124     if (InVT.getSizeInBits() == 64)
9125       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9126     else if (InVT.getSizeInBits() < 32)
9127       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9128     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9129   }
9130   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9131          "Invalid TRUNCATE operation");
9132
9133   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9134     if (VT.getVectorElementType().getSizeInBits() >=8)
9135       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9136
9137     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9138     unsigned NumElts = InVT.getVectorNumElements();
9139     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9140     if (InVT.getSizeInBits() < 512) {
9141       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9142       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9143       InVT = ExtVT;
9144     }
9145     
9146     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9147     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9148     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9149     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9150     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9151                            MachinePointerInfo::getConstantPool(),
9152                            false, false, false, Alignment);
9153     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9154     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9155     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9156   }
9157
9158   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9159     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9160     if (Subtarget->hasInt256()) {
9161       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9162       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9163       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9164                                 ShufMask);
9165       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9166                          DAG.getIntPtrConstant(0));
9167     }
9168
9169     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
9170     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9171                                DAG.getIntPtrConstant(0));
9172     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9173                                DAG.getIntPtrConstant(2));
9174
9175     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9176     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9177
9178     // The PSHUFD mask:
9179     static const int ShufMask1[] = {0, 2, 0, 0};
9180     SDValue Undef = DAG.getUNDEF(VT);
9181     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
9182     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
9183
9184     // The MOVLHPS mask:
9185     static const int ShufMask2[] = {0, 1, 4, 5};
9186     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
9187   }
9188
9189   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9190     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9191     if (Subtarget->hasInt256()) {
9192       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9193
9194       SmallVector<SDValue,32> pshufbMask;
9195       for (unsigned i = 0; i < 2; ++i) {
9196         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9197         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9198         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9199         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9200         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9201         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9202         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9203         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9204         for (unsigned j = 0; j < 8; ++j)
9205           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9206       }
9207       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9208                                &pshufbMask[0], 32);
9209       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9210       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9211
9212       static const int ShufMask[] = {0,  2,  -1,  -1};
9213       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9214                                 &ShufMask[0]);
9215       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9216                        DAG.getIntPtrConstant(0));
9217       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9218     }
9219
9220     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9221                                DAG.getIntPtrConstant(0));
9222
9223     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9224                                DAG.getIntPtrConstant(4));
9225
9226     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9227     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9228
9229     // The PSHUFB mask:
9230     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9231                                    -1, -1, -1, -1, -1, -1, -1, -1};
9232
9233     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9234     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9235     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9236
9237     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9238     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9239
9240     // The MOVLHPS Mask:
9241     static const int ShufMask2[] = {0, 1, 4, 5};
9242     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9243     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9244   }
9245
9246   // Handle truncation of V256 to V128 using shuffles.
9247   if (!VT.is128BitVector() || !InVT.is256BitVector())
9248     return SDValue();
9249
9250   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9251
9252   unsigned NumElems = VT.getVectorNumElements();
9253   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9254
9255   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9256   // Prepare truncation shuffle mask
9257   for (unsigned i = 0; i != NumElems; ++i)
9258     MaskVec[i] = i * 2;
9259   SDValue V = DAG.getVectorShuffle(NVT, DL,
9260                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9261                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9262   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9263                      DAG.getIntPtrConstant(0));
9264 }
9265
9266 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9267                                            SelectionDAG &DAG) const {
9268   MVT VT = Op.getSimpleValueType();
9269   if (VT.isVector()) {
9270     if (VT == MVT::v8i16)
9271       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9272                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9273                                      MVT::v8i32, Op.getOperand(0)));
9274     return SDValue();
9275   }
9276
9277   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9278     /*IsSigned=*/ true, /*IsReplace=*/ false);
9279   SDValue FIST = Vals.first, StackSlot = Vals.second;
9280   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9281   if (FIST.getNode() == 0) return Op;
9282
9283   if (StackSlot.getNode())
9284     // Load the result.
9285     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9286                        FIST, StackSlot, MachinePointerInfo(),
9287                        false, false, false, 0);
9288
9289   // The node is the result.
9290   return FIST;
9291 }
9292
9293 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9294                                            SelectionDAG &DAG) const {
9295   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9296     /*IsSigned=*/ false, /*IsReplace=*/ false);
9297   SDValue FIST = Vals.first, StackSlot = Vals.second;
9298   assert(FIST.getNode() && "Unexpected failure");
9299
9300   if (StackSlot.getNode())
9301     // Load the result.
9302     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9303                        FIST, StackSlot, MachinePointerInfo(),
9304                        false, false, false, 0);
9305
9306   // The node is the result.
9307   return FIST;
9308 }
9309
9310 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9311   SDLoc DL(Op);
9312   MVT VT = Op.getSimpleValueType();
9313   SDValue In = Op.getOperand(0);
9314   MVT SVT = In.getSimpleValueType();
9315
9316   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9317
9318   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9319                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9320                                  In, DAG.getUNDEF(SVT)));
9321 }
9322
9323 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9324   LLVMContext *Context = DAG.getContext();
9325   SDLoc dl(Op);
9326   MVT VT = Op.getSimpleValueType();
9327   MVT EltVT = VT;
9328   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9329   if (VT.isVector()) {
9330     EltVT = VT.getVectorElementType();
9331     NumElts = VT.getVectorNumElements();
9332   }
9333   Constant *C;
9334   if (EltVT == MVT::f64)
9335     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9336                                           APInt(64, ~(1ULL << 63))));
9337   else
9338     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9339                                           APInt(32, ~(1U << 31))));
9340   C = ConstantVector::getSplat(NumElts, C);
9341   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9342   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9343   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9344   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9345                              MachinePointerInfo::getConstantPool(),
9346                              false, false, false, Alignment);
9347   if (VT.isVector()) {
9348     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9349     return DAG.getNode(ISD::BITCAST, dl, VT,
9350                        DAG.getNode(ISD::AND, dl, ANDVT,
9351                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9352                                                Op.getOperand(0)),
9353                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9354   }
9355   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9356 }
9357
9358 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9359   LLVMContext *Context = DAG.getContext();
9360   SDLoc dl(Op);
9361   MVT VT = Op.getSimpleValueType();
9362   MVT EltVT = VT;
9363   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9364   if (VT.isVector()) {
9365     EltVT = VT.getVectorElementType();
9366     NumElts = VT.getVectorNumElements();
9367   }
9368   Constant *C;
9369   if (EltVT == MVT::f64)
9370     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9371                                           APInt(64, 1ULL << 63)));
9372   else
9373     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9374                                           APInt(32, 1U << 31)));
9375   C = ConstantVector::getSplat(NumElts, C);
9376   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9377   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9378   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9379   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9380                              MachinePointerInfo::getConstantPool(),
9381                              false, false, false, Alignment);
9382   if (VT.isVector()) {
9383     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9384     return DAG.getNode(ISD::BITCAST, dl, VT,
9385                        DAG.getNode(ISD::XOR, dl, XORVT,
9386                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9387                                                Op.getOperand(0)),
9388                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9389   }
9390
9391   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9392 }
9393
9394 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9396   LLVMContext *Context = DAG.getContext();
9397   SDValue Op0 = Op.getOperand(0);
9398   SDValue Op1 = Op.getOperand(1);
9399   SDLoc dl(Op);
9400   MVT VT = Op.getSimpleValueType();
9401   MVT SrcVT = Op1.getSimpleValueType();
9402
9403   // If second operand is smaller, extend it first.
9404   if (SrcVT.bitsLT(VT)) {
9405     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9406     SrcVT = VT;
9407   }
9408   // And if it is bigger, shrink it first.
9409   if (SrcVT.bitsGT(VT)) {
9410     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9411     SrcVT = VT;
9412   }
9413
9414   // At this point the operands and the result should have the same
9415   // type, and that won't be f80 since that is not custom lowered.
9416
9417   // First get the sign bit of second operand.
9418   SmallVector<Constant*,4> CV;
9419   if (SrcVT == MVT::f64) {
9420     const fltSemantics &Sem = APFloat::IEEEdouble;
9421     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9422     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9423   } else {
9424     const fltSemantics &Sem = APFloat::IEEEsingle;
9425     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9426     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9427     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9428     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9429   }
9430   Constant *C = ConstantVector::get(CV);
9431   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9432   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9433                               MachinePointerInfo::getConstantPool(),
9434                               false, false, false, 16);
9435   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9436
9437   // Shift sign bit right or left if the two operands have different types.
9438   if (SrcVT.bitsGT(VT)) {
9439     // Op0 is MVT::f32, Op1 is MVT::f64.
9440     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9441     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9442                           DAG.getConstant(32, MVT::i32));
9443     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9444     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9445                           DAG.getIntPtrConstant(0));
9446   }
9447
9448   // Clear first operand sign bit.
9449   CV.clear();
9450   if (VT == MVT::f64) {
9451     const fltSemantics &Sem = APFloat::IEEEdouble;
9452     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9453                                                    APInt(64, ~(1ULL << 63)))));
9454     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9455   } else {
9456     const fltSemantics &Sem = APFloat::IEEEsingle;
9457     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9458                                                    APInt(32, ~(1U << 31)))));
9459     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9460     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9461     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9462   }
9463   C = ConstantVector::get(CV);
9464   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9465   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9466                               MachinePointerInfo::getConstantPool(),
9467                               false, false, false, 16);
9468   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9469
9470   // Or the value with the sign bit.
9471   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9472 }
9473
9474 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9475   SDValue N0 = Op.getOperand(0);
9476   SDLoc dl(Op);
9477   MVT VT = Op.getSimpleValueType();
9478
9479   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9480   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9481                                   DAG.getConstant(1, VT));
9482   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9483 }
9484
9485 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9486 //
9487 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9488                                       SelectionDAG &DAG) {
9489   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9490
9491   if (!Subtarget->hasSSE41())
9492     return SDValue();
9493
9494   if (!Op->hasOneUse())
9495     return SDValue();
9496
9497   SDNode *N = Op.getNode();
9498   SDLoc DL(N);
9499
9500   SmallVector<SDValue, 8> Opnds;
9501   DenseMap<SDValue, unsigned> VecInMap;
9502   EVT VT = MVT::Other;
9503
9504   // Recognize a special case where a vector is casted into wide integer to
9505   // test all 0s.
9506   Opnds.push_back(N->getOperand(0));
9507   Opnds.push_back(N->getOperand(1));
9508
9509   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9510     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9511     // BFS traverse all OR'd operands.
9512     if (I->getOpcode() == ISD::OR) {
9513       Opnds.push_back(I->getOperand(0));
9514       Opnds.push_back(I->getOperand(1));
9515       // Re-evaluate the number of nodes to be traversed.
9516       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9517       continue;
9518     }
9519
9520     // Quit if a non-EXTRACT_VECTOR_ELT
9521     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9522       return SDValue();
9523
9524     // Quit if without a constant index.
9525     SDValue Idx = I->getOperand(1);
9526     if (!isa<ConstantSDNode>(Idx))
9527       return SDValue();
9528
9529     SDValue ExtractedFromVec = I->getOperand(0);
9530     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9531     if (M == VecInMap.end()) {
9532       VT = ExtractedFromVec.getValueType();
9533       // Quit if not 128/256-bit vector.
9534       if (!VT.is128BitVector() && !VT.is256BitVector())
9535         return SDValue();
9536       // Quit if not the same type.
9537       if (VecInMap.begin() != VecInMap.end() &&
9538           VT != VecInMap.begin()->first.getValueType())
9539         return SDValue();
9540       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9541     }
9542     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9543   }
9544
9545   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9546          "Not extracted from 128-/256-bit vector.");
9547
9548   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9549   SmallVector<SDValue, 8> VecIns;
9550
9551   for (DenseMap<SDValue, unsigned>::const_iterator
9552         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9553     // Quit if not all elements are used.
9554     if (I->second != FullMask)
9555       return SDValue();
9556     VecIns.push_back(I->first);
9557   }
9558
9559   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9560
9561   // Cast all vectors into TestVT for PTEST.
9562   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9563     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9564
9565   // If more than one full vectors are evaluated, OR them first before PTEST.
9566   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9567     // Each iteration will OR 2 nodes and append the result until there is only
9568     // 1 node left, i.e. the final OR'd value of all vectors.
9569     SDValue LHS = VecIns[Slot];
9570     SDValue RHS = VecIns[Slot + 1];
9571     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9572   }
9573
9574   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9575                      VecIns.back(), VecIns.back());
9576 }
9577
9578 /// Emit nodes that will be selected as "test Op0,Op0", or something
9579 /// equivalent.
9580 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9581                                     SelectionDAG &DAG) const {
9582   SDLoc dl(Op);
9583
9584   if (Op.getValueType() == MVT::i1)
9585     // KORTEST instruction should be selected
9586     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9587                        DAG.getConstant(0, Op.getValueType()));
9588
9589   // CF and OF aren't always set the way we want. Determine which
9590   // of these we need.
9591   bool NeedCF = false;
9592   bool NeedOF = false;
9593   switch (X86CC) {
9594   default: break;
9595   case X86::COND_A: case X86::COND_AE:
9596   case X86::COND_B: case X86::COND_BE:
9597     NeedCF = true;
9598     break;
9599   case X86::COND_G: case X86::COND_GE:
9600   case X86::COND_L: case X86::COND_LE:
9601   case X86::COND_O: case X86::COND_NO:
9602     NeedOF = true;
9603     break;
9604   }
9605   // See if we can use the EFLAGS value from the operand instead of
9606   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9607   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9608   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9609     // Emit a CMP with 0, which is the TEST pattern.
9610     //if (Op.getValueType() == MVT::i1)
9611     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9612     //                     DAG.getConstant(0, MVT::i1));
9613     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9614                        DAG.getConstant(0, Op.getValueType()));
9615   }
9616   unsigned Opcode = 0;
9617   unsigned NumOperands = 0;
9618
9619   // Truncate operations may prevent the merge of the SETCC instruction
9620   // and the arithmetic instruction before it. Attempt to truncate the operands
9621   // of the arithmetic instruction and use a reduced bit-width instruction.
9622   bool NeedTruncation = false;
9623   SDValue ArithOp = Op;
9624   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9625     SDValue Arith = Op->getOperand(0);
9626     // Both the trunc and the arithmetic op need to have one user each.
9627     if (Arith->hasOneUse())
9628       switch (Arith.getOpcode()) {
9629         default: break;
9630         case ISD::ADD:
9631         case ISD::SUB:
9632         case ISD::AND:
9633         case ISD::OR:
9634         case ISD::XOR: {
9635           NeedTruncation = true;
9636           ArithOp = Arith;
9637         }
9638       }
9639   }
9640
9641   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9642   // which may be the result of a CAST.  We use the variable 'Op', which is the
9643   // non-casted variable when we check for possible users.
9644   switch (ArithOp.getOpcode()) {
9645   case ISD::ADD:
9646     // Due to an isel shortcoming, be conservative if this add is likely to be
9647     // selected as part of a load-modify-store instruction. When the root node
9648     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9649     // uses of other nodes in the match, such as the ADD in this case. This
9650     // leads to the ADD being left around and reselected, with the result being
9651     // two adds in the output.  Alas, even if none our users are stores, that
9652     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9653     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9654     // climbing the DAG back to the root, and it doesn't seem to be worth the
9655     // effort.
9656     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9657          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9658       if (UI->getOpcode() != ISD::CopyToReg &&
9659           UI->getOpcode() != ISD::SETCC &&
9660           UI->getOpcode() != ISD::STORE)
9661         goto default_case;
9662
9663     if (ConstantSDNode *C =
9664         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9665       // An add of one will be selected as an INC.
9666       if (C->getAPIntValue() == 1) {
9667         Opcode = X86ISD::INC;
9668         NumOperands = 1;
9669         break;
9670       }
9671
9672       // An add of negative one (subtract of one) will be selected as a DEC.
9673       if (C->getAPIntValue().isAllOnesValue()) {
9674         Opcode = X86ISD::DEC;
9675         NumOperands = 1;
9676         break;
9677       }
9678     }
9679
9680     // Otherwise use a regular EFLAGS-setting add.
9681     Opcode = X86ISD::ADD;
9682     NumOperands = 2;
9683     break;
9684   case ISD::AND: {
9685     // If the primary and result isn't used, don't bother using X86ISD::AND,
9686     // because a TEST instruction will be better.
9687     bool NonFlagUse = false;
9688     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9689            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9690       SDNode *User = *UI;
9691       unsigned UOpNo = UI.getOperandNo();
9692       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9693         // Look pass truncate.
9694         UOpNo = User->use_begin().getOperandNo();
9695         User = *User->use_begin();
9696       }
9697
9698       if (User->getOpcode() != ISD::BRCOND &&
9699           User->getOpcode() != ISD::SETCC &&
9700           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9701         NonFlagUse = true;
9702         break;
9703       }
9704     }
9705
9706     if (!NonFlagUse)
9707       break;
9708   }
9709     // FALL THROUGH
9710   case ISD::SUB:
9711   case ISD::OR:
9712   case ISD::XOR:
9713     // Due to the ISEL shortcoming noted above, be conservative if this op is
9714     // likely to be selected as part of a load-modify-store instruction.
9715     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9716            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9717       if (UI->getOpcode() == ISD::STORE)
9718         goto default_case;
9719
9720     // Otherwise use a regular EFLAGS-setting instruction.
9721     switch (ArithOp.getOpcode()) {
9722     default: llvm_unreachable("unexpected operator!");
9723     case ISD::SUB: Opcode = X86ISD::SUB; break;
9724     case ISD::XOR: Opcode = X86ISD::XOR; break;
9725     case ISD::AND: Opcode = X86ISD::AND; break;
9726     case ISD::OR: {
9727       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9728         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9729         if (EFLAGS.getNode())
9730           return EFLAGS;
9731       }
9732       Opcode = X86ISD::OR;
9733       break;
9734     }
9735     }
9736
9737     NumOperands = 2;
9738     break;
9739   case X86ISD::ADD:
9740   case X86ISD::SUB:
9741   case X86ISD::INC:
9742   case X86ISD::DEC:
9743   case X86ISD::OR:
9744   case X86ISD::XOR:
9745   case X86ISD::AND:
9746     return SDValue(Op.getNode(), 1);
9747   default:
9748   default_case:
9749     break;
9750   }
9751
9752   // If we found that truncation is beneficial, perform the truncation and
9753   // update 'Op'.
9754   if (NeedTruncation) {
9755     EVT VT = Op.getValueType();
9756     SDValue WideVal = Op->getOperand(0);
9757     EVT WideVT = WideVal.getValueType();
9758     unsigned ConvertedOp = 0;
9759     // Use a target machine opcode to prevent further DAGCombine
9760     // optimizations that may separate the arithmetic operations
9761     // from the setcc node.
9762     switch (WideVal.getOpcode()) {
9763       default: break;
9764       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9765       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9766       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9767       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9768       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9769     }
9770
9771     if (ConvertedOp) {
9772       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9773       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9774         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9775         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9776         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9777       }
9778     }
9779   }
9780
9781   if (Opcode == 0)
9782     // Emit a CMP with 0, which is the TEST pattern.
9783     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9784                        DAG.getConstant(0, Op.getValueType()));
9785
9786   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9787   SmallVector<SDValue, 4> Ops;
9788   for (unsigned i = 0; i != NumOperands; ++i)
9789     Ops.push_back(Op.getOperand(i));
9790
9791   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9792   DAG.ReplaceAllUsesWith(Op, New);
9793   return SDValue(New.getNode(), 1);
9794 }
9795
9796 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9797 /// equivalent.
9798 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9799                                    SelectionDAG &DAG) const {
9800   SDLoc dl(Op0);
9801   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9802     if (C->getAPIntValue() == 0)
9803       return EmitTest(Op0, X86CC, DAG);
9804
9805      if (Op0.getValueType() == MVT::i1) {
9806        // invert the value
9807       Op0 = DAG.getNode(ISD::XOR, dl, MVT::i1, Op0,
9808                         DAG.getConstant(-1, MVT::i1));
9809       return EmitTest(Op0, X86CC, DAG);
9810      }
9811   }
9812  
9813   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9814        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9815     // Do the comparison at i32 if it's smaller. This avoids subregister
9816     // aliasing issues. Keep the smaller reference if we're optimizing for
9817     // size, however, as that'll allow better folding of memory operations.
9818     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9819         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9820              AttributeSet::FunctionIndex, Attribute::MinSize)) {
9821       unsigned ExtendOp =
9822           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9823       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9824       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9825     }
9826     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9827     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9828     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9829                               Op0, Op1);
9830     return SDValue(Sub.getNode(), 1);
9831   }
9832   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9833 }
9834
9835 /// Convert a comparison if required by the subtarget.
9836 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9837                                                  SelectionDAG &DAG) const {
9838   // If the subtarget does not support the FUCOMI instruction, floating-point
9839   // comparisons have to be converted.
9840   if (Subtarget->hasCMov() ||
9841       Cmp.getOpcode() != X86ISD::CMP ||
9842       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9843       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9844     return Cmp;
9845
9846   // The instruction selector will select an FUCOM instruction instead of
9847   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9848   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9849   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9850   SDLoc dl(Cmp);
9851   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9852   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9853   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9854                             DAG.getConstant(8, MVT::i8));
9855   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9856   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9857 }
9858
9859 static bool isAllOnes(SDValue V) {
9860   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9861   return C && C->isAllOnesValue();
9862 }
9863
9864 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9865 /// if it's possible.
9866 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9867                                      SDLoc dl, SelectionDAG &DAG) const {
9868   SDValue Op0 = And.getOperand(0);
9869   SDValue Op1 = And.getOperand(1);
9870   if (Op0.getOpcode() == ISD::TRUNCATE)
9871     Op0 = Op0.getOperand(0);
9872   if (Op1.getOpcode() == ISD::TRUNCATE)
9873     Op1 = Op1.getOperand(0);
9874
9875   SDValue LHS, RHS;
9876   if (Op1.getOpcode() == ISD::SHL)
9877     std::swap(Op0, Op1);
9878   if (Op0.getOpcode() == ISD::SHL) {
9879     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9880       if (And00C->getZExtValue() == 1) {
9881         // If we looked past a truncate, check that it's only truncating away
9882         // known zeros.
9883         unsigned BitWidth = Op0.getValueSizeInBits();
9884         unsigned AndBitWidth = And.getValueSizeInBits();
9885         if (BitWidth > AndBitWidth) {
9886           APInt Zeros, Ones;
9887           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9888           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9889             return SDValue();
9890         }
9891         LHS = Op1;
9892         RHS = Op0.getOperand(1);
9893       }
9894   } else if (Op1.getOpcode() == ISD::Constant) {
9895     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9896     uint64_t AndRHSVal = AndRHS->getZExtValue();
9897     SDValue AndLHS = Op0;
9898
9899     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9900       LHS = AndLHS.getOperand(0);
9901       RHS = AndLHS.getOperand(1);
9902     }
9903
9904     // Use BT if the immediate can't be encoded in a TEST instruction.
9905     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9906       LHS = AndLHS;
9907       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9908     }
9909   }
9910
9911   if (LHS.getNode()) {
9912     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9913     // instruction.  Since the shift amount is in-range-or-undefined, we know
9914     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9915     // the encoding for the i16 version is larger than the i32 version.
9916     // Also promote i16 to i32 for performance / code size reason.
9917     if (LHS.getValueType() == MVT::i8 ||
9918         LHS.getValueType() == MVT::i16)
9919       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9920
9921     // If the operand types disagree, extend the shift amount to match.  Since
9922     // BT ignores high bits (like shifts) we can use anyextend.
9923     if (LHS.getValueType() != RHS.getValueType())
9924       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9925
9926     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9927     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9928     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9929                        DAG.getConstant(Cond, MVT::i8), BT);
9930   }
9931
9932   return SDValue();
9933 }
9934
9935 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9936 /// mask CMPs.
9937 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9938                               SDValue &Op1) {
9939   unsigned SSECC;
9940   bool Swap = false;
9941
9942   // SSE Condition code mapping:
9943   //  0 - EQ
9944   //  1 - LT
9945   //  2 - LE
9946   //  3 - UNORD
9947   //  4 - NEQ
9948   //  5 - NLT
9949   //  6 - NLE
9950   //  7 - ORD
9951   switch (SetCCOpcode) {
9952   default: llvm_unreachable("Unexpected SETCC condition");
9953   case ISD::SETOEQ:
9954   case ISD::SETEQ:  SSECC = 0; break;
9955   case ISD::SETOGT:
9956   case ISD::SETGT:  Swap = true; // Fallthrough
9957   case ISD::SETLT:
9958   case ISD::SETOLT: SSECC = 1; break;
9959   case ISD::SETOGE:
9960   case ISD::SETGE:  Swap = true; // Fallthrough
9961   case ISD::SETLE:
9962   case ISD::SETOLE: SSECC = 2; break;
9963   case ISD::SETUO:  SSECC = 3; break;
9964   case ISD::SETUNE:
9965   case ISD::SETNE:  SSECC = 4; break;
9966   case ISD::SETULE: Swap = true; // Fallthrough
9967   case ISD::SETUGE: SSECC = 5; break;
9968   case ISD::SETULT: Swap = true; // Fallthrough
9969   case ISD::SETUGT: SSECC = 6; break;
9970   case ISD::SETO:   SSECC = 7; break;
9971   case ISD::SETUEQ:
9972   case ISD::SETONE: SSECC = 8; break;
9973   }
9974   if (Swap)
9975     std::swap(Op0, Op1);
9976
9977   return SSECC;
9978 }
9979
9980 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9981 // ones, and then concatenate the result back.
9982 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9983   MVT VT = Op.getSimpleValueType();
9984
9985   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9986          "Unsupported value type for operation");
9987
9988   unsigned NumElems = VT.getVectorNumElements();
9989   SDLoc dl(Op);
9990   SDValue CC = Op.getOperand(2);
9991
9992   // Extract the LHS vectors
9993   SDValue LHS = Op.getOperand(0);
9994   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9995   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9996
9997   // Extract the RHS vectors
9998   SDValue RHS = Op.getOperand(1);
9999   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10000   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10001
10002   // Issue the operation on the smaller types and concatenate the result back
10003   MVT EltVT = VT.getVectorElementType();
10004   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10005   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10006                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10007                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10008 }
10009
10010 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10011                                      const X86Subtarget *Subtarget) {
10012   SDValue Op0 = Op.getOperand(0);
10013   SDValue Op1 = Op.getOperand(1);
10014   SDValue CC = Op.getOperand(2);
10015   MVT VT = Op.getSimpleValueType();
10016   SDLoc dl(Op);
10017
10018   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10019          Op.getValueType().getScalarType() == MVT::i1 &&
10020          "Cannot set masked compare for this operation");
10021
10022   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10023   unsigned  Opc = 0;
10024   bool Unsigned = false;
10025   bool Swap = false;
10026   unsigned SSECC;
10027   switch (SetCCOpcode) {
10028   default: llvm_unreachable("Unexpected SETCC condition");
10029   case ISD::SETNE:  SSECC = 4; break;
10030   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10031   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10032   case ISD::SETLT:  Swap = true; //fall-through
10033   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10034   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10035   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10036   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10037   case ISD::SETULE: Unsigned = true; //fall-through
10038   case ISD::SETLE:  SSECC = 2; break;
10039   }
10040
10041   if (Swap)
10042     std::swap(Op0, Op1);
10043   if (Opc)
10044     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10045   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10046   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10047                      DAG.getConstant(SSECC, MVT::i8));
10048 }
10049
10050 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10051                            SelectionDAG &DAG) {
10052   SDValue Op0 = Op.getOperand(0);
10053   SDValue Op1 = Op.getOperand(1);
10054   SDValue CC = Op.getOperand(2);
10055   MVT VT = Op.getSimpleValueType();
10056   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10057   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10058   SDLoc dl(Op);
10059
10060   if (isFP) {
10061 #ifndef NDEBUG
10062     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10063     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10064 #endif
10065
10066     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10067     unsigned Opc = X86ISD::CMPP;
10068     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10069       assert(VT.getVectorNumElements() <= 16);
10070       Opc = X86ISD::CMPM;
10071     }
10072     // In the two special cases we can't handle, emit two comparisons.
10073     if (SSECC == 8) {
10074       unsigned CC0, CC1;
10075       unsigned CombineOpc;
10076       if (SetCCOpcode == ISD::SETUEQ) {
10077         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10078       } else {
10079         assert(SetCCOpcode == ISD::SETONE);
10080         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10081       }
10082
10083       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10084                                  DAG.getConstant(CC0, MVT::i8));
10085       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10086                                  DAG.getConstant(CC1, MVT::i8));
10087       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10088     }
10089     // Handle all other FP comparisons here.
10090     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10091                        DAG.getConstant(SSECC, MVT::i8));
10092   }
10093
10094   // Break 256-bit integer vector compare into smaller ones.
10095   if (VT.is256BitVector() && !Subtarget->hasInt256())
10096     return Lower256IntVSETCC(Op, DAG);
10097
10098   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10099   EVT OpVT = Op1.getValueType();
10100   if (Subtarget->hasAVX512()) {
10101     if (Op1.getValueType().is512BitVector() ||
10102         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10103       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10104
10105     // In AVX-512 architecture setcc returns mask with i1 elements,
10106     // But there is no compare instruction for i8 and i16 elements.
10107     // We are not talking about 512-bit operands in this case, these
10108     // types are illegal.
10109     if (MaskResult &&
10110         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10111          OpVT.getVectorElementType().getSizeInBits() >= 8))
10112       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10113                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10114   }
10115
10116   // We are handling one of the integer comparisons here.  Since SSE only has
10117   // GT and EQ comparisons for integer, swapping operands and multiple
10118   // operations may be required for some comparisons.
10119   unsigned Opc;
10120   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10121
10122   switch (SetCCOpcode) {
10123   default: llvm_unreachable("Unexpected SETCC condition");
10124   case ISD::SETNE:  Invert = true;
10125   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10126   case ISD::SETLT:  Swap = true;
10127   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10128   case ISD::SETGE:  Swap = true;
10129   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10130                     Invert = true; break;
10131   case ISD::SETULT: Swap = true;
10132   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10133                     FlipSigns = true; break;
10134   case ISD::SETUGE: Swap = true;
10135   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10136                     FlipSigns = true; Invert = true; break;
10137   }
10138
10139   // Special case: Use min/max operations for SETULE/SETUGE
10140   MVT VET = VT.getVectorElementType();
10141   bool hasMinMax =
10142        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10143     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10144
10145   if (hasMinMax) {
10146     switch (SetCCOpcode) {
10147     default: break;
10148     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10149     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10150     }
10151
10152     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10153   }
10154
10155   if (Swap)
10156     std::swap(Op0, Op1);
10157
10158   // Check that the operation in question is available (most are plain SSE2,
10159   // but PCMPGTQ and PCMPEQQ have different requirements).
10160   if (VT == MVT::v2i64) {
10161     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10162       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10163
10164       // First cast everything to the right type.
10165       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10166       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10167
10168       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10169       // bits of the inputs before performing those operations. The lower
10170       // compare is always unsigned.
10171       SDValue SB;
10172       if (FlipSigns) {
10173         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10174       } else {
10175         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10176         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10177         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10178                          Sign, Zero, Sign, Zero);
10179       }
10180       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10181       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10182
10183       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10184       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10185       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10186
10187       // Create masks for only the low parts/high parts of the 64 bit integers.
10188       static const int MaskHi[] = { 1, 1, 3, 3 };
10189       static const int MaskLo[] = { 0, 0, 2, 2 };
10190       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10191       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10192       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10193
10194       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10195       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10196
10197       if (Invert)
10198         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10199
10200       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10201     }
10202
10203     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10204       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10205       // pcmpeqd + pshufd + pand.
10206       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10207
10208       // First cast everything to the right type.
10209       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10210       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10211
10212       // Do the compare.
10213       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10214
10215       // Make sure the lower and upper halves are both all-ones.
10216       static const int Mask[] = { 1, 0, 3, 2 };
10217       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10218       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10219
10220       if (Invert)
10221         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10222
10223       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10224     }
10225   }
10226
10227   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10228   // bits of the inputs before performing those operations.
10229   if (FlipSigns) {
10230     EVT EltVT = VT.getVectorElementType();
10231     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10232     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10233     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10234   }
10235
10236   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10237
10238   // If the logical-not of the result is required, perform that now.
10239   if (Invert)
10240     Result = DAG.getNOT(dl, Result, VT);
10241
10242   if (MinMax)
10243     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10244
10245   return Result;
10246 }
10247
10248 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10249
10250   MVT VT = Op.getSimpleValueType();
10251
10252   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10253
10254   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10255          && "SetCC type must be 8-bit or 1-bit integer");
10256   SDValue Op0 = Op.getOperand(0);
10257   SDValue Op1 = Op.getOperand(1);
10258   SDLoc dl(Op);
10259   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10260
10261   // Optimize to BT if possible.
10262   // Lower (X & (1 << N)) == 0 to BT(X, N).
10263   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10264   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10265   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10266       Op1.getOpcode() == ISD::Constant &&
10267       cast<ConstantSDNode>(Op1)->isNullValue() &&
10268       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10269     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10270     if (NewSetCC.getNode())
10271       return NewSetCC;
10272   }
10273
10274   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10275   // these.
10276   if (Op1.getOpcode() == ISD::Constant &&
10277       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10278        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10279       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10280
10281     // If the input is a setcc, then reuse the input setcc or use a new one with
10282     // the inverted condition.
10283     if (Op0.getOpcode() == X86ISD::SETCC) {
10284       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10285       bool Invert = (CC == ISD::SETNE) ^
10286         cast<ConstantSDNode>(Op1)->isNullValue();
10287       if (!Invert)
10288         return Op0;
10289
10290       CCode = X86::GetOppositeBranchCondition(CCode);
10291       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10292                                   DAG.getConstant(CCode, MVT::i8),
10293                                   Op0.getOperand(1));
10294       if (VT == MVT::i1)
10295         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10296       return SetCC;
10297     }
10298   }
10299
10300   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10301   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10302   if (X86CC == X86::COND_INVALID)
10303     return SDValue();
10304
10305   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10306   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10307   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10308                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10309   if (VT == MVT::i1)
10310     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10311   return SetCC;
10312 }
10313
10314 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10315 static bool isX86LogicalCmp(SDValue Op) {
10316   unsigned Opc = Op.getNode()->getOpcode();
10317   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10318       Opc == X86ISD::SAHF)
10319     return true;
10320   if (Op.getResNo() == 1 &&
10321       (Opc == X86ISD::ADD ||
10322        Opc == X86ISD::SUB ||
10323        Opc == X86ISD::ADC ||
10324        Opc == X86ISD::SBB ||
10325        Opc == X86ISD::SMUL ||
10326        Opc == X86ISD::UMUL ||
10327        Opc == X86ISD::INC ||
10328        Opc == X86ISD::DEC ||
10329        Opc == X86ISD::OR ||
10330        Opc == X86ISD::XOR ||
10331        Opc == X86ISD::AND))
10332     return true;
10333
10334   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10335     return true;
10336
10337   return false;
10338 }
10339
10340 static bool isZero(SDValue V) {
10341   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10342   return C && C->isNullValue();
10343 }
10344
10345 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10346   if (V.getOpcode() != ISD::TRUNCATE)
10347     return false;
10348
10349   SDValue VOp0 = V.getOperand(0);
10350   unsigned InBits = VOp0.getValueSizeInBits();
10351   unsigned Bits = V.getValueSizeInBits();
10352   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10353 }
10354
10355 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10356   bool addTest = true;
10357   SDValue Cond  = Op.getOperand(0);
10358   SDValue Op1 = Op.getOperand(1);
10359   SDValue Op2 = Op.getOperand(2);
10360   SDLoc DL(Op);
10361   EVT VT = Op1.getValueType();
10362   SDValue CC;
10363
10364   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10365   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10366   // sequence later on.
10367   if (Cond.getOpcode() == ISD::SETCC &&
10368       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10369        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10370       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10371     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10372     int SSECC = translateX86FSETCC(
10373         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10374
10375     if (SSECC != 8) {
10376       if (Subtarget->hasAVX512()) {
10377         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10378                                   DAG.getConstant(SSECC, MVT::i8));
10379         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10380       }
10381       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10382                                 DAG.getConstant(SSECC, MVT::i8));
10383       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10384       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10385       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10386     }
10387   }
10388
10389   if (Cond.getOpcode() == ISD::SETCC) {
10390     SDValue NewCond = LowerSETCC(Cond, DAG);
10391     if (NewCond.getNode())
10392       Cond = NewCond;
10393   }
10394
10395   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10396   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10397   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10398   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10399   if (Cond.getOpcode() == X86ISD::SETCC &&
10400       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10401       isZero(Cond.getOperand(1).getOperand(1))) {
10402     SDValue Cmp = Cond.getOperand(1);
10403
10404     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10405
10406     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10407         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10408       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10409
10410       SDValue CmpOp0 = Cmp.getOperand(0);
10411       // Apply further optimizations for special cases
10412       // (select (x != 0), -1, 0) -> neg & sbb
10413       // (select (x == 0), 0, -1) -> neg & sbb
10414       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10415         if (YC->isNullValue() &&
10416             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10417           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10418           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10419                                     DAG.getConstant(0, CmpOp0.getValueType()),
10420                                     CmpOp0);
10421           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10422                                     DAG.getConstant(X86::COND_B, MVT::i8),
10423                                     SDValue(Neg.getNode(), 1));
10424           return Res;
10425         }
10426
10427       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10428                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10429       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10430
10431       SDValue Res =   // Res = 0 or -1.
10432         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10433                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10434
10435       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10436         Res = DAG.getNOT(DL, Res, Res.getValueType());
10437
10438       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10439       if (N2C == 0 || !N2C->isNullValue())
10440         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10441       return Res;
10442     }
10443   }
10444
10445   // Look past (and (setcc_carry (cmp ...)), 1).
10446   if (Cond.getOpcode() == ISD::AND &&
10447       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10448     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10449     if (C && C->getAPIntValue() == 1)
10450       Cond = Cond.getOperand(0);
10451   }
10452
10453   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10454   // setting operand in place of the X86ISD::SETCC.
10455   unsigned CondOpcode = Cond.getOpcode();
10456   if (CondOpcode == X86ISD::SETCC ||
10457       CondOpcode == X86ISD::SETCC_CARRY) {
10458     CC = Cond.getOperand(0);
10459
10460     SDValue Cmp = Cond.getOperand(1);
10461     unsigned Opc = Cmp.getOpcode();
10462     MVT VT = Op.getSimpleValueType();
10463
10464     bool IllegalFPCMov = false;
10465     if (VT.isFloatingPoint() && !VT.isVector() &&
10466         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10467       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10468
10469     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10470         Opc == X86ISD::BT) { // FIXME
10471       Cond = Cmp;
10472       addTest = false;
10473     }
10474   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10475              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10476              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10477               Cond.getOperand(0).getValueType() != MVT::i8)) {
10478     SDValue LHS = Cond.getOperand(0);
10479     SDValue RHS = Cond.getOperand(1);
10480     unsigned X86Opcode;
10481     unsigned X86Cond;
10482     SDVTList VTs;
10483     switch (CondOpcode) {
10484     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10485     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10486     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10487     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10488     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10489     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10490     default: llvm_unreachable("unexpected overflowing operator");
10491     }
10492     if (CondOpcode == ISD::UMULO)
10493       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10494                           MVT::i32);
10495     else
10496       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10497
10498     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10499
10500     if (CondOpcode == ISD::UMULO)
10501       Cond = X86Op.getValue(2);
10502     else
10503       Cond = X86Op.getValue(1);
10504
10505     CC = DAG.getConstant(X86Cond, MVT::i8);
10506     addTest = false;
10507   }
10508
10509   if (addTest) {
10510     // Look pass the truncate if the high bits are known zero.
10511     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10512         Cond = Cond.getOperand(0);
10513
10514     // We know the result of AND is compared against zero. Try to match
10515     // it to BT.
10516     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10517       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10518       if (NewSetCC.getNode()) {
10519         CC = NewSetCC.getOperand(0);
10520         Cond = NewSetCC.getOperand(1);
10521         addTest = false;
10522       }
10523     }
10524   }
10525
10526   if (addTest) {
10527     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10528     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10529   }
10530
10531   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10532   // a <  b ?  0 : -1 -> RES = setcc_carry
10533   // a >= b ? -1 :  0 -> RES = setcc_carry
10534   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10535   if (Cond.getOpcode() == X86ISD::SUB) {
10536     Cond = ConvertCmpIfNecessary(Cond, DAG);
10537     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10538
10539     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10540         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10541       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10542                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10543       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10544         return DAG.getNOT(DL, Res, Res.getValueType());
10545       return Res;
10546     }
10547   }
10548
10549   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10550   // widen the cmov and push the truncate through. This avoids introducing a new
10551   // branch during isel and doesn't add any extensions.
10552   if (Op.getValueType() == MVT::i8 &&
10553       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10554     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10555     if (T1.getValueType() == T2.getValueType() &&
10556         // Blacklist CopyFromReg to avoid partial register stalls.
10557         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10558       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10559       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10560       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10561     }
10562   }
10563
10564   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10565   // condition is true.
10566   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10567   SDValue Ops[] = { Op2, Op1, CC, Cond };
10568   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10569 }
10570
10571 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10572   MVT VT = Op->getSimpleValueType(0);
10573   SDValue In = Op->getOperand(0);
10574   MVT InVT = In.getSimpleValueType();
10575   SDLoc dl(Op);
10576
10577   unsigned int NumElts = VT.getVectorNumElements();
10578   if (NumElts != 8 && NumElts != 16)
10579     return SDValue();
10580
10581   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10582     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10583
10584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10585   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10586
10587   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10588   Constant *C = ConstantInt::get(*DAG.getContext(),
10589     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10590
10591   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10592   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10593   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10594                           MachinePointerInfo::getConstantPool(),
10595                           false, false, false, Alignment);
10596   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10597   if (VT.is512BitVector())
10598     return Brcst;
10599   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10600 }
10601
10602 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10603                                 SelectionDAG &DAG) {
10604   MVT VT = Op->getSimpleValueType(0);
10605   SDValue In = Op->getOperand(0);
10606   MVT InVT = In.getSimpleValueType();
10607   SDLoc dl(Op);
10608
10609   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10610     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10611
10612   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10613       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10614       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10615     return SDValue();
10616
10617   if (Subtarget->hasInt256())
10618     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10619
10620   // Optimize vectors in AVX mode
10621   // Sign extend  v8i16 to v8i32 and
10622   //              v4i32 to v4i64
10623   //
10624   // Divide input vector into two parts
10625   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10626   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10627   // concat the vectors to original VT
10628
10629   unsigned NumElems = InVT.getVectorNumElements();
10630   SDValue Undef = DAG.getUNDEF(InVT);
10631
10632   SmallVector<int,8> ShufMask1(NumElems, -1);
10633   for (unsigned i = 0; i != NumElems/2; ++i)
10634     ShufMask1[i] = i;
10635
10636   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10637
10638   SmallVector<int,8> ShufMask2(NumElems, -1);
10639   for (unsigned i = 0; i != NumElems/2; ++i)
10640     ShufMask2[i] = i + NumElems/2;
10641
10642   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10643
10644   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10645                                 VT.getVectorNumElements()/2);
10646
10647   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10648   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10649
10650   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10651 }
10652
10653 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10654 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10655 // from the AND / OR.
10656 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10657   Opc = Op.getOpcode();
10658   if (Opc != ISD::OR && Opc != ISD::AND)
10659     return false;
10660   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10661           Op.getOperand(0).hasOneUse() &&
10662           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10663           Op.getOperand(1).hasOneUse());
10664 }
10665
10666 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10667 // 1 and that the SETCC node has a single use.
10668 static bool isXor1OfSetCC(SDValue Op) {
10669   if (Op.getOpcode() != ISD::XOR)
10670     return false;
10671   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10672   if (N1C && N1C->getAPIntValue() == 1) {
10673     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10674       Op.getOperand(0).hasOneUse();
10675   }
10676   return false;
10677 }
10678
10679 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10680   bool addTest = true;
10681   SDValue Chain = Op.getOperand(0);
10682   SDValue Cond  = Op.getOperand(1);
10683   SDValue Dest  = Op.getOperand(2);
10684   SDLoc dl(Op);
10685   SDValue CC;
10686   bool Inverted = false;
10687
10688   if (Cond.getOpcode() == ISD::SETCC) {
10689     // Check for setcc([su]{add,sub,mul}o == 0).
10690     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10691         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10692         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10693         Cond.getOperand(0).getResNo() == 1 &&
10694         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10695          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10696          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10697          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10698          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10699          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10700       Inverted = true;
10701       Cond = Cond.getOperand(0);
10702     } else {
10703       SDValue NewCond = LowerSETCC(Cond, DAG);
10704       if (NewCond.getNode())
10705         Cond = NewCond;
10706     }
10707   }
10708 #if 0
10709   // FIXME: LowerXALUO doesn't handle these!!
10710   else if (Cond.getOpcode() == X86ISD::ADD  ||
10711            Cond.getOpcode() == X86ISD::SUB  ||
10712            Cond.getOpcode() == X86ISD::SMUL ||
10713            Cond.getOpcode() == X86ISD::UMUL)
10714     Cond = LowerXALUO(Cond, DAG);
10715 #endif
10716
10717   // Look pass (and (setcc_carry (cmp ...)), 1).
10718   if (Cond.getOpcode() == ISD::AND &&
10719       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10720     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10721     if (C && C->getAPIntValue() == 1)
10722       Cond = Cond.getOperand(0);
10723   }
10724
10725   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10726   // setting operand in place of the X86ISD::SETCC.
10727   unsigned CondOpcode = Cond.getOpcode();
10728   if (CondOpcode == X86ISD::SETCC ||
10729       CondOpcode == X86ISD::SETCC_CARRY) {
10730     CC = Cond.getOperand(0);
10731
10732     SDValue Cmp = Cond.getOperand(1);
10733     unsigned Opc = Cmp.getOpcode();
10734     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10735     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10736       Cond = Cmp;
10737       addTest = false;
10738     } else {
10739       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10740       default: break;
10741       case X86::COND_O:
10742       case X86::COND_B:
10743         // These can only come from an arithmetic instruction with overflow,
10744         // e.g. SADDO, UADDO.
10745         Cond = Cond.getNode()->getOperand(1);
10746         addTest = false;
10747         break;
10748       }
10749     }
10750   }
10751   CondOpcode = Cond.getOpcode();
10752   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10753       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10754       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10755        Cond.getOperand(0).getValueType() != MVT::i8)) {
10756     SDValue LHS = Cond.getOperand(0);
10757     SDValue RHS = Cond.getOperand(1);
10758     unsigned X86Opcode;
10759     unsigned X86Cond;
10760     SDVTList VTs;
10761     // Keep this in sync with LowerXALUO, otherwise we might create redundant
10762     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10763     // X86ISD::INC).
10764     switch (CondOpcode) {
10765     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10766     case ISD::SADDO:
10767       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10768         if (C->isOne()) {
10769           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10770           break;
10771         }
10772       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10773     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10774     case ISD::SSUBO:
10775       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10776         if (C->isOne()) {
10777           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10778           break;
10779         }
10780       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10781     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10782     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10783     default: llvm_unreachable("unexpected overflowing operator");
10784     }
10785     if (Inverted)
10786       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10787     if (CondOpcode == ISD::UMULO)
10788       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10789                           MVT::i32);
10790     else
10791       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10792
10793     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10794
10795     if (CondOpcode == ISD::UMULO)
10796       Cond = X86Op.getValue(2);
10797     else
10798       Cond = X86Op.getValue(1);
10799
10800     CC = DAG.getConstant(X86Cond, MVT::i8);
10801     addTest = false;
10802   } else {
10803     unsigned CondOpc;
10804     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10805       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10806       if (CondOpc == ISD::OR) {
10807         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10808         // two branches instead of an explicit OR instruction with a
10809         // separate test.
10810         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10811             isX86LogicalCmp(Cmp)) {
10812           CC = Cond.getOperand(0).getOperand(0);
10813           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10814                               Chain, Dest, CC, Cmp);
10815           CC = Cond.getOperand(1).getOperand(0);
10816           Cond = Cmp;
10817           addTest = false;
10818         }
10819       } else { // ISD::AND
10820         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10821         // two branches instead of an explicit AND instruction with a
10822         // separate test. However, we only do this if this block doesn't
10823         // have a fall-through edge, because this requires an explicit
10824         // jmp when the condition is false.
10825         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10826             isX86LogicalCmp(Cmp) &&
10827             Op.getNode()->hasOneUse()) {
10828           X86::CondCode CCode =
10829             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10830           CCode = X86::GetOppositeBranchCondition(CCode);
10831           CC = DAG.getConstant(CCode, MVT::i8);
10832           SDNode *User = *Op.getNode()->use_begin();
10833           // Look for an unconditional branch following this conditional branch.
10834           // We need this because we need to reverse the successors in order
10835           // to implement FCMP_OEQ.
10836           if (User->getOpcode() == ISD::BR) {
10837             SDValue FalseBB = User->getOperand(1);
10838             SDNode *NewBR =
10839               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10840             assert(NewBR == User);
10841             (void)NewBR;
10842             Dest = FalseBB;
10843
10844             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10845                                 Chain, Dest, CC, Cmp);
10846             X86::CondCode CCode =
10847               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10848             CCode = X86::GetOppositeBranchCondition(CCode);
10849             CC = DAG.getConstant(CCode, MVT::i8);
10850             Cond = Cmp;
10851             addTest = false;
10852           }
10853         }
10854       }
10855     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10856       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10857       // It should be transformed during dag combiner except when the condition
10858       // is set by a arithmetics with overflow node.
10859       X86::CondCode CCode =
10860         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10861       CCode = X86::GetOppositeBranchCondition(CCode);
10862       CC = DAG.getConstant(CCode, MVT::i8);
10863       Cond = Cond.getOperand(0).getOperand(1);
10864       addTest = false;
10865     } else if (Cond.getOpcode() == ISD::SETCC &&
10866                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10867       // For FCMP_OEQ, we can emit
10868       // two branches instead of an explicit AND instruction with a
10869       // separate test. However, we only do this if this block doesn't
10870       // have a fall-through edge, because this requires an explicit
10871       // jmp when the condition is false.
10872       if (Op.getNode()->hasOneUse()) {
10873         SDNode *User = *Op.getNode()->use_begin();
10874         // Look for an unconditional branch following this conditional branch.
10875         // We need this because we need to reverse the successors in order
10876         // to implement FCMP_OEQ.
10877         if (User->getOpcode() == ISD::BR) {
10878           SDValue FalseBB = User->getOperand(1);
10879           SDNode *NewBR =
10880             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10881           assert(NewBR == User);
10882           (void)NewBR;
10883           Dest = FalseBB;
10884
10885           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10886                                     Cond.getOperand(0), Cond.getOperand(1));
10887           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10888           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10889           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10890                               Chain, Dest, CC, Cmp);
10891           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10892           Cond = Cmp;
10893           addTest = false;
10894         }
10895       }
10896     } else if (Cond.getOpcode() == ISD::SETCC &&
10897                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10898       // For FCMP_UNE, we can emit
10899       // two branches instead of an explicit AND instruction with a
10900       // separate test. However, we only do this if this block doesn't
10901       // have a fall-through edge, because this requires an explicit
10902       // jmp when the condition is false.
10903       if (Op.getNode()->hasOneUse()) {
10904         SDNode *User = *Op.getNode()->use_begin();
10905         // Look for an unconditional branch following this conditional branch.
10906         // We need this because we need to reverse the successors in order
10907         // to implement FCMP_UNE.
10908         if (User->getOpcode() == ISD::BR) {
10909           SDValue FalseBB = User->getOperand(1);
10910           SDNode *NewBR =
10911             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10912           assert(NewBR == User);
10913           (void)NewBR;
10914
10915           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10916                                     Cond.getOperand(0), Cond.getOperand(1));
10917           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10918           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10919           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10920                               Chain, Dest, CC, Cmp);
10921           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10922           Cond = Cmp;
10923           addTest = false;
10924           Dest = FalseBB;
10925         }
10926       }
10927     }
10928   }
10929
10930   if (addTest) {
10931     // Look pass the truncate if the high bits are known zero.
10932     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10933         Cond = Cond.getOperand(0);
10934
10935     // We know the result of AND is compared against zero. Try to match
10936     // it to BT.
10937     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10938       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10939       if (NewSetCC.getNode()) {
10940         CC = NewSetCC.getOperand(0);
10941         Cond = NewSetCC.getOperand(1);
10942         addTest = false;
10943       }
10944     }
10945   }
10946
10947   if (addTest) {
10948     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10949     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10950   }
10951   Cond = ConvertCmpIfNecessary(Cond, DAG);
10952   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10953                      Chain, Dest, CC, Cond);
10954 }
10955
10956 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10957 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10958 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10959 // that the guard pages used by the OS virtual memory manager are allocated in
10960 // correct sequence.
10961 SDValue
10962 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10963                                            SelectionDAG &DAG) const {
10964   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10965           getTargetMachine().Options.EnableSegmentedStacks) &&
10966          "This should be used only on Windows targets or when segmented stacks "
10967          "are being used");
10968   assert(!Subtarget->isTargetMacho() && "Not implemented");
10969   SDLoc dl(Op);
10970
10971   // Get the inputs.
10972   SDValue Chain = Op.getOperand(0);
10973   SDValue Size  = Op.getOperand(1);
10974   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10975   EVT VT = Op.getNode()->getValueType(0);
10976
10977   bool Is64Bit = Subtarget->is64Bit();
10978   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10979
10980   if (getTargetMachine().Options.EnableSegmentedStacks) {
10981     MachineFunction &MF = DAG.getMachineFunction();
10982     MachineRegisterInfo &MRI = MF.getRegInfo();
10983
10984     if (Is64Bit) {
10985       // The 64 bit implementation of segmented stacks needs to clobber both r10
10986       // r11. This makes it impossible to use it along with nested parameters.
10987       const Function *F = MF.getFunction();
10988
10989       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10990            I != E; ++I)
10991         if (I->hasNestAttr())
10992           report_fatal_error("Cannot use segmented stacks with functions that "
10993                              "have nested arguments.");
10994     }
10995
10996     const TargetRegisterClass *AddrRegClass =
10997       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10998     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10999     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11000     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11001                                 DAG.getRegister(Vreg, SPTy));
11002     SDValue Ops1[2] = { Value, Chain };
11003     return DAG.getMergeValues(Ops1, 2, dl);
11004   } else {
11005     SDValue Flag;
11006     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11007
11008     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11009     Flag = Chain.getValue(1);
11010     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11011
11012     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11013
11014     const X86RegisterInfo *RegInfo =
11015       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11016     unsigned SPReg = RegInfo->getStackRegister();
11017     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11018     Chain = SP.getValue(1);
11019
11020     if (Align) {
11021       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11022                        DAG.getConstant(-(uint64_t)Align, VT));
11023       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11024     }
11025
11026     SDValue Ops1[2] = { SP, Chain };
11027     return DAG.getMergeValues(Ops1, 2, dl);
11028   }
11029 }
11030
11031 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11032   MachineFunction &MF = DAG.getMachineFunction();
11033   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11034
11035   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11036   SDLoc DL(Op);
11037
11038   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11039     // vastart just stores the address of the VarArgsFrameIndex slot into the
11040     // memory location argument.
11041     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11042                                    getPointerTy());
11043     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11044                         MachinePointerInfo(SV), false, false, 0);
11045   }
11046
11047   // __va_list_tag:
11048   //   gp_offset         (0 - 6 * 8)
11049   //   fp_offset         (48 - 48 + 8 * 16)
11050   //   overflow_arg_area (point to parameters coming in memory).
11051   //   reg_save_area
11052   SmallVector<SDValue, 8> MemOps;
11053   SDValue FIN = Op.getOperand(1);
11054   // Store gp_offset
11055   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11056                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11057                                                MVT::i32),
11058                                FIN, MachinePointerInfo(SV), false, false, 0);
11059   MemOps.push_back(Store);
11060
11061   // Store fp_offset
11062   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11063                     FIN, DAG.getIntPtrConstant(4));
11064   Store = DAG.getStore(Op.getOperand(0), DL,
11065                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11066                                        MVT::i32),
11067                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11068   MemOps.push_back(Store);
11069
11070   // Store ptr to overflow_arg_area
11071   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11072                     FIN, DAG.getIntPtrConstant(4));
11073   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11074                                     getPointerTy());
11075   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11076                        MachinePointerInfo(SV, 8),
11077                        false, false, 0);
11078   MemOps.push_back(Store);
11079
11080   // Store ptr to reg_save_area.
11081   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11082                     FIN, DAG.getIntPtrConstant(8));
11083   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11084                                     getPointerTy());
11085   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11086                        MachinePointerInfo(SV, 16), false, false, 0);
11087   MemOps.push_back(Store);
11088   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11089                      &MemOps[0], MemOps.size());
11090 }
11091
11092 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11093   assert(Subtarget->is64Bit() &&
11094          "LowerVAARG only handles 64-bit va_arg!");
11095   assert((Subtarget->isTargetLinux() ||
11096           Subtarget->isTargetDarwin()) &&
11097           "Unhandled target in LowerVAARG");
11098   assert(Op.getNode()->getNumOperands() == 4);
11099   SDValue Chain = Op.getOperand(0);
11100   SDValue SrcPtr = Op.getOperand(1);
11101   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11102   unsigned Align = Op.getConstantOperandVal(3);
11103   SDLoc dl(Op);
11104
11105   EVT ArgVT = Op.getNode()->getValueType(0);
11106   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11107   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11108   uint8_t ArgMode;
11109
11110   // Decide which area this value should be read from.
11111   // TODO: Implement the AMD64 ABI in its entirety. This simple
11112   // selection mechanism works only for the basic types.
11113   if (ArgVT == MVT::f80) {
11114     llvm_unreachable("va_arg for f80 not yet implemented");
11115   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11116     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11117   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11118     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11119   } else {
11120     llvm_unreachable("Unhandled argument type in LowerVAARG");
11121   }
11122
11123   if (ArgMode == 2) {
11124     // Sanity Check: Make sure using fp_offset makes sense.
11125     assert(!getTargetMachine().Options.UseSoftFloat &&
11126            !(DAG.getMachineFunction()
11127                 .getFunction()->getAttributes()
11128                 .hasAttribute(AttributeSet::FunctionIndex,
11129                               Attribute::NoImplicitFloat)) &&
11130            Subtarget->hasSSE1());
11131   }
11132
11133   // Insert VAARG_64 node into the DAG
11134   // VAARG_64 returns two values: Variable Argument Address, Chain
11135   SmallVector<SDValue, 11> InstOps;
11136   InstOps.push_back(Chain);
11137   InstOps.push_back(SrcPtr);
11138   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11139   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11140   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11141   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11142   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11143                                           VTs, &InstOps[0], InstOps.size(),
11144                                           MVT::i64,
11145                                           MachinePointerInfo(SV),
11146                                           /*Align=*/0,
11147                                           /*Volatile=*/false,
11148                                           /*ReadMem=*/true,
11149                                           /*WriteMem=*/true);
11150   Chain = VAARG.getValue(1);
11151
11152   // Load the next argument and return it
11153   return DAG.getLoad(ArgVT, dl,
11154                      Chain,
11155                      VAARG,
11156                      MachinePointerInfo(),
11157                      false, false, false, 0);
11158 }
11159
11160 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11161                            SelectionDAG &DAG) {
11162   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11163   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11164   SDValue Chain = Op.getOperand(0);
11165   SDValue DstPtr = Op.getOperand(1);
11166   SDValue SrcPtr = Op.getOperand(2);
11167   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11168   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11169   SDLoc DL(Op);
11170
11171   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11172                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11173                        false,
11174                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11175 }
11176
11177 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11178 // amount is a constant. Takes immediate version of shift as input.
11179 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11180                                           SDValue SrcOp, uint64_t ShiftAmt,
11181                                           SelectionDAG &DAG) {
11182   MVT ElementType = VT.getVectorElementType();
11183
11184   // Check for ShiftAmt >= element width
11185   if (ShiftAmt >= ElementType.getSizeInBits()) {
11186     if (Opc == X86ISD::VSRAI)
11187       ShiftAmt = ElementType.getSizeInBits() - 1;
11188     else
11189       return DAG.getConstant(0, VT);
11190   }
11191
11192   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11193          && "Unknown target vector shift-by-constant node");
11194
11195   // Fold this packed vector shift into a build vector if SrcOp is a
11196   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11197   if (VT == SrcOp.getSimpleValueType() &&
11198       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11199     SmallVector<SDValue, 8> Elts;
11200     unsigned NumElts = SrcOp->getNumOperands();
11201     ConstantSDNode *ND;
11202
11203     switch(Opc) {
11204     default: llvm_unreachable(0);
11205     case X86ISD::VSHLI:
11206       for (unsigned i=0; i!=NumElts; ++i) {
11207         SDValue CurrentOp = SrcOp->getOperand(i);
11208         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11209           Elts.push_back(CurrentOp);
11210           continue;
11211         }
11212         ND = cast<ConstantSDNode>(CurrentOp);
11213         const APInt &C = ND->getAPIntValue();
11214         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11215       }
11216       break;
11217     case X86ISD::VSRLI:
11218       for (unsigned i=0; i!=NumElts; ++i) {
11219         SDValue CurrentOp = SrcOp->getOperand(i);
11220         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11221           Elts.push_back(CurrentOp);
11222           continue;
11223         }
11224         ND = cast<ConstantSDNode>(CurrentOp);
11225         const APInt &C = ND->getAPIntValue();
11226         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11227       }
11228       break;
11229     case X86ISD::VSRAI:
11230       for (unsigned i=0; i!=NumElts; ++i) {
11231         SDValue CurrentOp = SrcOp->getOperand(i);
11232         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11233           Elts.push_back(CurrentOp);
11234           continue;
11235         }
11236         ND = cast<ConstantSDNode>(CurrentOp);
11237         const APInt &C = ND->getAPIntValue();
11238         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11239       }
11240       break;
11241     }
11242
11243     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11244   }
11245
11246   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11247 }
11248
11249 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11250 // may or may not be a constant. Takes immediate version of shift as input.
11251 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11252                                    SDValue SrcOp, SDValue ShAmt,
11253                                    SelectionDAG &DAG) {
11254   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11255
11256   // Catch shift-by-constant.
11257   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11258     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11259                                       CShAmt->getZExtValue(), DAG);
11260
11261   // Change opcode to non-immediate version
11262   switch (Opc) {
11263     default: llvm_unreachable("Unknown target vector shift node");
11264     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11265     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11266     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11267   }
11268
11269   // Need to build a vector containing shift amount
11270   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11271   SDValue ShOps[4];
11272   ShOps[0] = ShAmt;
11273   ShOps[1] = DAG.getConstant(0, MVT::i32);
11274   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11275   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11276
11277   // The return type has to be a 128-bit type with the same element
11278   // type as the input type.
11279   MVT EltVT = VT.getVectorElementType();
11280   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11281
11282   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11283   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11284 }
11285
11286 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11287   SDLoc dl(Op);
11288   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11289   switch (IntNo) {
11290   default: return SDValue();    // Don't custom lower most intrinsics.
11291   // Comparison intrinsics.
11292   case Intrinsic::x86_sse_comieq_ss:
11293   case Intrinsic::x86_sse_comilt_ss:
11294   case Intrinsic::x86_sse_comile_ss:
11295   case Intrinsic::x86_sse_comigt_ss:
11296   case Intrinsic::x86_sse_comige_ss:
11297   case Intrinsic::x86_sse_comineq_ss:
11298   case Intrinsic::x86_sse_ucomieq_ss:
11299   case Intrinsic::x86_sse_ucomilt_ss:
11300   case Intrinsic::x86_sse_ucomile_ss:
11301   case Intrinsic::x86_sse_ucomigt_ss:
11302   case Intrinsic::x86_sse_ucomige_ss:
11303   case Intrinsic::x86_sse_ucomineq_ss:
11304   case Intrinsic::x86_sse2_comieq_sd:
11305   case Intrinsic::x86_sse2_comilt_sd:
11306   case Intrinsic::x86_sse2_comile_sd:
11307   case Intrinsic::x86_sse2_comigt_sd:
11308   case Intrinsic::x86_sse2_comige_sd:
11309   case Intrinsic::x86_sse2_comineq_sd:
11310   case Intrinsic::x86_sse2_ucomieq_sd:
11311   case Intrinsic::x86_sse2_ucomilt_sd:
11312   case Intrinsic::x86_sse2_ucomile_sd:
11313   case Intrinsic::x86_sse2_ucomigt_sd:
11314   case Intrinsic::x86_sse2_ucomige_sd:
11315   case Intrinsic::x86_sse2_ucomineq_sd: {
11316     unsigned Opc;
11317     ISD::CondCode CC;
11318     switch (IntNo) {
11319     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11320     case Intrinsic::x86_sse_comieq_ss:
11321     case Intrinsic::x86_sse2_comieq_sd:
11322       Opc = X86ISD::COMI;
11323       CC = ISD::SETEQ;
11324       break;
11325     case Intrinsic::x86_sse_comilt_ss:
11326     case Intrinsic::x86_sse2_comilt_sd:
11327       Opc = X86ISD::COMI;
11328       CC = ISD::SETLT;
11329       break;
11330     case Intrinsic::x86_sse_comile_ss:
11331     case Intrinsic::x86_sse2_comile_sd:
11332       Opc = X86ISD::COMI;
11333       CC = ISD::SETLE;
11334       break;
11335     case Intrinsic::x86_sse_comigt_ss:
11336     case Intrinsic::x86_sse2_comigt_sd:
11337       Opc = X86ISD::COMI;
11338       CC = ISD::SETGT;
11339       break;
11340     case Intrinsic::x86_sse_comige_ss:
11341     case Intrinsic::x86_sse2_comige_sd:
11342       Opc = X86ISD::COMI;
11343       CC = ISD::SETGE;
11344       break;
11345     case Intrinsic::x86_sse_comineq_ss:
11346     case Intrinsic::x86_sse2_comineq_sd:
11347       Opc = X86ISD::COMI;
11348       CC = ISD::SETNE;
11349       break;
11350     case Intrinsic::x86_sse_ucomieq_ss:
11351     case Intrinsic::x86_sse2_ucomieq_sd:
11352       Opc = X86ISD::UCOMI;
11353       CC = ISD::SETEQ;
11354       break;
11355     case Intrinsic::x86_sse_ucomilt_ss:
11356     case Intrinsic::x86_sse2_ucomilt_sd:
11357       Opc = X86ISD::UCOMI;
11358       CC = ISD::SETLT;
11359       break;
11360     case Intrinsic::x86_sse_ucomile_ss:
11361     case Intrinsic::x86_sse2_ucomile_sd:
11362       Opc = X86ISD::UCOMI;
11363       CC = ISD::SETLE;
11364       break;
11365     case Intrinsic::x86_sse_ucomigt_ss:
11366     case Intrinsic::x86_sse2_ucomigt_sd:
11367       Opc = X86ISD::UCOMI;
11368       CC = ISD::SETGT;
11369       break;
11370     case Intrinsic::x86_sse_ucomige_ss:
11371     case Intrinsic::x86_sse2_ucomige_sd:
11372       Opc = X86ISD::UCOMI;
11373       CC = ISD::SETGE;
11374       break;
11375     case Intrinsic::x86_sse_ucomineq_ss:
11376     case Intrinsic::x86_sse2_ucomineq_sd:
11377       Opc = X86ISD::UCOMI;
11378       CC = ISD::SETNE;
11379       break;
11380     }
11381
11382     SDValue LHS = Op.getOperand(1);
11383     SDValue RHS = Op.getOperand(2);
11384     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11385     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11386     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11387     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11388                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11389     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11390   }
11391
11392   // Arithmetic intrinsics.
11393   case Intrinsic::x86_sse2_pmulu_dq:
11394   case Intrinsic::x86_avx2_pmulu_dq:
11395     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11396                        Op.getOperand(1), Op.getOperand(2));
11397
11398   // SSE2/AVX2 sub with unsigned saturation intrinsics
11399   case Intrinsic::x86_sse2_psubus_b:
11400   case Intrinsic::x86_sse2_psubus_w:
11401   case Intrinsic::x86_avx2_psubus_b:
11402   case Intrinsic::x86_avx2_psubus_w:
11403     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11404                        Op.getOperand(1), Op.getOperand(2));
11405
11406   // SSE3/AVX horizontal add/sub intrinsics
11407   case Intrinsic::x86_sse3_hadd_ps:
11408   case Intrinsic::x86_sse3_hadd_pd:
11409   case Intrinsic::x86_avx_hadd_ps_256:
11410   case Intrinsic::x86_avx_hadd_pd_256:
11411   case Intrinsic::x86_sse3_hsub_ps:
11412   case Intrinsic::x86_sse3_hsub_pd:
11413   case Intrinsic::x86_avx_hsub_ps_256:
11414   case Intrinsic::x86_avx_hsub_pd_256:
11415   case Intrinsic::x86_ssse3_phadd_w_128:
11416   case Intrinsic::x86_ssse3_phadd_d_128:
11417   case Intrinsic::x86_avx2_phadd_w:
11418   case Intrinsic::x86_avx2_phadd_d:
11419   case Intrinsic::x86_ssse3_phsub_w_128:
11420   case Intrinsic::x86_ssse3_phsub_d_128:
11421   case Intrinsic::x86_avx2_phsub_w:
11422   case Intrinsic::x86_avx2_phsub_d: {
11423     unsigned Opcode;
11424     switch (IntNo) {
11425     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11426     case Intrinsic::x86_sse3_hadd_ps:
11427     case Intrinsic::x86_sse3_hadd_pd:
11428     case Intrinsic::x86_avx_hadd_ps_256:
11429     case Intrinsic::x86_avx_hadd_pd_256:
11430       Opcode = X86ISD::FHADD;
11431       break;
11432     case Intrinsic::x86_sse3_hsub_ps:
11433     case Intrinsic::x86_sse3_hsub_pd:
11434     case Intrinsic::x86_avx_hsub_ps_256:
11435     case Intrinsic::x86_avx_hsub_pd_256:
11436       Opcode = X86ISD::FHSUB;
11437       break;
11438     case Intrinsic::x86_ssse3_phadd_w_128:
11439     case Intrinsic::x86_ssse3_phadd_d_128:
11440     case Intrinsic::x86_avx2_phadd_w:
11441     case Intrinsic::x86_avx2_phadd_d:
11442       Opcode = X86ISD::HADD;
11443       break;
11444     case Intrinsic::x86_ssse3_phsub_w_128:
11445     case Intrinsic::x86_ssse3_phsub_d_128:
11446     case Intrinsic::x86_avx2_phsub_w:
11447     case Intrinsic::x86_avx2_phsub_d:
11448       Opcode = X86ISD::HSUB;
11449       break;
11450     }
11451     return DAG.getNode(Opcode, dl, Op.getValueType(),
11452                        Op.getOperand(1), Op.getOperand(2));
11453   }
11454
11455   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11456   case Intrinsic::x86_sse2_pmaxu_b:
11457   case Intrinsic::x86_sse41_pmaxuw:
11458   case Intrinsic::x86_sse41_pmaxud:
11459   case Intrinsic::x86_avx2_pmaxu_b:
11460   case Intrinsic::x86_avx2_pmaxu_w:
11461   case Intrinsic::x86_avx2_pmaxu_d:
11462   case Intrinsic::x86_sse2_pminu_b:
11463   case Intrinsic::x86_sse41_pminuw:
11464   case Intrinsic::x86_sse41_pminud:
11465   case Intrinsic::x86_avx2_pminu_b:
11466   case Intrinsic::x86_avx2_pminu_w:
11467   case Intrinsic::x86_avx2_pminu_d:
11468   case Intrinsic::x86_sse41_pmaxsb:
11469   case Intrinsic::x86_sse2_pmaxs_w:
11470   case Intrinsic::x86_sse41_pmaxsd:
11471   case Intrinsic::x86_avx2_pmaxs_b:
11472   case Intrinsic::x86_avx2_pmaxs_w:
11473   case Intrinsic::x86_avx2_pmaxs_d:
11474   case Intrinsic::x86_sse41_pminsb:
11475   case Intrinsic::x86_sse2_pmins_w:
11476   case Intrinsic::x86_sse41_pminsd:
11477   case Intrinsic::x86_avx2_pmins_b:
11478   case Intrinsic::x86_avx2_pmins_w:
11479   case Intrinsic::x86_avx2_pmins_d: {
11480     unsigned Opcode;
11481     switch (IntNo) {
11482     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11483     case Intrinsic::x86_sse2_pmaxu_b:
11484     case Intrinsic::x86_sse41_pmaxuw:
11485     case Intrinsic::x86_sse41_pmaxud:
11486     case Intrinsic::x86_avx2_pmaxu_b:
11487     case Intrinsic::x86_avx2_pmaxu_w:
11488     case Intrinsic::x86_avx2_pmaxu_d:
11489       Opcode = X86ISD::UMAX;
11490       break;
11491     case Intrinsic::x86_sse2_pminu_b:
11492     case Intrinsic::x86_sse41_pminuw:
11493     case Intrinsic::x86_sse41_pminud:
11494     case Intrinsic::x86_avx2_pminu_b:
11495     case Intrinsic::x86_avx2_pminu_w:
11496     case Intrinsic::x86_avx2_pminu_d:
11497       Opcode = X86ISD::UMIN;
11498       break;
11499     case Intrinsic::x86_sse41_pmaxsb:
11500     case Intrinsic::x86_sse2_pmaxs_w:
11501     case Intrinsic::x86_sse41_pmaxsd:
11502     case Intrinsic::x86_avx2_pmaxs_b:
11503     case Intrinsic::x86_avx2_pmaxs_w:
11504     case Intrinsic::x86_avx2_pmaxs_d:
11505       Opcode = X86ISD::SMAX;
11506       break;
11507     case Intrinsic::x86_sse41_pminsb:
11508     case Intrinsic::x86_sse2_pmins_w:
11509     case Intrinsic::x86_sse41_pminsd:
11510     case Intrinsic::x86_avx2_pmins_b:
11511     case Intrinsic::x86_avx2_pmins_w:
11512     case Intrinsic::x86_avx2_pmins_d:
11513       Opcode = X86ISD::SMIN;
11514       break;
11515     }
11516     return DAG.getNode(Opcode, dl, Op.getValueType(),
11517                        Op.getOperand(1), Op.getOperand(2));
11518   }
11519
11520   // SSE/SSE2/AVX floating point max/min intrinsics.
11521   case Intrinsic::x86_sse_max_ps:
11522   case Intrinsic::x86_sse2_max_pd:
11523   case Intrinsic::x86_avx_max_ps_256:
11524   case Intrinsic::x86_avx_max_pd_256:
11525   case Intrinsic::x86_sse_min_ps:
11526   case Intrinsic::x86_sse2_min_pd:
11527   case Intrinsic::x86_avx_min_ps_256:
11528   case Intrinsic::x86_avx_min_pd_256: {
11529     unsigned Opcode;
11530     switch (IntNo) {
11531     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11532     case Intrinsic::x86_sse_max_ps:
11533     case Intrinsic::x86_sse2_max_pd:
11534     case Intrinsic::x86_avx_max_ps_256:
11535     case Intrinsic::x86_avx_max_pd_256:
11536       Opcode = X86ISD::FMAX;
11537       break;
11538     case Intrinsic::x86_sse_min_ps:
11539     case Intrinsic::x86_sse2_min_pd:
11540     case Intrinsic::x86_avx_min_ps_256:
11541     case Intrinsic::x86_avx_min_pd_256:
11542       Opcode = X86ISD::FMIN;
11543       break;
11544     }
11545     return DAG.getNode(Opcode, dl, Op.getValueType(),
11546                        Op.getOperand(1), Op.getOperand(2));
11547   }
11548
11549   // AVX2 variable shift intrinsics
11550   case Intrinsic::x86_avx2_psllv_d:
11551   case Intrinsic::x86_avx2_psllv_q:
11552   case Intrinsic::x86_avx2_psllv_d_256:
11553   case Intrinsic::x86_avx2_psllv_q_256:
11554   case Intrinsic::x86_avx2_psrlv_d:
11555   case Intrinsic::x86_avx2_psrlv_q:
11556   case Intrinsic::x86_avx2_psrlv_d_256:
11557   case Intrinsic::x86_avx2_psrlv_q_256:
11558   case Intrinsic::x86_avx2_psrav_d:
11559   case Intrinsic::x86_avx2_psrav_d_256: {
11560     unsigned Opcode;
11561     switch (IntNo) {
11562     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11563     case Intrinsic::x86_avx2_psllv_d:
11564     case Intrinsic::x86_avx2_psllv_q:
11565     case Intrinsic::x86_avx2_psllv_d_256:
11566     case Intrinsic::x86_avx2_psllv_q_256:
11567       Opcode = ISD::SHL;
11568       break;
11569     case Intrinsic::x86_avx2_psrlv_d:
11570     case Intrinsic::x86_avx2_psrlv_q:
11571     case Intrinsic::x86_avx2_psrlv_d_256:
11572     case Intrinsic::x86_avx2_psrlv_q_256:
11573       Opcode = ISD::SRL;
11574       break;
11575     case Intrinsic::x86_avx2_psrav_d:
11576     case Intrinsic::x86_avx2_psrav_d_256:
11577       Opcode = ISD::SRA;
11578       break;
11579     }
11580     return DAG.getNode(Opcode, dl, Op.getValueType(),
11581                        Op.getOperand(1), Op.getOperand(2));
11582   }
11583
11584   case Intrinsic::x86_ssse3_pshuf_b_128:
11585   case Intrinsic::x86_avx2_pshuf_b:
11586     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11587                        Op.getOperand(1), Op.getOperand(2));
11588
11589   case Intrinsic::x86_ssse3_psign_b_128:
11590   case Intrinsic::x86_ssse3_psign_w_128:
11591   case Intrinsic::x86_ssse3_psign_d_128:
11592   case Intrinsic::x86_avx2_psign_b:
11593   case Intrinsic::x86_avx2_psign_w:
11594   case Intrinsic::x86_avx2_psign_d:
11595     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11596                        Op.getOperand(1), Op.getOperand(2));
11597
11598   case Intrinsic::x86_sse41_insertps:
11599     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11600                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11601
11602   case Intrinsic::x86_avx_vperm2f128_ps_256:
11603   case Intrinsic::x86_avx_vperm2f128_pd_256:
11604   case Intrinsic::x86_avx_vperm2f128_si_256:
11605   case Intrinsic::x86_avx2_vperm2i128:
11606     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11607                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11608
11609   case Intrinsic::x86_avx2_permd:
11610   case Intrinsic::x86_avx2_permps:
11611     // Operands intentionally swapped. Mask is last operand to intrinsic,
11612     // but second operand for node/instruction.
11613     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11614                        Op.getOperand(2), Op.getOperand(1));
11615
11616   case Intrinsic::x86_sse_sqrt_ps:
11617   case Intrinsic::x86_sse2_sqrt_pd:
11618   case Intrinsic::x86_avx_sqrt_ps_256:
11619   case Intrinsic::x86_avx_sqrt_pd_256:
11620     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11621
11622   // ptest and testp intrinsics. The intrinsic these come from are designed to
11623   // return an integer value, not just an instruction so lower it to the ptest
11624   // or testp pattern and a setcc for the result.
11625   case Intrinsic::x86_sse41_ptestz:
11626   case Intrinsic::x86_sse41_ptestc:
11627   case Intrinsic::x86_sse41_ptestnzc:
11628   case Intrinsic::x86_avx_ptestz_256:
11629   case Intrinsic::x86_avx_ptestc_256:
11630   case Intrinsic::x86_avx_ptestnzc_256:
11631   case Intrinsic::x86_avx_vtestz_ps:
11632   case Intrinsic::x86_avx_vtestc_ps:
11633   case Intrinsic::x86_avx_vtestnzc_ps:
11634   case Intrinsic::x86_avx_vtestz_pd:
11635   case Intrinsic::x86_avx_vtestc_pd:
11636   case Intrinsic::x86_avx_vtestnzc_pd:
11637   case Intrinsic::x86_avx_vtestz_ps_256:
11638   case Intrinsic::x86_avx_vtestc_ps_256:
11639   case Intrinsic::x86_avx_vtestnzc_ps_256:
11640   case Intrinsic::x86_avx_vtestz_pd_256:
11641   case Intrinsic::x86_avx_vtestc_pd_256:
11642   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11643     bool IsTestPacked = false;
11644     unsigned X86CC;
11645     switch (IntNo) {
11646     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11647     case Intrinsic::x86_avx_vtestz_ps:
11648     case Intrinsic::x86_avx_vtestz_pd:
11649     case Intrinsic::x86_avx_vtestz_ps_256:
11650     case Intrinsic::x86_avx_vtestz_pd_256:
11651       IsTestPacked = true; // Fallthrough
11652     case Intrinsic::x86_sse41_ptestz:
11653     case Intrinsic::x86_avx_ptestz_256:
11654       // ZF = 1
11655       X86CC = X86::COND_E;
11656       break;
11657     case Intrinsic::x86_avx_vtestc_ps:
11658     case Intrinsic::x86_avx_vtestc_pd:
11659     case Intrinsic::x86_avx_vtestc_ps_256:
11660     case Intrinsic::x86_avx_vtestc_pd_256:
11661       IsTestPacked = true; // Fallthrough
11662     case Intrinsic::x86_sse41_ptestc:
11663     case Intrinsic::x86_avx_ptestc_256:
11664       // CF = 1
11665       X86CC = X86::COND_B;
11666       break;
11667     case Intrinsic::x86_avx_vtestnzc_ps:
11668     case Intrinsic::x86_avx_vtestnzc_pd:
11669     case Intrinsic::x86_avx_vtestnzc_ps_256:
11670     case Intrinsic::x86_avx_vtestnzc_pd_256:
11671       IsTestPacked = true; // Fallthrough
11672     case Intrinsic::x86_sse41_ptestnzc:
11673     case Intrinsic::x86_avx_ptestnzc_256:
11674       // ZF and CF = 0
11675       X86CC = X86::COND_A;
11676       break;
11677     }
11678
11679     SDValue LHS = Op.getOperand(1);
11680     SDValue RHS = Op.getOperand(2);
11681     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11682     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11683     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11684     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11685     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11686   }
11687   case Intrinsic::x86_avx512_kortestz_w:
11688   case Intrinsic::x86_avx512_kortestc_w: {
11689     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11690     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11691     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11692     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11693     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11694     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11695     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11696   }
11697
11698   // SSE/AVX shift intrinsics
11699   case Intrinsic::x86_sse2_psll_w:
11700   case Intrinsic::x86_sse2_psll_d:
11701   case Intrinsic::x86_sse2_psll_q:
11702   case Intrinsic::x86_avx2_psll_w:
11703   case Intrinsic::x86_avx2_psll_d:
11704   case Intrinsic::x86_avx2_psll_q:
11705   case Intrinsic::x86_sse2_psrl_w:
11706   case Intrinsic::x86_sse2_psrl_d:
11707   case Intrinsic::x86_sse2_psrl_q:
11708   case Intrinsic::x86_avx2_psrl_w:
11709   case Intrinsic::x86_avx2_psrl_d:
11710   case Intrinsic::x86_avx2_psrl_q:
11711   case Intrinsic::x86_sse2_psra_w:
11712   case Intrinsic::x86_sse2_psra_d:
11713   case Intrinsic::x86_avx2_psra_w:
11714   case Intrinsic::x86_avx2_psra_d: {
11715     unsigned Opcode;
11716     switch (IntNo) {
11717     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11718     case Intrinsic::x86_sse2_psll_w:
11719     case Intrinsic::x86_sse2_psll_d:
11720     case Intrinsic::x86_sse2_psll_q:
11721     case Intrinsic::x86_avx2_psll_w:
11722     case Intrinsic::x86_avx2_psll_d:
11723     case Intrinsic::x86_avx2_psll_q:
11724       Opcode = X86ISD::VSHL;
11725       break;
11726     case Intrinsic::x86_sse2_psrl_w:
11727     case Intrinsic::x86_sse2_psrl_d:
11728     case Intrinsic::x86_sse2_psrl_q:
11729     case Intrinsic::x86_avx2_psrl_w:
11730     case Intrinsic::x86_avx2_psrl_d:
11731     case Intrinsic::x86_avx2_psrl_q:
11732       Opcode = X86ISD::VSRL;
11733       break;
11734     case Intrinsic::x86_sse2_psra_w:
11735     case Intrinsic::x86_sse2_psra_d:
11736     case Intrinsic::x86_avx2_psra_w:
11737     case Intrinsic::x86_avx2_psra_d:
11738       Opcode = X86ISD::VSRA;
11739       break;
11740     }
11741     return DAG.getNode(Opcode, dl, Op.getValueType(),
11742                        Op.getOperand(1), Op.getOperand(2));
11743   }
11744
11745   // SSE/AVX immediate shift intrinsics
11746   case Intrinsic::x86_sse2_pslli_w:
11747   case Intrinsic::x86_sse2_pslli_d:
11748   case Intrinsic::x86_sse2_pslli_q:
11749   case Intrinsic::x86_avx2_pslli_w:
11750   case Intrinsic::x86_avx2_pslli_d:
11751   case Intrinsic::x86_avx2_pslli_q:
11752   case Intrinsic::x86_sse2_psrli_w:
11753   case Intrinsic::x86_sse2_psrli_d:
11754   case Intrinsic::x86_sse2_psrli_q:
11755   case Intrinsic::x86_avx2_psrli_w:
11756   case Intrinsic::x86_avx2_psrli_d:
11757   case Intrinsic::x86_avx2_psrli_q:
11758   case Intrinsic::x86_sse2_psrai_w:
11759   case Intrinsic::x86_sse2_psrai_d:
11760   case Intrinsic::x86_avx2_psrai_w:
11761   case Intrinsic::x86_avx2_psrai_d: {
11762     unsigned Opcode;
11763     switch (IntNo) {
11764     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11765     case Intrinsic::x86_sse2_pslli_w:
11766     case Intrinsic::x86_sse2_pslli_d:
11767     case Intrinsic::x86_sse2_pslli_q:
11768     case Intrinsic::x86_avx2_pslli_w:
11769     case Intrinsic::x86_avx2_pslli_d:
11770     case Intrinsic::x86_avx2_pslli_q:
11771       Opcode = X86ISD::VSHLI;
11772       break;
11773     case Intrinsic::x86_sse2_psrli_w:
11774     case Intrinsic::x86_sse2_psrli_d:
11775     case Intrinsic::x86_sse2_psrli_q:
11776     case Intrinsic::x86_avx2_psrli_w:
11777     case Intrinsic::x86_avx2_psrli_d:
11778     case Intrinsic::x86_avx2_psrli_q:
11779       Opcode = X86ISD::VSRLI;
11780       break;
11781     case Intrinsic::x86_sse2_psrai_w:
11782     case Intrinsic::x86_sse2_psrai_d:
11783     case Intrinsic::x86_avx2_psrai_w:
11784     case Intrinsic::x86_avx2_psrai_d:
11785       Opcode = X86ISD::VSRAI;
11786       break;
11787     }
11788     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11789                                Op.getOperand(1), Op.getOperand(2), DAG);
11790   }
11791
11792   case Intrinsic::x86_sse42_pcmpistria128:
11793   case Intrinsic::x86_sse42_pcmpestria128:
11794   case Intrinsic::x86_sse42_pcmpistric128:
11795   case Intrinsic::x86_sse42_pcmpestric128:
11796   case Intrinsic::x86_sse42_pcmpistrio128:
11797   case Intrinsic::x86_sse42_pcmpestrio128:
11798   case Intrinsic::x86_sse42_pcmpistris128:
11799   case Intrinsic::x86_sse42_pcmpestris128:
11800   case Intrinsic::x86_sse42_pcmpistriz128:
11801   case Intrinsic::x86_sse42_pcmpestriz128: {
11802     unsigned Opcode;
11803     unsigned X86CC;
11804     switch (IntNo) {
11805     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11806     case Intrinsic::x86_sse42_pcmpistria128:
11807       Opcode = X86ISD::PCMPISTRI;
11808       X86CC = X86::COND_A;
11809       break;
11810     case Intrinsic::x86_sse42_pcmpestria128:
11811       Opcode = X86ISD::PCMPESTRI;
11812       X86CC = X86::COND_A;
11813       break;
11814     case Intrinsic::x86_sse42_pcmpistric128:
11815       Opcode = X86ISD::PCMPISTRI;
11816       X86CC = X86::COND_B;
11817       break;
11818     case Intrinsic::x86_sse42_pcmpestric128:
11819       Opcode = X86ISD::PCMPESTRI;
11820       X86CC = X86::COND_B;
11821       break;
11822     case Intrinsic::x86_sse42_pcmpistrio128:
11823       Opcode = X86ISD::PCMPISTRI;
11824       X86CC = X86::COND_O;
11825       break;
11826     case Intrinsic::x86_sse42_pcmpestrio128:
11827       Opcode = X86ISD::PCMPESTRI;
11828       X86CC = X86::COND_O;
11829       break;
11830     case Intrinsic::x86_sse42_pcmpistris128:
11831       Opcode = X86ISD::PCMPISTRI;
11832       X86CC = X86::COND_S;
11833       break;
11834     case Intrinsic::x86_sse42_pcmpestris128:
11835       Opcode = X86ISD::PCMPESTRI;
11836       X86CC = X86::COND_S;
11837       break;
11838     case Intrinsic::x86_sse42_pcmpistriz128:
11839       Opcode = X86ISD::PCMPISTRI;
11840       X86CC = X86::COND_E;
11841       break;
11842     case Intrinsic::x86_sse42_pcmpestriz128:
11843       Opcode = X86ISD::PCMPESTRI;
11844       X86CC = X86::COND_E;
11845       break;
11846     }
11847     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11848     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11849     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11850     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11851                                 DAG.getConstant(X86CC, MVT::i8),
11852                                 SDValue(PCMP.getNode(), 1));
11853     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11854   }
11855
11856   case Intrinsic::x86_sse42_pcmpistri128:
11857   case Intrinsic::x86_sse42_pcmpestri128: {
11858     unsigned Opcode;
11859     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11860       Opcode = X86ISD::PCMPISTRI;
11861     else
11862       Opcode = X86ISD::PCMPESTRI;
11863
11864     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11865     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11866     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11867   }
11868   case Intrinsic::x86_fma_vfmadd_ps:
11869   case Intrinsic::x86_fma_vfmadd_pd:
11870   case Intrinsic::x86_fma_vfmsub_ps:
11871   case Intrinsic::x86_fma_vfmsub_pd:
11872   case Intrinsic::x86_fma_vfnmadd_ps:
11873   case Intrinsic::x86_fma_vfnmadd_pd:
11874   case Intrinsic::x86_fma_vfnmsub_ps:
11875   case Intrinsic::x86_fma_vfnmsub_pd:
11876   case Intrinsic::x86_fma_vfmaddsub_ps:
11877   case Intrinsic::x86_fma_vfmaddsub_pd:
11878   case Intrinsic::x86_fma_vfmsubadd_ps:
11879   case Intrinsic::x86_fma_vfmsubadd_pd:
11880   case Intrinsic::x86_fma_vfmadd_ps_256:
11881   case Intrinsic::x86_fma_vfmadd_pd_256:
11882   case Intrinsic::x86_fma_vfmsub_ps_256:
11883   case Intrinsic::x86_fma_vfmsub_pd_256:
11884   case Intrinsic::x86_fma_vfnmadd_ps_256:
11885   case Intrinsic::x86_fma_vfnmadd_pd_256:
11886   case Intrinsic::x86_fma_vfnmsub_ps_256:
11887   case Intrinsic::x86_fma_vfnmsub_pd_256:
11888   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11889   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11890   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11891   case Intrinsic::x86_fma_vfmsubadd_pd_256:
11892   case Intrinsic::x86_fma_vfmadd_ps_512:
11893   case Intrinsic::x86_fma_vfmadd_pd_512:
11894   case Intrinsic::x86_fma_vfmsub_ps_512:
11895   case Intrinsic::x86_fma_vfmsub_pd_512:
11896   case Intrinsic::x86_fma_vfnmadd_ps_512:
11897   case Intrinsic::x86_fma_vfnmadd_pd_512:
11898   case Intrinsic::x86_fma_vfnmsub_ps_512:
11899   case Intrinsic::x86_fma_vfnmsub_pd_512:
11900   case Intrinsic::x86_fma_vfmaddsub_ps_512:
11901   case Intrinsic::x86_fma_vfmaddsub_pd_512:
11902   case Intrinsic::x86_fma_vfmsubadd_ps_512:
11903   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11904     unsigned Opc;
11905     switch (IntNo) {
11906     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11907     case Intrinsic::x86_fma_vfmadd_ps:
11908     case Intrinsic::x86_fma_vfmadd_pd:
11909     case Intrinsic::x86_fma_vfmadd_ps_256:
11910     case Intrinsic::x86_fma_vfmadd_pd_256:
11911     case Intrinsic::x86_fma_vfmadd_ps_512:
11912     case Intrinsic::x86_fma_vfmadd_pd_512:
11913       Opc = X86ISD::FMADD;
11914       break;
11915     case Intrinsic::x86_fma_vfmsub_ps:
11916     case Intrinsic::x86_fma_vfmsub_pd:
11917     case Intrinsic::x86_fma_vfmsub_ps_256:
11918     case Intrinsic::x86_fma_vfmsub_pd_256:
11919     case Intrinsic::x86_fma_vfmsub_ps_512:
11920     case Intrinsic::x86_fma_vfmsub_pd_512:
11921       Opc = X86ISD::FMSUB;
11922       break;
11923     case Intrinsic::x86_fma_vfnmadd_ps:
11924     case Intrinsic::x86_fma_vfnmadd_pd:
11925     case Intrinsic::x86_fma_vfnmadd_ps_256:
11926     case Intrinsic::x86_fma_vfnmadd_pd_256:
11927     case Intrinsic::x86_fma_vfnmadd_ps_512:
11928     case Intrinsic::x86_fma_vfnmadd_pd_512:
11929       Opc = X86ISD::FNMADD;
11930       break;
11931     case Intrinsic::x86_fma_vfnmsub_ps:
11932     case Intrinsic::x86_fma_vfnmsub_pd:
11933     case Intrinsic::x86_fma_vfnmsub_ps_256:
11934     case Intrinsic::x86_fma_vfnmsub_pd_256:
11935     case Intrinsic::x86_fma_vfnmsub_ps_512:
11936     case Intrinsic::x86_fma_vfnmsub_pd_512:
11937       Opc = X86ISD::FNMSUB;
11938       break;
11939     case Intrinsic::x86_fma_vfmaddsub_ps:
11940     case Intrinsic::x86_fma_vfmaddsub_pd:
11941     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11942     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11943     case Intrinsic::x86_fma_vfmaddsub_ps_512:
11944     case Intrinsic::x86_fma_vfmaddsub_pd_512:
11945       Opc = X86ISD::FMADDSUB;
11946       break;
11947     case Intrinsic::x86_fma_vfmsubadd_ps:
11948     case Intrinsic::x86_fma_vfmsubadd_pd:
11949     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11950     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11951     case Intrinsic::x86_fma_vfmsubadd_ps_512:
11952     case Intrinsic::x86_fma_vfmsubadd_pd_512:
11953       Opc = X86ISD::FMSUBADD;
11954       break;
11955     }
11956
11957     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11958                        Op.getOperand(2), Op.getOperand(3));
11959   }
11960   }
11961 }
11962
11963 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11964                              SDValue Base, SDValue Index,
11965                              SDValue ScaleOp, SDValue Chain,
11966                              const X86Subtarget * Subtarget) {
11967   SDLoc dl(Op);
11968   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11969   assert(C && "Invalid scale type");
11970   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11971   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11972   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11973                              Index.getSimpleValueType().getVectorNumElements());
11974   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11975   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11976   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11977   SDValue Segment = DAG.getRegister(0, MVT::i32);
11978   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11979   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11980   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11981   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11982 }
11983
11984 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11985                               SDValue Src, SDValue Mask, SDValue Base,
11986                               SDValue Index, SDValue ScaleOp, SDValue Chain,
11987                               const X86Subtarget * Subtarget) {
11988   SDLoc dl(Op);
11989   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11990   assert(C && "Invalid scale type");
11991   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11992   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11993                              Index.getSimpleValueType().getVectorNumElements());
11994   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11995   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11996   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11997   SDValue Segment = DAG.getRegister(0, MVT::i32);
11998   if (Src.getOpcode() == ISD::UNDEF)
11999     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12000   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12001   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12002   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12003   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12004 }
12005
12006 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12007                               SDValue Src, SDValue Base, SDValue Index,
12008                               SDValue ScaleOp, SDValue Chain) {
12009   SDLoc dl(Op);
12010   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12011   assert(C && "Invalid scale type");
12012   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12013   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12014   SDValue Segment = DAG.getRegister(0, MVT::i32);
12015   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12016                              Index.getSimpleValueType().getVectorNumElements());
12017   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12018   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12019   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12020   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12021   return SDValue(Res, 1);
12022 }
12023
12024 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12025                                SDValue Src, SDValue Mask, SDValue Base,
12026                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12027   SDLoc dl(Op);
12028   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12029   assert(C && "Invalid scale type");
12030   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12031   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12032   SDValue Segment = DAG.getRegister(0, MVT::i32);
12033   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12034                              Index.getSimpleValueType().getVectorNumElements());
12035   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12036   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12037   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12038   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12039   return SDValue(Res, 1);
12040 }
12041
12042 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12043                                       SelectionDAG &DAG) {
12044   SDLoc dl(Op);
12045   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12046   switch (IntNo) {
12047   default: return SDValue();    // Don't custom lower most intrinsics.
12048
12049   // RDRAND/RDSEED intrinsics.
12050   case Intrinsic::x86_rdrand_16:
12051   case Intrinsic::x86_rdrand_32:
12052   case Intrinsic::x86_rdrand_64:
12053   case Intrinsic::x86_rdseed_16:
12054   case Intrinsic::x86_rdseed_32:
12055   case Intrinsic::x86_rdseed_64: {
12056     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12057                        IntNo == Intrinsic::x86_rdseed_32 ||
12058                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12059                                                             X86ISD::RDRAND;
12060     // Emit the node with the right value type.
12061     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12062     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12063
12064     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12065     // Otherwise return the value from Rand, which is always 0, casted to i32.
12066     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12067                       DAG.getConstant(1, Op->getValueType(1)),
12068                       DAG.getConstant(X86::COND_B, MVT::i32),
12069                       SDValue(Result.getNode(), 1) };
12070     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12071                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12072                                   Ops, array_lengthof(Ops));
12073
12074     // Return { result, isValid, chain }.
12075     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12076                        SDValue(Result.getNode(), 2));
12077   }
12078   //int_gather(index, base, scale);
12079   case Intrinsic::x86_avx512_gather_qpd_512:
12080   case Intrinsic::x86_avx512_gather_qps_512:
12081   case Intrinsic::x86_avx512_gather_dpd_512:
12082   case Intrinsic::x86_avx512_gather_qpi_512:
12083   case Intrinsic::x86_avx512_gather_qpq_512:
12084   case Intrinsic::x86_avx512_gather_dpq_512:
12085   case Intrinsic::x86_avx512_gather_dps_512:
12086   case Intrinsic::x86_avx512_gather_dpi_512: {
12087     unsigned Opc;
12088     switch (IntNo) {
12089     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12090     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12091     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12092     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12093     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12094     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12095     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12096     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12097     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12098     }
12099     SDValue Chain = Op.getOperand(0);
12100     SDValue Index = Op.getOperand(2);
12101     SDValue Base  = Op.getOperand(3);
12102     SDValue Scale = Op.getOperand(4);
12103     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12104   }
12105   //int_gather_mask(v1, mask, index, base, scale);
12106   case Intrinsic::x86_avx512_gather_qps_mask_512:
12107   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12108   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12109   case Intrinsic::x86_avx512_gather_dps_mask_512:
12110   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12111   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12112   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12113   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12114     unsigned Opc;
12115     switch (IntNo) {
12116     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12117     case Intrinsic::x86_avx512_gather_qps_mask_512:
12118       Opc = X86::VGATHERQPSZrm; break;
12119     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12120       Opc = X86::VGATHERQPDZrm; break;
12121     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12122       Opc = X86::VGATHERDPDZrm; break;
12123     case Intrinsic::x86_avx512_gather_dps_mask_512:
12124       Opc = X86::VGATHERDPSZrm; break;
12125     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12126       Opc = X86::VPGATHERQDZrm; break;
12127     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12128       Opc = X86::VPGATHERQQZrm; break;
12129     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12130       Opc = X86::VPGATHERDDZrm; break;
12131     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12132       Opc = X86::VPGATHERDQZrm; break;
12133     }
12134     SDValue Chain = Op.getOperand(0);
12135     SDValue Src   = Op.getOperand(2);
12136     SDValue Mask  = Op.getOperand(3);
12137     SDValue Index = Op.getOperand(4);
12138     SDValue Base  = Op.getOperand(5);
12139     SDValue Scale = Op.getOperand(6);
12140     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12141                           Subtarget);
12142   }
12143   //int_scatter(base, index, v1, scale);
12144   case Intrinsic::x86_avx512_scatter_qpd_512:
12145   case Intrinsic::x86_avx512_scatter_qps_512:
12146   case Intrinsic::x86_avx512_scatter_dpd_512:
12147   case Intrinsic::x86_avx512_scatter_qpi_512:
12148   case Intrinsic::x86_avx512_scatter_qpq_512:
12149   case Intrinsic::x86_avx512_scatter_dpq_512:
12150   case Intrinsic::x86_avx512_scatter_dps_512:
12151   case Intrinsic::x86_avx512_scatter_dpi_512: {
12152     unsigned Opc;
12153     switch (IntNo) {
12154     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12155     case Intrinsic::x86_avx512_scatter_qpd_512:
12156       Opc = X86::VSCATTERQPDZmr; break;
12157     case Intrinsic::x86_avx512_scatter_qps_512:
12158       Opc = X86::VSCATTERQPSZmr; break;
12159     case Intrinsic::x86_avx512_scatter_dpd_512:
12160       Opc = X86::VSCATTERDPDZmr; break;
12161     case Intrinsic::x86_avx512_scatter_dps_512:
12162       Opc = X86::VSCATTERDPSZmr; break;
12163     case Intrinsic::x86_avx512_scatter_qpi_512:
12164       Opc = X86::VPSCATTERQDZmr; break;
12165     case Intrinsic::x86_avx512_scatter_qpq_512:
12166       Opc = X86::VPSCATTERQQZmr; break;
12167     case Intrinsic::x86_avx512_scatter_dpq_512:
12168       Opc = X86::VPSCATTERDQZmr; break;
12169     case Intrinsic::x86_avx512_scatter_dpi_512:
12170       Opc = X86::VPSCATTERDDZmr; break;
12171     }
12172     SDValue Chain = Op.getOperand(0);
12173     SDValue Base  = Op.getOperand(2);
12174     SDValue Index = Op.getOperand(3);
12175     SDValue Src   = Op.getOperand(4);
12176     SDValue Scale = Op.getOperand(5);
12177     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12178   }
12179   //int_scatter_mask(base, mask, index, v1, scale);
12180   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12181   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12182   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12183   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12184   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12185   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12186   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12187   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12188     unsigned Opc;
12189     switch (IntNo) {
12190     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12191     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12192       Opc = X86::VSCATTERQPDZmr; break;
12193     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12194       Opc = X86::VSCATTERQPSZmr; break;
12195     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12196       Opc = X86::VSCATTERDPDZmr; break;
12197     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12198       Opc = X86::VSCATTERDPSZmr; break;
12199     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12200       Opc = X86::VPSCATTERQDZmr; break;
12201     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12202       Opc = X86::VPSCATTERQQZmr; break;
12203     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12204       Opc = X86::VPSCATTERDQZmr; break;
12205     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12206       Opc = X86::VPSCATTERDDZmr; break;
12207     }
12208     SDValue Chain = Op.getOperand(0);
12209     SDValue Base  = Op.getOperand(2);
12210     SDValue Mask  = Op.getOperand(3);
12211     SDValue Index = Op.getOperand(4);
12212     SDValue Src   = Op.getOperand(5);
12213     SDValue Scale = Op.getOperand(6);
12214     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12215   }
12216   // XTEST intrinsics.
12217   case Intrinsic::x86_xtest: {
12218     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12219     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12220     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12221                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12222                                 InTrans);
12223     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12224     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12225                        Ret, SDValue(InTrans.getNode(), 1));
12226   }
12227   }
12228 }
12229
12230 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12231                                            SelectionDAG &DAG) const {
12232   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12233   MFI->setReturnAddressIsTaken(true);
12234
12235   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12236     return SDValue();
12237
12238   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12239   SDLoc dl(Op);
12240   EVT PtrVT = getPointerTy();
12241
12242   if (Depth > 0) {
12243     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12244     const X86RegisterInfo *RegInfo =
12245       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12246     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12247     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12248                        DAG.getNode(ISD::ADD, dl, PtrVT,
12249                                    FrameAddr, Offset),
12250                        MachinePointerInfo(), false, false, false, 0);
12251   }
12252
12253   // Just load the return address.
12254   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12255   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12256                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12257 }
12258
12259 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12260   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12261   MFI->setFrameAddressIsTaken(true);
12262
12263   EVT VT = Op.getValueType();
12264   SDLoc dl(Op);  // FIXME probably not meaningful
12265   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12266   const X86RegisterInfo *RegInfo =
12267     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12268   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12269   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12270           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12271          "Invalid Frame Register!");
12272   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12273   while (Depth--)
12274     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12275                             MachinePointerInfo(),
12276                             false, false, false, 0);
12277   return FrameAddr;
12278 }
12279
12280 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12281                                                      SelectionDAG &DAG) const {
12282   const X86RegisterInfo *RegInfo =
12283     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12284   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12285 }
12286
12287 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12288   SDValue Chain     = Op.getOperand(0);
12289   SDValue Offset    = Op.getOperand(1);
12290   SDValue Handler   = Op.getOperand(2);
12291   SDLoc dl      (Op);
12292
12293   EVT PtrVT = getPointerTy();
12294   const X86RegisterInfo *RegInfo =
12295     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12296   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12297   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12298           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12299          "Invalid Frame Register!");
12300   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12301   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12302
12303   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12304                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12305   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12306   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12307                        false, false, 0);
12308   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12309
12310   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12311                      DAG.getRegister(StoreAddrReg, PtrVT));
12312 }
12313
12314 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12315                                                SelectionDAG &DAG) const {
12316   SDLoc DL(Op);
12317   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12318                      DAG.getVTList(MVT::i32, MVT::Other),
12319                      Op.getOperand(0), Op.getOperand(1));
12320 }
12321
12322 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12323                                                 SelectionDAG &DAG) const {
12324   SDLoc DL(Op);
12325   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12326                      Op.getOperand(0), Op.getOperand(1));
12327 }
12328
12329 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12330   return Op.getOperand(0);
12331 }
12332
12333 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12334                                                 SelectionDAG &DAG) const {
12335   SDValue Root = Op.getOperand(0);
12336   SDValue Trmp = Op.getOperand(1); // trampoline
12337   SDValue FPtr = Op.getOperand(2); // nested function
12338   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12339   SDLoc dl (Op);
12340
12341   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12342   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12343
12344   if (Subtarget->is64Bit()) {
12345     SDValue OutChains[6];
12346
12347     // Large code-model.
12348     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12349     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12350
12351     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12352     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12353
12354     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12355
12356     // Load the pointer to the nested function into R11.
12357     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12358     SDValue Addr = Trmp;
12359     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12360                                 Addr, MachinePointerInfo(TrmpAddr),
12361                                 false, false, 0);
12362
12363     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12364                        DAG.getConstant(2, MVT::i64));
12365     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12366                                 MachinePointerInfo(TrmpAddr, 2),
12367                                 false, false, 2);
12368
12369     // Load the 'nest' parameter value into R10.
12370     // R10 is specified in X86CallingConv.td
12371     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12372     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12373                        DAG.getConstant(10, MVT::i64));
12374     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12375                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12376                                 false, false, 0);
12377
12378     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12379                        DAG.getConstant(12, MVT::i64));
12380     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12381                                 MachinePointerInfo(TrmpAddr, 12),
12382                                 false, false, 2);
12383
12384     // Jump to the nested function.
12385     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12386     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12387                        DAG.getConstant(20, MVT::i64));
12388     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12389                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12390                                 false, false, 0);
12391
12392     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12393     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12394                        DAG.getConstant(22, MVT::i64));
12395     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12396                                 MachinePointerInfo(TrmpAddr, 22),
12397                                 false, false, 0);
12398
12399     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12400   } else {
12401     const Function *Func =
12402       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12403     CallingConv::ID CC = Func->getCallingConv();
12404     unsigned NestReg;
12405
12406     switch (CC) {
12407     default:
12408       llvm_unreachable("Unsupported calling convention");
12409     case CallingConv::C:
12410     case CallingConv::X86_StdCall: {
12411       // Pass 'nest' parameter in ECX.
12412       // Must be kept in sync with X86CallingConv.td
12413       NestReg = X86::ECX;
12414
12415       // Check that ECX wasn't needed by an 'inreg' parameter.
12416       FunctionType *FTy = Func->getFunctionType();
12417       const AttributeSet &Attrs = Func->getAttributes();
12418
12419       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12420         unsigned InRegCount = 0;
12421         unsigned Idx = 1;
12422
12423         for (FunctionType::param_iterator I = FTy->param_begin(),
12424              E = FTy->param_end(); I != E; ++I, ++Idx)
12425           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12426             // FIXME: should only count parameters that are lowered to integers.
12427             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12428
12429         if (InRegCount > 2) {
12430           report_fatal_error("Nest register in use - reduce number of inreg"
12431                              " parameters!");
12432         }
12433       }
12434       break;
12435     }
12436     case CallingConv::X86_FastCall:
12437     case CallingConv::X86_ThisCall:
12438     case CallingConv::Fast:
12439       // Pass 'nest' parameter in EAX.
12440       // Must be kept in sync with X86CallingConv.td
12441       NestReg = X86::EAX;
12442       break;
12443     }
12444
12445     SDValue OutChains[4];
12446     SDValue Addr, Disp;
12447
12448     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12449                        DAG.getConstant(10, MVT::i32));
12450     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12451
12452     // This is storing the opcode for MOV32ri.
12453     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12454     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12455     OutChains[0] = DAG.getStore(Root, dl,
12456                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12457                                 Trmp, MachinePointerInfo(TrmpAddr),
12458                                 false, false, 0);
12459
12460     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12461                        DAG.getConstant(1, MVT::i32));
12462     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12463                                 MachinePointerInfo(TrmpAddr, 1),
12464                                 false, false, 1);
12465
12466     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12467     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12468                        DAG.getConstant(5, MVT::i32));
12469     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12470                                 MachinePointerInfo(TrmpAddr, 5),
12471                                 false, false, 1);
12472
12473     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12474                        DAG.getConstant(6, MVT::i32));
12475     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12476                                 MachinePointerInfo(TrmpAddr, 6),
12477                                 false, false, 1);
12478
12479     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12480   }
12481 }
12482
12483 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12484                                             SelectionDAG &DAG) const {
12485   /*
12486    The rounding mode is in bits 11:10 of FPSR, and has the following
12487    settings:
12488      00 Round to nearest
12489      01 Round to -inf
12490      10 Round to +inf
12491      11 Round to 0
12492
12493   FLT_ROUNDS, on the other hand, expects the following:
12494     -1 Undefined
12495      0 Round to 0
12496      1 Round to nearest
12497      2 Round to +inf
12498      3 Round to -inf
12499
12500   To perform the conversion, we do:
12501     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12502   */
12503
12504   MachineFunction &MF = DAG.getMachineFunction();
12505   const TargetMachine &TM = MF.getTarget();
12506   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12507   unsigned StackAlignment = TFI.getStackAlignment();
12508   MVT VT = Op.getSimpleValueType();
12509   SDLoc DL(Op);
12510
12511   // Save FP Control Word to stack slot
12512   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12513   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12514
12515   MachineMemOperand *MMO =
12516    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12517                            MachineMemOperand::MOStore, 2, 2);
12518
12519   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12520   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12521                                           DAG.getVTList(MVT::Other),
12522                                           Ops, array_lengthof(Ops), MVT::i16,
12523                                           MMO);
12524
12525   // Load FP Control Word from stack slot
12526   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12527                             MachinePointerInfo(), false, false, false, 0);
12528
12529   // Transform as necessary
12530   SDValue CWD1 =
12531     DAG.getNode(ISD::SRL, DL, MVT::i16,
12532                 DAG.getNode(ISD::AND, DL, MVT::i16,
12533                             CWD, DAG.getConstant(0x800, MVT::i16)),
12534                 DAG.getConstant(11, MVT::i8));
12535   SDValue CWD2 =
12536     DAG.getNode(ISD::SRL, DL, MVT::i16,
12537                 DAG.getNode(ISD::AND, DL, MVT::i16,
12538                             CWD, DAG.getConstant(0x400, MVT::i16)),
12539                 DAG.getConstant(9, MVT::i8));
12540
12541   SDValue RetVal =
12542     DAG.getNode(ISD::AND, DL, MVT::i16,
12543                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12544                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12545                             DAG.getConstant(1, MVT::i16)),
12546                 DAG.getConstant(3, MVT::i16));
12547
12548   return DAG.getNode((VT.getSizeInBits() < 16 ?
12549                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12550 }
12551
12552 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12553   MVT VT = Op.getSimpleValueType();
12554   EVT OpVT = VT;
12555   unsigned NumBits = VT.getSizeInBits();
12556   SDLoc dl(Op);
12557
12558   Op = Op.getOperand(0);
12559   if (VT == MVT::i8) {
12560     // Zero extend to i32 since there is not an i8 bsr.
12561     OpVT = MVT::i32;
12562     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12563   }
12564
12565   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12566   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12567   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12568
12569   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12570   SDValue Ops[] = {
12571     Op,
12572     DAG.getConstant(NumBits+NumBits-1, OpVT),
12573     DAG.getConstant(X86::COND_E, MVT::i8),
12574     Op.getValue(1)
12575   };
12576   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12577
12578   // Finally xor with NumBits-1.
12579   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12580
12581   if (VT == MVT::i8)
12582     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12583   return Op;
12584 }
12585
12586 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12587   MVT VT = Op.getSimpleValueType();
12588   EVT OpVT = VT;
12589   unsigned NumBits = VT.getSizeInBits();
12590   SDLoc dl(Op);
12591
12592   Op = Op.getOperand(0);
12593   if (VT == MVT::i8) {
12594     // Zero extend to i32 since there is not an i8 bsr.
12595     OpVT = MVT::i32;
12596     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12597   }
12598
12599   // Issue a bsr (scan bits in reverse).
12600   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12601   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12602
12603   // And xor with NumBits-1.
12604   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12605
12606   if (VT == MVT::i8)
12607     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12608   return Op;
12609 }
12610
12611 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12612   MVT VT = Op.getSimpleValueType();
12613   unsigned NumBits = VT.getSizeInBits();
12614   SDLoc dl(Op);
12615   Op = Op.getOperand(0);
12616
12617   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12618   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12619   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12620
12621   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12622   SDValue Ops[] = {
12623     Op,
12624     DAG.getConstant(NumBits, VT),
12625     DAG.getConstant(X86::COND_E, MVT::i8),
12626     Op.getValue(1)
12627   };
12628   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12629 }
12630
12631 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12632 // ones, and then concatenate the result back.
12633 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12634   MVT VT = Op.getSimpleValueType();
12635
12636   assert(VT.is256BitVector() && VT.isInteger() &&
12637          "Unsupported value type for operation");
12638
12639   unsigned NumElems = VT.getVectorNumElements();
12640   SDLoc dl(Op);
12641
12642   // Extract the LHS vectors
12643   SDValue LHS = Op.getOperand(0);
12644   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12645   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12646
12647   // Extract the RHS vectors
12648   SDValue RHS = Op.getOperand(1);
12649   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12650   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12651
12652   MVT EltVT = VT.getVectorElementType();
12653   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12654
12655   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12656                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12657                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12658 }
12659
12660 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12661   assert(Op.getSimpleValueType().is256BitVector() &&
12662          Op.getSimpleValueType().isInteger() &&
12663          "Only handle AVX 256-bit vector integer operation");
12664   return Lower256IntArith(Op, DAG);
12665 }
12666
12667 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12668   assert(Op.getSimpleValueType().is256BitVector() &&
12669          Op.getSimpleValueType().isInteger() &&
12670          "Only handle AVX 256-bit vector integer operation");
12671   return Lower256IntArith(Op, DAG);
12672 }
12673
12674 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12675                         SelectionDAG &DAG) {
12676   SDLoc dl(Op);
12677   MVT VT = Op.getSimpleValueType();
12678
12679   // Decompose 256-bit ops into smaller 128-bit ops.
12680   if (VT.is256BitVector() && !Subtarget->hasInt256())
12681     return Lower256IntArith(Op, DAG);
12682
12683   SDValue A = Op.getOperand(0);
12684   SDValue B = Op.getOperand(1);
12685
12686   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12687   if (VT == MVT::v4i32) {
12688     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12689            "Should not custom lower when pmuldq is available!");
12690
12691     // Extract the odd parts.
12692     static const int UnpackMask[] = { 1, -1, 3, -1 };
12693     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12694     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12695
12696     // Multiply the even parts.
12697     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12698     // Now multiply odd parts.
12699     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12700
12701     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12702     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12703
12704     // Merge the two vectors back together with a shuffle. This expands into 2
12705     // shuffles.
12706     static const int ShufMask[] = { 0, 4, 2, 6 };
12707     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12708   }
12709
12710   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12711          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12712
12713   //  Ahi = psrlqi(a, 32);
12714   //  Bhi = psrlqi(b, 32);
12715   //
12716   //  AloBlo = pmuludq(a, b);
12717   //  AloBhi = pmuludq(a, Bhi);
12718   //  AhiBlo = pmuludq(Ahi, b);
12719
12720   //  AloBhi = psllqi(AloBhi, 32);
12721   //  AhiBlo = psllqi(AhiBlo, 32);
12722   //  return AloBlo + AloBhi + AhiBlo;
12723
12724   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12725   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12726
12727   // Bit cast to 32-bit vectors for MULUDQ
12728   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12729                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12730   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12731   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12732   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12733   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12734
12735   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12736   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12737   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12738
12739   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12740   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12741
12742   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12743   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12744 }
12745
12746 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12747   MVT VT = Op.getSimpleValueType();
12748   MVT EltTy = VT.getVectorElementType();
12749   unsigned NumElts = VT.getVectorNumElements();
12750   SDValue N0 = Op.getOperand(0);
12751   SDLoc dl(Op);
12752
12753   // Lower sdiv X, pow2-const.
12754   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12755   if (!C)
12756     return SDValue();
12757
12758   APInt SplatValue, SplatUndef;
12759   unsigned SplatBitSize;
12760   bool HasAnyUndefs;
12761   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12762                           HasAnyUndefs) ||
12763       EltTy.getSizeInBits() < SplatBitSize)
12764     return SDValue();
12765
12766   if ((SplatValue != 0) &&
12767       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12768     unsigned Lg2 = SplatValue.countTrailingZeros();
12769     // Splat the sign bit.
12770     SmallVector<SDValue, 16> Sz(NumElts,
12771                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12772                                                 EltTy));
12773     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12774                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12775                                           NumElts));
12776     // Add (N0 < 0) ? abs2 - 1 : 0;
12777     SmallVector<SDValue, 16> Amt(NumElts,
12778                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12779                                                  EltTy));
12780     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12781                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12782                                           NumElts));
12783     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12784     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12785     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12786                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12787                                           NumElts));
12788
12789     // If we're dividing by a positive value, we're done.  Otherwise, we must
12790     // negate the result.
12791     if (SplatValue.isNonNegative())
12792       return SRA;
12793
12794     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12795     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12796     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12797   }
12798   return SDValue();
12799 }
12800
12801 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12802                                          const X86Subtarget *Subtarget) {
12803   MVT VT = Op.getSimpleValueType();
12804   SDLoc dl(Op);
12805   SDValue R = Op.getOperand(0);
12806   SDValue Amt = Op.getOperand(1);
12807
12808   // Optimize shl/srl/sra with constant shift amount.
12809   if (isSplatVector(Amt.getNode())) {
12810     SDValue SclrAmt = Amt->getOperand(0);
12811     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12812       uint64_t ShiftAmt = C->getZExtValue();
12813
12814       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12815           (Subtarget->hasInt256() &&
12816            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12817           (Subtarget->hasAVX512() &&
12818            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12819         if (Op.getOpcode() == ISD::SHL)
12820           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12821                                             DAG);
12822         if (Op.getOpcode() == ISD::SRL)
12823           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12824                                             DAG);
12825         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12826           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12827                                             DAG);
12828       }
12829
12830       if (VT == MVT::v16i8) {
12831         if (Op.getOpcode() == ISD::SHL) {
12832           // Make a large shift.
12833           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12834                                                    MVT::v8i16, R, ShiftAmt,
12835                                                    DAG);
12836           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12837           // Zero out the rightmost bits.
12838           SmallVector<SDValue, 16> V(16,
12839                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12840                                                      MVT::i8));
12841           return DAG.getNode(ISD::AND, dl, VT, SHL,
12842                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12843         }
12844         if (Op.getOpcode() == ISD::SRL) {
12845           // Make a large shift.
12846           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12847                                                    MVT::v8i16, R, ShiftAmt,
12848                                                    DAG);
12849           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12850           // Zero out the leftmost bits.
12851           SmallVector<SDValue, 16> V(16,
12852                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12853                                                      MVT::i8));
12854           return DAG.getNode(ISD::AND, dl, VT, SRL,
12855                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12856         }
12857         if (Op.getOpcode() == ISD::SRA) {
12858           if (ShiftAmt == 7) {
12859             // R s>> 7  ===  R s< 0
12860             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12861             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12862           }
12863
12864           // R s>> a === ((R u>> a) ^ m) - m
12865           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12866           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12867                                                          MVT::i8));
12868           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12869           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12870           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12871           return Res;
12872         }
12873         llvm_unreachable("Unknown shift opcode.");
12874       }
12875
12876       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12877         if (Op.getOpcode() == ISD::SHL) {
12878           // Make a large shift.
12879           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12880                                                    MVT::v16i16, R, ShiftAmt,
12881                                                    DAG);
12882           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12883           // Zero out the rightmost bits.
12884           SmallVector<SDValue, 32> V(32,
12885                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12886                                                      MVT::i8));
12887           return DAG.getNode(ISD::AND, dl, VT, SHL,
12888                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12889         }
12890         if (Op.getOpcode() == ISD::SRL) {
12891           // Make a large shift.
12892           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12893                                                    MVT::v16i16, R, ShiftAmt,
12894                                                    DAG);
12895           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12896           // Zero out the leftmost bits.
12897           SmallVector<SDValue, 32> V(32,
12898                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12899                                                      MVT::i8));
12900           return DAG.getNode(ISD::AND, dl, VT, SRL,
12901                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12902         }
12903         if (Op.getOpcode() == ISD::SRA) {
12904           if (ShiftAmt == 7) {
12905             // R s>> 7  ===  R s< 0
12906             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12907             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12908           }
12909
12910           // R s>> a === ((R u>> a) ^ m) - m
12911           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12912           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12913                                                          MVT::i8));
12914           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12915           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12916           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12917           return Res;
12918         }
12919         llvm_unreachable("Unknown shift opcode.");
12920       }
12921     }
12922   }
12923
12924   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12925   if (!Subtarget->is64Bit() &&
12926       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12927       Amt.getOpcode() == ISD::BITCAST &&
12928       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12929     Amt = Amt.getOperand(0);
12930     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
12931                      VT.getVectorNumElements();
12932     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12933     uint64_t ShiftAmt = 0;
12934     for (unsigned i = 0; i != Ratio; ++i) {
12935       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12936       if (C == 0)
12937         return SDValue();
12938       // 6 == Log2(64)
12939       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12940     }
12941     // Check remaining shift amounts.
12942     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12943       uint64_t ShAmt = 0;
12944       for (unsigned j = 0; j != Ratio; ++j) {
12945         ConstantSDNode *C =
12946           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12947         if (C == 0)
12948           return SDValue();
12949         // 6 == Log2(64)
12950         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12951       }
12952       if (ShAmt != ShiftAmt)
12953         return SDValue();
12954     }
12955     switch (Op.getOpcode()) {
12956     default:
12957       llvm_unreachable("Unknown shift opcode!");
12958     case ISD::SHL:
12959       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12960                                         DAG);
12961     case ISD::SRL:
12962       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12963                                         DAG);
12964     case ISD::SRA:
12965       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12966                                         DAG);
12967     }
12968   }
12969
12970   return SDValue();
12971 }
12972
12973 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12974                                         const X86Subtarget* Subtarget) {
12975   MVT VT = Op.getSimpleValueType();
12976   SDLoc dl(Op);
12977   SDValue R = Op.getOperand(0);
12978   SDValue Amt = Op.getOperand(1);
12979
12980   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12981       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12982       (Subtarget->hasInt256() &&
12983        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12984         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12985        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12986     SDValue BaseShAmt;
12987     EVT EltVT = VT.getVectorElementType();
12988
12989     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12990       unsigned NumElts = VT.getVectorNumElements();
12991       unsigned i, j;
12992       for (i = 0; i != NumElts; ++i) {
12993         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12994           continue;
12995         break;
12996       }
12997       for (j = i; j != NumElts; ++j) {
12998         SDValue Arg = Amt.getOperand(j);
12999         if (Arg.getOpcode() == ISD::UNDEF) continue;
13000         if (Arg != Amt.getOperand(i))
13001           break;
13002       }
13003       if (i != NumElts && j == NumElts)
13004         BaseShAmt = Amt.getOperand(i);
13005     } else {
13006       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13007         Amt = Amt.getOperand(0);
13008       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13009                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13010         SDValue InVec = Amt.getOperand(0);
13011         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13012           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13013           unsigned i = 0;
13014           for (; i != NumElts; ++i) {
13015             SDValue Arg = InVec.getOperand(i);
13016             if (Arg.getOpcode() == ISD::UNDEF) continue;
13017             BaseShAmt = Arg;
13018             break;
13019           }
13020         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13021            if (ConstantSDNode *C =
13022                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13023              unsigned SplatIdx =
13024                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13025              if (C->getZExtValue() == SplatIdx)
13026                BaseShAmt = InVec.getOperand(1);
13027            }
13028         }
13029         if (BaseShAmt.getNode() == 0)
13030           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13031                                   DAG.getIntPtrConstant(0));
13032       }
13033     }
13034
13035     if (BaseShAmt.getNode()) {
13036       if (EltVT.bitsGT(MVT::i32))
13037         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13038       else if (EltVT.bitsLT(MVT::i32))
13039         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13040
13041       switch (Op.getOpcode()) {
13042       default:
13043         llvm_unreachable("Unknown shift opcode!");
13044       case ISD::SHL:
13045         switch (VT.SimpleTy) {
13046         default: return SDValue();
13047         case MVT::v2i64:
13048         case MVT::v4i32:
13049         case MVT::v8i16:
13050         case MVT::v4i64:
13051         case MVT::v8i32:
13052         case MVT::v16i16:
13053         case MVT::v16i32:
13054         case MVT::v8i64:
13055           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13056         }
13057       case ISD::SRA:
13058         switch (VT.SimpleTy) {
13059         default: return SDValue();
13060         case MVT::v4i32:
13061         case MVT::v8i16:
13062         case MVT::v8i32:
13063         case MVT::v16i16:
13064         case MVT::v16i32:
13065         case MVT::v8i64:
13066           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13067         }
13068       case ISD::SRL:
13069         switch (VT.SimpleTy) {
13070         default: return SDValue();
13071         case MVT::v2i64:
13072         case MVT::v4i32:
13073         case MVT::v8i16:
13074         case MVT::v4i64:
13075         case MVT::v8i32:
13076         case MVT::v16i16:
13077         case MVT::v16i32:
13078         case MVT::v8i64:
13079           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13080         }
13081       }
13082     }
13083   }
13084
13085   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13086   if (!Subtarget->is64Bit() &&
13087       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13088       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13089       Amt.getOpcode() == ISD::BITCAST &&
13090       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13091     Amt = Amt.getOperand(0);
13092     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13093                      VT.getVectorNumElements();
13094     std::vector<SDValue> Vals(Ratio);
13095     for (unsigned i = 0; i != Ratio; ++i)
13096       Vals[i] = Amt.getOperand(i);
13097     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13098       for (unsigned j = 0; j != Ratio; ++j)
13099         if (Vals[j] != Amt.getOperand(i + j))
13100           return SDValue();
13101     }
13102     switch (Op.getOpcode()) {
13103     default:
13104       llvm_unreachable("Unknown shift opcode!");
13105     case ISD::SHL:
13106       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13107     case ISD::SRL:
13108       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13109     case ISD::SRA:
13110       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13111     }
13112   }
13113
13114   return SDValue();
13115 }
13116
13117 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13118                           SelectionDAG &DAG) {
13119
13120   MVT VT = Op.getSimpleValueType();
13121   SDLoc dl(Op);
13122   SDValue R = Op.getOperand(0);
13123   SDValue Amt = Op.getOperand(1);
13124   SDValue V;
13125
13126   if (!Subtarget->hasSSE2())
13127     return SDValue();
13128
13129   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13130   if (V.getNode())
13131     return V;
13132
13133   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13134   if (V.getNode())
13135       return V;
13136
13137   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13138     return Op;
13139   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13140   if (Subtarget->hasInt256()) {
13141     if (Op.getOpcode() == ISD::SRL &&
13142         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13143          VT == MVT::v4i64 || VT == MVT::v8i32))
13144       return Op;
13145     if (Op.getOpcode() == ISD::SHL &&
13146         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13147          VT == MVT::v4i64 || VT == MVT::v8i32))
13148       return Op;
13149     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13150       return Op;
13151   }
13152
13153   // Lower SHL with variable shift amount.
13154   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13155     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13156
13157     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13158     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13159     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13160     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13161   }
13162   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13163     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13164
13165     // a = a << 5;
13166     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13167     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13168
13169     // Turn 'a' into a mask suitable for VSELECT
13170     SDValue VSelM = DAG.getConstant(0x80, VT);
13171     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13172     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13173
13174     SDValue CM1 = DAG.getConstant(0x0f, VT);
13175     SDValue CM2 = DAG.getConstant(0x3f, VT);
13176
13177     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13178     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13179     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13180     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13181     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13182
13183     // a += a
13184     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13185     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13186     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13187
13188     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13189     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13190     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13191     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13192     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13193
13194     // a += a
13195     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13196     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13197     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13198
13199     // return VSELECT(r, r+r, a);
13200     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13201                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13202     return R;
13203   }
13204
13205   // Decompose 256-bit shifts into smaller 128-bit shifts.
13206   if (VT.is256BitVector()) {
13207     unsigned NumElems = VT.getVectorNumElements();
13208     MVT EltVT = VT.getVectorElementType();
13209     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13210
13211     // Extract the two vectors
13212     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13213     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13214
13215     // Recreate the shift amount vectors
13216     SDValue Amt1, Amt2;
13217     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13218       // Constant shift amount
13219       SmallVector<SDValue, 4> Amt1Csts;
13220       SmallVector<SDValue, 4> Amt2Csts;
13221       for (unsigned i = 0; i != NumElems/2; ++i)
13222         Amt1Csts.push_back(Amt->getOperand(i));
13223       for (unsigned i = NumElems/2; i != NumElems; ++i)
13224         Amt2Csts.push_back(Amt->getOperand(i));
13225
13226       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13227                                  &Amt1Csts[0], NumElems/2);
13228       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13229                                  &Amt2Csts[0], NumElems/2);
13230     } else {
13231       // Variable shift amount
13232       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13233       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13234     }
13235
13236     // Issue new vector shifts for the smaller types
13237     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13238     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13239
13240     // Concatenate the result back
13241     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13242   }
13243
13244   return SDValue();
13245 }
13246
13247 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13248   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13249   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13250   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13251   // has only one use.
13252   SDNode *N = Op.getNode();
13253   SDValue LHS = N->getOperand(0);
13254   SDValue RHS = N->getOperand(1);
13255   unsigned BaseOp = 0;
13256   unsigned Cond = 0;
13257   SDLoc DL(Op);
13258   switch (Op.getOpcode()) {
13259   default: llvm_unreachable("Unknown ovf instruction!");
13260   case ISD::SADDO:
13261     // A subtract of one will be selected as a INC. Note that INC doesn't
13262     // set CF, so we can't do this for UADDO.
13263     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13264       if (C->isOne()) {
13265         BaseOp = X86ISD::INC;
13266         Cond = X86::COND_O;
13267         break;
13268       }
13269     BaseOp = X86ISD::ADD;
13270     Cond = X86::COND_O;
13271     break;
13272   case ISD::UADDO:
13273     BaseOp = X86ISD::ADD;
13274     Cond = X86::COND_B;
13275     break;
13276   case ISD::SSUBO:
13277     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13278     // set CF, so we can't do this for USUBO.
13279     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13280       if (C->isOne()) {
13281         BaseOp = X86ISD::DEC;
13282         Cond = X86::COND_O;
13283         break;
13284       }
13285     BaseOp = X86ISD::SUB;
13286     Cond = X86::COND_O;
13287     break;
13288   case ISD::USUBO:
13289     BaseOp = X86ISD::SUB;
13290     Cond = X86::COND_B;
13291     break;
13292   case ISD::SMULO:
13293     BaseOp = X86ISD::SMUL;
13294     Cond = X86::COND_O;
13295     break;
13296   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13297     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13298                                  MVT::i32);
13299     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13300
13301     SDValue SetCC =
13302       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13303                   DAG.getConstant(X86::COND_O, MVT::i32),
13304                   SDValue(Sum.getNode(), 2));
13305
13306     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13307   }
13308   }
13309
13310   // Also sets EFLAGS.
13311   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13312   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13313
13314   SDValue SetCC =
13315     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13316                 DAG.getConstant(Cond, MVT::i32),
13317                 SDValue(Sum.getNode(), 1));
13318
13319   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13320 }
13321
13322 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13323                                                   SelectionDAG &DAG) const {
13324   SDLoc dl(Op);
13325   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13326   MVT VT = Op.getSimpleValueType();
13327
13328   if (!Subtarget->hasSSE2() || !VT.isVector())
13329     return SDValue();
13330
13331   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13332                       ExtraVT.getScalarType().getSizeInBits();
13333
13334   switch (VT.SimpleTy) {
13335     default: return SDValue();
13336     case MVT::v8i32:
13337     case MVT::v16i16:
13338       if (!Subtarget->hasFp256())
13339         return SDValue();
13340       if (!Subtarget->hasInt256()) {
13341         // needs to be split
13342         unsigned NumElems = VT.getVectorNumElements();
13343
13344         // Extract the LHS vectors
13345         SDValue LHS = Op.getOperand(0);
13346         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13347         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13348
13349         MVT EltVT = VT.getVectorElementType();
13350         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13351
13352         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13353         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13354         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13355                                    ExtraNumElems/2);
13356         SDValue Extra = DAG.getValueType(ExtraVT);
13357
13358         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13359         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13360
13361         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13362       }
13363       // fall through
13364     case MVT::v4i32:
13365     case MVT::v8i16: {
13366       SDValue Op0 = Op.getOperand(0);
13367       SDValue Op00 = Op0.getOperand(0);
13368       SDValue Tmp1;
13369       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13370       if (Op0.getOpcode() == ISD::BITCAST &&
13371           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13372         // (sext (vzext x)) -> (vsext x)
13373         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13374         if (Tmp1.getNode()) {
13375           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13376           // This folding is only valid when the in-reg type is a vector of i8,
13377           // i16, or i32.
13378           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13379               ExtraEltVT == MVT::i32) {
13380             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13381             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13382                    "This optimization is invalid without a VZEXT.");
13383             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13384           }
13385           Op0 = Tmp1;
13386         }
13387       }
13388
13389       // If the above didn't work, then just use Shift-Left + Shift-Right.
13390       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13391                                         DAG);
13392       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13393                                         DAG);
13394     }
13395   }
13396 }
13397
13398 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13399                                  SelectionDAG &DAG) {
13400   SDLoc dl(Op);
13401   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13402     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13403   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13404     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13405
13406   // The only fence that needs an instruction is a sequentially-consistent
13407   // cross-thread fence.
13408   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13409     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13410     // no-sse2). There isn't any reason to disable it if the target processor
13411     // supports it.
13412     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13413       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13414
13415     SDValue Chain = Op.getOperand(0);
13416     SDValue Zero = DAG.getConstant(0, MVT::i32);
13417     SDValue Ops[] = {
13418       DAG.getRegister(X86::ESP, MVT::i32), // Base
13419       DAG.getTargetConstant(1, MVT::i8),   // Scale
13420       DAG.getRegister(0, MVT::i32),        // Index
13421       DAG.getTargetConstant(0, MVT::i32),  // Disp
13422       DAG.getRegister(0, MVT::i32),        // Segment.
13423       Zero,
13424       Chain
13425     };
13426     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13427     return SDValue(Res, 0);
13428   }
13429
13430   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13431   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13432 }
13433
13434 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13435                              SelectionDAG &DAG) {
13436   MVT T = Op.getSimpleValueType();
13437   SDLoc DL(Op);
13438   unsigned Reg = 0;
13439   unsigned size = 0;
13440   switch(T.SimpleTy) {
13441   default: llvm_unreachable("Invalid value type!");
13442   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13443   case MVT::i16: Reg = X86::AX;  size = 2; break;
13444   case MVT::i32: Reg = X86::EAX; size = 4; break;
13445   case MVT::i64:
13446     assert(Subtarget->is64Bit() && "Node not type legal!");
13447     Reg = X86::RAX; size = 8;
13448     break;
13449   }
13450   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13451                                     Op.getOperand(2), SDValue());
13452   SDValue Ops[] = { cpIn.getValue(0),
13453                     Op.getOperand(1),
13454                     Op.getOperand(3),
13455                     DAG.getTargetConstant(size, MVT::i8),
13456                     cpIn.getValue(1) };
13457   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13458   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13459   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13460                                            Ops, array_lengthof(Ops), T, MMO);
13461   SDValue cpOut =
13462     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13463   return cpOut;
13464 }
13465
13466 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13467                                      SelectionDAG &DAG) {
13468   assert(Subtarget->is64Bit() && "Result not type legalized?");
13469   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13470   SDValue TheChain = Op.getOperand(0);
13471   SDLoc dl(Op);
13472   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13473   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13474   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13475                                    rax.getValue(2));
13476   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13477                             DAG.getConstant(32, MVT::i8));
13478   SDValue Ops[] = {
13479     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13480     rdx.getValue(1)
13481   };
13482   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13483 }
13484
13485 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13486                             SelectionDAG &DAG) {
13487   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13488   MVT DstVT = Op.getSimpleValueType();
13489   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13490          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13491   assert((DstVT == MVT::i64 ||
13492           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13493          "Unexpected custom BITCAST");
13494   // i64 <=> MMX conversions are Legal.
13495   if (SrcVT==MVT::i64 && DstVT.isVector())
13496     return Op;
13497   if (DstVT==MVT::i64 && SrcVT.isVector())
13498     return Op;
13499   // MMX <=> MMX conversions are Legal.
13500   if (SrcVT.isVector() && DstVT.isVector())
13501     return Op;
13502   // All other conversions need to be expanded.
13503   return SDValue();
13504 }
13505
13506 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13507   SDNode *Node = Op.getNode();
13508   SDLoc dl(Node);
13509   EVT T = Node->getValueType(0);
13510   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13511                               DAG.getConstant(0, T), Node->getOperand(2));
13512   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13513                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13514                        Node->getOperand(0),
13515                        Node->getOperand(1), negOp,
13516                        cast<AtomicSDNode>(Node)->getSrcValue(),
13517                        cast<AtomicSDNode>(Node)->getAlignment(),
13518                        cast<AtomicSDNode>(Node)->getOrdering(),
13519                        cast<AtomicSDNode>(Node)->getSynchScope());
13520 }
13521
13522 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13523   SDNode *Node = Op.getNode();
13524   SDLoc dl(Node);
13525   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13526
13527   // Convert seq_cst store -> xchg
13528   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13529   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13530   //        (The only way to get a 16-byte store is cmpxchg16b)
13531   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13532   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13533       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13534     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13535                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13536                                  Node->getOperand(0),
13537                                  Node->getOperand(1), Node->getOperand(2),
13538                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13539                                  cast<AtomicSDNode>(Node)->getOrdering(),
13540                                  cast<AtomicSDNode>(Node)->getSynchScope());
13541     return Swap.getValue(1);
13542   }
13543   // Other atomic stores have a simple pattern.
13544   return Op;
13545 }
13546
13547 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13548   EVT VT = Op.getNode()->getSimpleValueType(0);
13549
13550   // Let legalize expand this if it isn't a legal type yet.
13551   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13552     return SDValue();
13553
13554   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13555
13556   unsigned Opc;
13557   bool ExtraOp = false;
13558   switch (Op.getOpcode()) {
13559   default: llvm_unreachable("Invalid code");
13560   case ISD::ADDC: Opc = X86ISD::ADD; break;
13561   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13562   case ISD::SUBC: Opc = X86ISD::SUB; break;
13563   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13564   }
13565
13566   if (!ExtraOp)
13567     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13568                        Op.getOperand(1));
13569   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13570                      Op.getOperand(1), Op.getOperand(2));
13571 }
13572
13573 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13574                             SelectionDAG &DAG) {
13575   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13576
13577   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13578   // which returns the values as { float, float } (in XMM0) or
13579   // { double, double } (which is returned in XMM0, XMM1).
13580   SDLoc dl(Op);
13581   SDValue Arg = Op.getOperand(0);
13582   EVT ArgVT = Arg.getValueType();
13583   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13584
13585   TargetLowering::ArgListTy Args;
13586   TargetLowering::ArgListEntry Entry;
13587
13588   Entry.Node = Arg;
13589   Entry.Ty = ArgTy;
13590   Entry.isSExt = false;
13591   Entry.isZExt = false;
13592   Args.push_back(Entry);
13593
13594   bool isF64 = ArgVT == MVT::f64;
13595   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13596   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13597   // the results are returned via SRet in memory.
13598   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13599   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13600   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13601
13602   Type *RetTy = isF64
13603     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13604     : (Type*)VectorType::get(ArgTy, 4);
13605   TargetLowering::
13606     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13607                          false, false, false, false, 0,
13608                          CallingConv::C, /*isTaillCall=*/false,
13609                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13610                          Callee, Args, DAG, dl);
13611   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13612
13613   if (isF64)
13614     // Returned in xmm0 and xmm1.
13615     return CallResult.first;
13616
13617   // Returned in bits 0:31 and 32:64 xmm0.
13618   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13619                                CallResult.first, DAG.getIntPtrConstant(0));
13620   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13621                                CallResult.first, DAG.getIntPtrConstant(1));
13622   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13623   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13624 }
13625
13626 /// LowerOperation - Provide custom lowering hooks for some operations.
13627 ///
13628 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13629   switch (Op.getOpcode()) {
13630   default: llvm_unreachable("Should not custom lower this!");
13631   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13632   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13633   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13634   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13635   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13636   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13637   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13638   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13639   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13640   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13641   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13642   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13643   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13644   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13645   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13646   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13647   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13648   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13649   case ISD::SHL_PARTS:
13650   case ISD::SRA_PARTS:
13651   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13652   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13653   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13654   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13655   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13656   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13657   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13658   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13659   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13660   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13661   case ISD::FABS:               return LowerFABS(Op, DAG);
13662   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13663   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13664   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13665   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13666   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13667   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13668   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13669   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13670   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13671   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13672   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13673   case ISD::INTRINSIC_VOID:
13674   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13675   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13676   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13677   case ISD::FRAME_TO_ARGS_OFFSET:
13678                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13679   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13680   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13681   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13682   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13683   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13684   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13685   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13686   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13687   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13688   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13689   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13690   case ISD::SRA:
13691   case ISD::SRL:
13692   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13693   case ISD::SADDO:
13694   case ISD::UADDO:
13695   case ISD::SSUBO:
13696   case ISD::USUBO:
13697   case ISD::SMULO:
13698   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13699   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13700   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13701   case ISD::ADDC:
13702   case ISD::ADDE:
13703   case ISD::SUBC:
13704   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13705   case ISD::ADD:                return LowerADD(Op, DAG);
13706   case ISD::SUB:                return LowerSUB(Op, DAG);
13707   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13708   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13709   }
13710 }
13711
13712 static void ReplaceATOMIC_LOAD(SDNode *Node,
13713                                   SmallVectorImpl<SDValue> &Results,
13714                                   SelectionDAG &DAG) {
13715   SDLoc dl(Node);
13716   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13717
13718   // Convert wide load -> cmpxchg8b/cmpxchg16b
13719   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13720   //        (The only way to get a 16-byte load is cmpxchg16b)
13721   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13722   SDValue Zero = DAG.getConstant(0, VT);
13723   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13724                                Node->getOperand(0),
13725                                Node->getOperand(1), Zero, Zero,
13726                                cast<AtomicSDNode>(Node)->getMemOperand(),
13727                                cast<AtomicSDNode>(Node)->getOrdering(),
13728                                cast<AtomicSDNode>(Node)->getSynchScope());
13729   Results.push_back(Swap.getValue(0));
13730   Results.push_back(Swap.getValue(1));
13731 }
13732
13733 static void
13734 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13735                         SelectionDAG &DAG, unsigned NewOp) {
13736   SDLoc dl(Node);
13737   assert (Node->getValueType(0) == MVT::i64 &&
13738           "Only know how to expand i64 atomics");
13739
13740   SDValue Chain = Node->getOperand(0);
13741   SDValue In1 = Node->getOperand(1);
13742   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13743                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13744   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13745                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13746   SDValue Ops[] = { Chain, In1, In2L, In2H };
13747   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13748   SDValue Result =
13749     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13750                             cast<MemSDNode>(Node)->getMemOperand());
13751   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13752   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13753   Results.push_back(Result.getValue(2));
13754 }
13755
13756 /// ReplaceNodeResults - Replace a node with an illegal result type
13757 /// with a new node built out of custom code.
13758 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13759                                            SmallVectorImpl<SDValue>&Results,
13760                                            SelectionDAG &DAG) const {
13761   SDLoc dl(N);
13762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13763   switch (N->getOpcode()) {
13764   default:
13765     llvm_unreachable("Do not know how to custom type legalize this operation!");
13766   case ISD::SIGN_EXTEND_INREG:
13767   case ISD::ADDC:
13768   case ISD::ADDE:
13769   case ISD::SUBC:
13770   case ISD::SUBE:
13771     // We don't want to expand or promote these.
13772     return;
13773   case ISD::FP_TO_SINT:
13774   case ISD::FP_TO_UINT: {
13775     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13776
13777     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13778       return;
13779
13780     std::pair<SDValue,SDValue> Vals =
13781         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13782     SDValue FIST = Vals.first, StackSlot = Vals.second;
13783     if (FIST.getNode() != 0) {
13784       EVT VT = N->getValueType(0);
13785       // Return a load from the stack slot.
13786       if (StackSlot.getNode() != 0)
13787         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13788                                       MachinePointerInfo(),
13789                                       false, false, false, 0));
13790       else
13791         Results.push_back(FIST);
13792     }
13793     return;
13794   }
13795   case ISD::UINT_TO_FP: {
13796     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13797     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13798         N->getValueType(0) != MVT::v2f32)
13799       return;
13800     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13801                                  N->getOperand(0));
13802     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13803                                      MVT::f64);
13804     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13805     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13806                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13807     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13808     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13809     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13810     return;
13811   }
13812   case ISD::FP_ROUND: {
13813     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13814         return;
13815     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13816     Results.push_back(V);
13817     return;
13818   }
13819   case ISD::READCYCLECOUNTER: {
13820     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13821     SDValue TheChain = N->getOperand(0);
13822     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13823     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13824                                      rd.getValue(1));
13825     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13826                                      eax.getValue(2));
13827     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13828     SDValue Ops[] = { eax, edx };
13829     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13830                                   array_lengthof(Ops)));
13831     Results.push_back(edx.getValue(1));
13832     return;
13833   }
13834   case ISD::ATOMIC_CMP_SWAP: {
13835     EVT T = N->getValueType(0);
13836     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13837     bool Regs64bit = T == MVT::i128;
13838     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13839     SDValue cpInL, cpInH;
13840     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13841                         DAG.getConstant(0, HalfT));
13842     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13843                         DAG.getConstant(1, HalfT));
13844     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13845                              Regs64bit ? X86::RAX : X86::EAX,
13846                              cpInL, SDValue());
13847     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13848                              Regs64bit ? X86::RDX : X86::EDX,
13849                              cpInH, cpInL.getValue(1));
13850     SDValue swapInL, swapInH;
13851     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13852                           DAG.getConstant(0, HalfT));
13853     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13854                           DAG.getConstant(1, HalfT));
13855     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13856                                Regs64bit ? X86::RBX : X86::EBX,
13857                                swapInL, cpInH.getValue(1));
13858     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13859                                Regs64bit ? X86::RCX : X86::ECX,
13860                                swapInH, swapInL.getValue(1));
13861     SDValue Ops[] = { swapInH.getValue(0),
13862                       N->getOperand(1),
13863                       swapInH.getValue(1) };
13864     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13865     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13866     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13867                                   X86ISD::LCMPXCHG8_DAG;
13868     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13869                                              Ops, array_lengthof(Ops), T, MMO);
13870     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13871                                         Regs64bit ? X86::RAX : X86::EAX,
13872                                         HalfT, Result.getValue(1));
13873     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13874                                         Regs64bit ? X86::RDX : X86::EDX,
13875                                         HalfT, cpOutL.getValue(2));
13876     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13877     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13878     Results.push_back(cpOutH.getValue(1));
13879     return;
13880   }
13881   case ISD::ATOMIC_LOAD_ADD:
13882   case ISD::ATOMIC_LOAD_AND:
13883   case ISD::ATOMIC_LOAD_NAND:
13884   case ISD::ATOMIC_LOAD_OR:
13885   case ISD::ATOMIC_LOAD_SUB:
13886   case ISD::ATOMIC_LOAD_XOR:
13887   case ISD::ATOMIC_LOAD_MAX:
13888   case ISD::ATOMIC_LOAD_MIN:
13889   case ISD::ATOMIC_LOAD_UMAX:
13890   case ISD::ATOMIC_LOAD_UMIN:
13891   case ISD::ATOMIC_SWAP: {
13892     unsigned Opc;
13893     switch (N->getOpcode()) {
13894     default: llvm_unreachable("Unexpected opcode");
13895     case ISD::ATOMIC_LOAD_ADD:
13896       Opc = X86ISD::ATOMADD64_DAG;
13897       break;
13898     case ISD::ATOMIC_LOAD_AND:
13899       Opc = X86ISD::ATOMAND64_DAG;
13900       break;
13901     case ISD::ATOMIC_LOAD_NAND:
13902       Opc = X86ISD::ATOMNAND64_DAG;
13903       break;
13904     case ISD::ATOMIC_LOAD_OR:
13905       Opc = X86ISD::ATOMOR64_DAG;
13906       break;
13907     case ISD::ATOMIC_LOAD_SUB:
13908       Opc = X86ISD::ATOMSUB64_DAG;
13909       break;
13910     case ISD::ATOMIC_LOAD_XOR:
13911       Opc = X86ISD::ATOMXOR64_DAG;
13912       break;
13913     case ISD::ATOMIC_LOAD_MAX:
13914       Opc = X86ISD::ATOMMAX64_DAG;
13915       break;
13916     case ISD::ATOMIC_LOAD_MIN:
13917       Opc = X86ISD::ATOMMIN64_DAG;
13918       break;
13919     case ISD::ATOMIC_LOAD_UMAX:
13920       Opc = X86ISD::ATOMUMAX64_DAG;
13921       break;
13922     case ISD::ATOMIC_LOAD_UMIN:
13923       Opc = X86ISD::ATOMUMIN64_DAG;
13924       break;
13925     case ISD::ATOMIC_SWAP:
13926       Opc = X86ISD::ATOMSWAP64_DAG;
13927       break;
13928     }
13929     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13930     return;
13931   }
13932   case ISD::ATOMIC_LOAD:
13933     ReplaceATOMIC_LOAD(N, Results, DAG);
13934   }
13935 }
13936
13937 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13938   switch (Opcode) {
13939   default: return NULL;
13940   case X86ISD::BSF:                return "X86ISD::BSF";
13941   case X86ISD::BSR:                return "X86ISD::BSR";
13942   case X86ISD::SHLD:               return "X86ISD::SHLD";
13943   case X86ISD::SHRD:               return "X86ISD::SHRD";
13944   case X86ISD::FAND:               return "X86ISD::FAND";
13945   case X86ISD::FANDN:              return "X86ISD::FANDN";
13946   case X86ISD::FOR:                return "X86ISD::FOR";
13947   case X86ISD::FXOR:               return "X86ISD::FXOR";
13948   case X86ISD::FSRL:               return "X86ISD::FSRL";
13949   case X86ISD::FILD:               return "X86ISD::FILD";
13950   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13951   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13952   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13953   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13954   case X86ISD::FLD:                return "X86ISD::FLD";
13955   case X86ISD::FST:                return "X86ISD::FST";
13956   case X86ISD::CALL:               return "X86ISD::CALL";
13957   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13958   case X86ISD::BT:                 return "X86ISD::BT";
13959   case X86ISD::CMP:                return "X86ISD::CMP";
13960   case X86ISD::COMI:               return "X86ISD::COMI";
13961   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13962   case X86ISD::CMPM:               return "X86ISD::CMPM";
13963   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
13964   case X86ISD::SETCC:              return "X86ISD::SETCC";
13965   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13966   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
13967   case X86ISD::CMOV:               return "X86ISD::CMOV";
13968   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13969   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13970   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13971   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13972   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13973   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13974   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13975   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13976   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13977   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13978   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13979   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13980   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13981   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13982   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13983   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13984   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13985   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13986   case X86ISD::HADD:               return "X86ISD::HADD";
13987   case X86ISD::HSUB:               return "X86ISD::HSUB";
13988   case X86ISD::FHADD:              return "X86ISD::FHADD";
13989   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13990   case X86ISD::UMAX:               return "X86ISD::UMAX";
13991   case X86ISD::UMIN:               return "X86ISD::UMIN";
13992   case X86ISD::SMAX:               return "X86ISD::SMAX";
13993   case X86ISD::SMIN:               return "X86ISD::SMIN";
13994   case X86ISD::FMAX:               return "X86ISD::FMAX";
13995   case X86ISD::FMIN:               return "X86ISD::FMIN";
13996   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13997   case X86ISD::FMINC:              return "X86ISD::FMINC";
13998   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13999   case X86ISD::FRCP:               return "X86ISD::FRCP";
14000   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14001   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14002   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14003   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14004   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14005   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14006   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14007   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14008   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14009   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14010   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14011   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14012   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14013   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14014   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14015   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14016   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14017   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14018   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
14019   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14020   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14021   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14022   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14023   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14024   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14025   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14026   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14027   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14028   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14029   case X86ISD::VSHL:               return "X86ISD::VSHL";
14030   case X86ISD::VSRL:               return "X86ISD::VSRL";
14031   case X86ISD::VSRA:               return "X86ISD::VSRA";
14032   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14033   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14034   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14035   case X86ISD::CMPP:               return "X86ISD::CMPP";
14036   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14037   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14038   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14039   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14040   case X86ISD::ADD:                return "X86ISD::ADD";
14041   case X86ISD::SUB:                return "X86ISD::SUB";
14042   case X86ISD::ADC:                return "X86ISD::ADC";
14043   case X86ISD::SBB:                return "X86ISD::SBB";
14044   case X86ISD::SMUL:               return "X86ISD::SMUL";
14045   case X86ISD::UMUL:               return "X86ISD::UMUL";
14046   case X86ISD::INC:                return "X86ISD::INC";
14047   case X86ISD::DEC:                return "X86ISD::DEC";
14048   case X86ISD::OR:                 return "X86ISD::OR";
14049   case X86ISD::XOR:                return "X86ISD::XOR";
14050   case X86ISD::AND:                return "X86ISD::AND";
14051   case X86ISD::BZHI:               return "X86ISD::BZHI";
14052   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14053   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14054   case X86ISD::PTEST:              return "X86ISD::PTEST";
14055   case X86ISD::TESTP:              return "X86ISD::TESTP";
14056   case X86ISD::TESTM:              return "X86ISD::TESTM";
14057   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14058   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14059   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14060   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14061   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14062   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14063   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14064   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14065   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14066   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14067   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14068   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14069   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14070   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14071   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14072   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14073   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14074   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14075   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14076   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14077   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14078   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14079   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14080   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14081   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14082   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14083   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14084   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14085   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14086   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14087   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14088   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14089   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14090   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14091   case X86ISD::SAHF:               return "X86ISD::SAHF";
14092   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14093   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14094   case X86ISD::FMADD:              return "X86ISD::FMADD";
14095   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14096   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14097   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14098   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14099   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14100   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14101   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14102   case X86ISD::XTEST:              return "X86ISD::XTEST";
14103   }
14104 }
14105
14106 // isLegalAddressingMode - Return true if the addressing mode represented
14107 // by AM is legal for this target, for a load/store of the specified type.
14108 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14109                                               Type *Ty) const {
14110   // X86 supports extremely general addressing modes.
14111   CodeModel::Model M = getTargetMachine().getCodeModel();
14112   Reloc::Model R = getTargetMachine().getRelocationModel();
14113
14114   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14115   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14116     return false;
14117
14118   if (AM.BaseGV) {
14119     unsigned GVFlags =
14120       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14121
14122     // If a reference to this global requires an extra load, we can't fold it.
14123     if (isGlobalStubReference(GVFlags))
14124       return false;
14125
14126     // If BaseGV requires a register for the PIC base, we cannot also have a
14127     // BaseReg specified.
14128     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14129       return false;
14130
14131     // If lower 4G is not available, then we must use rip-relative addressing.
14132     if ((M != CodeModel::Small || R != Reloc::Static) &&
14133         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14134       return false;
14135   }
14136
14137   switch (AM.Scale) {
14138   case 0:
14139   case 1:
14140   case 2:
14141   case 4:
14142   case 8:
14143     // These scales always work.
14144     break;
14145   case 3:
14146   case 5:
14147   case 9:
14148     // These scales are formed with basereg+scalereg.  Only accept if there is
14149     // no basereg yet.
14150     if (AM.HasBaseReg)
14151       return false;
14152     break;
14153   default:  // Other stuff never works.
14154     return false;
14155   }
14156
14157   return true;
14158 }
14159
14160 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14161   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14162     return false;
14163   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14164   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14165   return NumBits1 > NumBits2;
14166 }
14167
14168 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14169   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14170     return false;
14171
14172   if (!isTypeLegal(EVT::getEVT(Ty1)))
14173     return false;
14174
14175   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14176
14177   // Assuming the caller doesn't have a zeroext or signext return parameter,
14178   // truncation all the way down to i1 is valid.
14179   return true;
14180 }
14181
14182 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14183   return isInt<32>(Imm);
14184 }
14185
14186 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14187   // Can also use sub to handle negated immediates.
14188   return isInt<32>(Imm);
14189 }
14190
14191 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14192   if (!VT1.isInteger() || !VT2.isInteger())
14193     return false;
14194   unsigned NumBits1 = VT1.getSizeInBits();
14195   unsigned NumBits2 = VT2.getSizeInBits();
14196   return NumBits1 > NumBits2;
14197 }
14198
14199 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14200   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14201   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14202 }
14203
14204 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14205   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14206   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14207 }
14208
14209 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14210   EVT VT1 = Val.getValueType();
14211   if (isZExtFree(VT1, VT2))
14212     return true;
14213
14214   if (Val.getOpcode() != ISD::LOAD)
14215     return false;
14216
14217   if (!VT1.isSimple() || !VT1.isInteger() ||
14218       !VT2.isSimple() || !VT2.isInteger())
14219     return false;
14220
14221   switch (VT1.getSimpleVT().SimpleTy) {
14222   default: break;
14223   case MVT::i8:
14224   case MVT::i16:
14225   case MVT::i32:
14226     // X86 has 8, 16, and 32-bit zero-extending loads.
14227     return true;
14228   }
14229
14230   return false;
14231 }
14232
14233 bool
14234 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14235   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14236     return false;
14237
14238   VT = VT.getScalarType();
14239
14240   if (!VT.isSimple())
14241     return false;
14242
14243   switch (VT.getSimpleVT().SimpleTy) {
14244   case MVT::f32:
14245   case MVT::f64:
14246     return true;
14247   default:
14248     break;
14249   }
14250
14251   return false;
14252 }
14253
14254 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14255   // i16 instructions are longer (0x66 prefix) and potentially slower.
14256   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14257 }
14258
14259 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14260 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14261 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14262 /// are assumed to be legal.
14263 bool
14264 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14265                                       EVT VT) const {
14266   if (!VT.isSimple())
14267     return false;
14268
14269   MVT SVT = VT.getSimpleVT();
14270
14271   // Very little shuffling can be done for 64-bit vectors right now.
14272   if (VT.getSizeInBits() == 64)
14273     return false;
14274
14275   // FIXME: pshufb, blends, shifts.
14276   return (SVT.getVectorNumElements() == 2 ||
14277           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14278           isMOVLMask(M, SVT) ||
14279           isSHUFPMask(M, SVT) ||
14280           isPSHUFDMask(M, SVT) ||
14281           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14282           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14283           isPALIGNRMask(M, SVT, Subtarget) ||
14284           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14285           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14286           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14287           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14288 }
14289
14290 bool
14291 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14292                                           EVT VT) const {
14293   if (!VT.isSimple())
14294     return false;
14295
14296   MVT SVT = VT.getSimpleVT();
14297   unsigned NumElts = SVT.getVectorNumElements();
14298   // FIXME: This collection of masks seems suspect.
14299   if (NumElts == 2)
14300     return true;
14301   if (NumElts == 4 && SVT.is128BitVector()) {
14302     return (isMOVLMask(Mask, SVT)  ||
14303             isCommutedMOVLMask(Mask, SVT, true) ||
14304             isSHUFPMask(Mask, SVT) ||
14305             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14306   }
14307   return false;
14308 }
14309
14310 //===----------------------------------------------------------------------===//
14311 //                           X86 Scheduler Hooks
14312 //===----------------------------------------------------------------------===//
14313
14314 /// Utility function to emit xbegin specifying the start of an RTM region.
14315 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14316                                      const TargetInstrInfo *TII) {
14317   DebugLoc DL = MI->getDebugLoc();
14318
14319   const BasicBlock *BB = MBB->getBasicBlock();
14320   MachineFunction::iterator I = MBB;
14321   ++I;
14322
14323   // For the v = xbegin(), we generate
14324   //
14325   // thisMBB:
14326   //  xbegin sinkMBB
14327   //
14328   // mainMBB:
14329   //  eax = -1
14330   //
14331   // sinkMBB:
14332   //  v = eax
14333
14334   MachineBasicBlock *thisMBB = MBB;
14335   MachineFunction *MF = MBB->getParent();
14336   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14337   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14338   MF->insert(I, mainMBB);
14339   MF->insert(I, sinkMBB);
14340
14341   // Transfer the remainder of BB and its successor edges to sinkMBB.
14342   sinkMBB->splice(sinkMBB->begin(), MBB,
14343                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14344   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14345
14346   // thisMBB:
14347   //  xbegin sinkMBB
14348   //  # fallthrough to mainMBB
14349   //  # abortion to sinkMBB
14350   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14351   thisMBB->addSuccessor(mainMBB);
14352   thisMBB->addSuccessor(sinkMBB);
14353
14354   // mainMBB:
14355   //  EAX = -1
14356   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14357   mainMBB->addSuccessor(sinkMBB);
14358
14359   // sinkMBB:
14360   // EAX is live into the sinkMBB
14361   sinkMBB->addLiveIn(X86::EAX);
14362   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14363           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14364     .addReg(X86::EAX);
14365
14366   MI->eraseFromParent();
14367   return sinkMBB;
14368 }
14369
14370 // Get CMPXCHG opcode for the specified data type.
14371 static unsigned getCmpXChgOpcode(EVT VT) {
14372   switch (VT.getSimpleVT().SimpleTy) {
14373   case MVT::i8:  return X86::LCMPXCHG8;
14374   case MVT::i16: return X86::LCMPXCHG16;
14375   case MVT::i32: return X86::LCMPXCHG32;
14376   case MVT::i64: return X86::LCMPXCHG64;
14377   default:
14378     break;
14379   }
14380   llvm_unreachable("Invalid operand size!");
14381 }
14382
14383 // Get LOAD opcode for the specified data type.
14384 static unsigned getLoadOpcode(EVT VT) {
14385   switch (VT.getSimpleVT().SimpleTy) {
14386   case MVT::i8:  return X86::MOV8rm;
14387   case MVT::i16: return X86::MOV16rm;
14388   case MVT::i32: return X86::MOV32rm;
14389   case MVT::i64: return X86::MOV64rm;
14390   default:
14391     break;
14392   }
14393   llvm_unreachable("Invalid operand size!");
14394 }
14395
14396 // Get opcode of the non-atomic one from the specified atomic instruction.
14397 static unsigned getNonAtomicOpcode(unsigned Opc) {
14398   switch (Opc) {
14399   case X86::ATOMAND8:  return X86::AND8rr;
14400   case X86::ATOMAND16: return X86::AND16rr;
14401   case X86::ATOMAND32: return X86::AND32rr;
14402   case X86::ATOMAND64: return X86::AND64rr;
14403   case X86::ATOMOR8:   return X86::OR8rr;
14404   case X86::ATOMOR16:  return X86::OR16rr;
14405   case X86::ATOMOR32:  return X86::OR32rr;
14406   case X86::ATOMOR64:  return X86::OR64rr;
14407   case X86::ATOMXOR8:  return X86::XOR8rr;
14408   case X86::ATOMXOR16: return X86::XOR16rr;
14409   case X86::ATOMXOR32: return X86::XOR32rr;
14410   case X86::ATOMXOR64: return X86::XOR64rr;
14411   }
14412   llvm_unreachable("Unhandled atomic-load-op opcode!");
14413 }
14414
14415 // Get opcode of the non-atomic one from the specified atomic instruction with
14416 // extra opcode.
14417 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14418                                                unsigned &ExtraOpc) {
14419   switch (Opc) {
14420   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14421   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14422   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14423   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14424   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14425   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14426   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14427   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14428   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14429   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14430   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14431   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14432   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14433   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14434   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14435   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14436   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14437   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14438   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14439   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14440   }
14441   llvm_unreachable("Unhandled atomic-load-op opcode!");
14442 }
14443
14444 // Get opcode of the non-atomic one from the specified atomic instruction for
14445 // 64-bit data type on 32-bit target.
14446 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14447   switch (Opc) {
14448   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14449   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14450   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14451   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14452   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14453   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14454   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14455   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14456   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14457   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14458   }
14459   llvm_unreachable("Unhandled atomic-load-op opcode!");
14460 }
14461
14462 // Get opcode of the non-atomic one from the specified atomic instruction for
14463 // 64-bit data type on 32-bit target with extra opcode.
14464 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14465                                                    unsigned &HiOpc,
14466                                                    unsigned &ExtraOpc) {
14467   switch (Opc) {
14468   case X86::ATOMNAND6432:
14469     ExtraOpc = X86::NOT32r;
14470     HiOpc = X86::AND32rr;
14471     return X86::AND32rr;
14472   }
14473   llvm_unreachable("Unhandled atomic-load-op opcode!");
14474 }
14475
14476 // Get pseudo CMOV opcode from the specified data type.
14477 static unsigned getPseudoCMOVOpc(EVT VT) {
14478   switch (VT.getSimpleVT().SimpleTy) {
14479   case MVT::i8:  return X86::CMOV_GR8;
14480   case MVT::i16: return X86::CMOV_GR16;
14481   case MVT::i32: return X86::CMOV_GR32;
14482   default:
14483     break;
14484   }
14485   llvm_unreachable("Unknown CMOV opcode!");
14486 }
14487
14488 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14489 // They will be translated into a spin-loop or compare-exchange loop from
14490 //
14491 //    ...
14492 //    dst = atomic-fetch-op MI.addr, MI.val
14493 //    ...
14494 //
14495 // to
14496 //
14497 //    ...
14498 //    t1 = LOAD MI.addr
14499 // loop:
14500 //    t4 = phi(t1, t3 / loop)
14501 //    t2 = OP MI.val, t4
14502 //    EAX = t4
14503 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14504 //    t3 = EAX
14505 //    JNE loop
14506 // sink:
14507 //    dst = t3
14508 //    ...
14509 MachineBasicBlock *
14510 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14511                                        MachineBasicBlock *MBB) const {
14512   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14513   DebugLoc DL = MI->getDebugLoc();
14514
14515   MachineFunction *MF = MBB->getParent();
14516   MachineRegisterInfo &MRI = MF->getRegInfo();
14517
14518   const BasicBlock *BB = MBB->getBasicBlock();
14519   MachineFunction::iterator I = MBB;
14520   ++I;
14521
14522   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14523          "Unexpected number of operands");
14524
14525   assert(MI->hasOneMemOperand() &&
14526          "Expected atomic-load-op to have one memoperand");
14527
14528   // Memory Reference
14529   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14530   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14531
14532   unsigned DstReg, SrcReg;
14533   unsigned MemOpndSlot;
14534
14535   unsigned CurOp = 0;
14536
14537   DstReg = MI->getOperand(CurOp++).getReg();
14538   MemOpndSlot = CurOp;
14539   CurOp += X86::AddrNumOperands;
14540   SrcReg = MI->getOperand(CurOp++).getReg();
14541
14542   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14543   MVT::SimpleValueType VT = *RC->vt_begin();
14544   unsigned t1 = MRI.createVirtualRegister(RC);
14545   unsigned t2 = MRI.createVirtualRegister(RC);
14546   unsigned t3 = MRI.createVirtualRegister(RC);
14547   unsigned t4 = MRI.createVirtualRegister(RC);
14548   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14549
14550   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14551   unsigned LOADOpc = getLoadOpcode(VT);
14552
14553   // For the atomic load-arith operator, we generate
14554   //
14555   //  thisMBB:
14556   //    t1 = LOAD [MI.addr]
14557   //  mainMBB:
14558   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14559   //    t1 = OP MI.val, EAX
14560   //    EAX = t4
14561   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14562   //    t3 = EAX
14563   //    JNE mainMBB
14564   //  sinkMBB:
14565   //    dst = t3
14566
14567   MachineBasicBlock *thisMBB = MBB;
14568   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14569   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14570   MF->insert(I, mainMBB);
14571   MF->insert(I, sinkMBB);
14572
14573   MachineInstrBuilder MIB;
14574
14575   // Transfer the remainder of BB and its successor edges to sinkMBB.
14576   sinkMBB->splice(sinkMBB->begin(), MBB,
14577                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14578   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14579
14580   // thisMBB:
14581   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14582   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14583     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14584     if (NewMO.isReg())
14585       NewMO.setIsKill(false);
14586     MIB.addOperand(NewMO);
14587   }
14588   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14589     unsigned flags = (*MMOI)->getFlags();
14590     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14591     MachineMemOperand *MMO =
14592       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14593                                (*MMOI)->getSize(),
14594                                (*MMOI)->getBaseAlignment(),
14595                                (*MMOI)->getTBAAInfo(),
14596                                (*MMOI)->getRanges());
14597     MIB.addMemOperand(MMO);
14598   }
14599
14600   thisMBB->addSuccessor(mainMBB);
14601
14602   // mainMBB:
14603   MachineBasicBlock *origMainMBB = mainMBB;
14604
14605   // Add a PHI.
14606   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14607                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14608
14609   unsigned Opc = MI->getOpcode();
14610   switch (Opc) {
14611   default:
14612     llvm_unreachable("Unhandled atomic-load-op opcode!");
14613   case X86::ATOMAND8:
14614   case X86::ATOMAND16:
14615   case X86::ATOMAND32:
14616   case X86::ATOMAND64:
14617   case X86::ATOMOR8:
14618   case X86::ATOMOR16:
14619   case X86::ATOMOR32:
14620   case X86::ATOMOR64:
14621   case X86::ATOMXOR8:
14622   case X86::ATOMXOR16:
14623   case X86::ATOMXOR32:
14624   case X86::ATOMXOR64: {
14625     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14626     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14627       .addReg(t4);
14628     break;
14629   }
14630   case X86::ATOMNAND8:
14631   case X86::ATOMNAND16:
14632   case X86::ATOMNAND32:
14633   case X86::ATOMNAND64: {
14634     unsigned Tmp = MRI.createVirtualRegister(RC);
14635     unsigned NOTOpc;
14636     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14637     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14638       .addReg(t4);
14639     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14640     break;
14641   }
14642   case X86::ATOMMAX8:
14643   case X86::ATOMMAX16:
14644   case X86::ATOMMAX32:
14645   case X86::ATOMMAX64:
14646   case X86::ATOMMIN8:
14647   case X86::ATOMMIN16:
14648   case X86::ATOMMIN32:
14649   case X86::ATOMMIN64:
14650   case X86::ATOMUMAX8:
14651   case X86::ATOMUMAX16:
14652   case X86::ATOMUMAX32:
14653   case X86::ATOMUMAX64:
14654   case X86::ATOMUMIN8:
14655   case X86::ATOMUMIN16:
14656   case X86::ATOMUMIN32:
14657   case X86::ATOMUMIN64: {
14658     unsigned CMPOpc;
14659     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14660
14661     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14662       .addReg(SrcReg)
14663       .addReg(t4);
14664
14665     if (Subtarget->hasCMov()) {
14666       if (VT != MVT::i8) {
14667         // Native support
14668         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14669           .addReg(SrcReg)
14670           .addReg(t4);
14671       } else {
14672         // Promote i8 to i32 to use CMOV32
14673         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14674         const TargetRegisterClass *RC32 =
14675           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14676         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14677         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14678         unsigned Tmp = MRI.createVirtualRegister(RC32);
14679
14680         unsigned Undef = MRI.createVirtualRegister(RC32);
14681         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14682
14683         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14684           .addReg(Undef)
14685           .addReg(SrcReg)
14686           .addImm(X86::sub_8bit);
14687         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14688           .addReg(Undef)
14689           .addReg(t4)
14690           .addImm(X86::sub_8bit);
14691
14692         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14693           .addReg(SrcReg32)
14694           .addReg(AccReg32);
14695
14696         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14697           .addReg(Tmp, 0, X86::sub_8bit);
14698       }
14699     } else {
14700       // Use pseudo select and lower them.
14701       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14702              "Invalid atomic-load-op transformation!");
14703       unsigned SelOpc = getPseudoCMOVOpc(VT);
14704       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14705       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14706       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14707               .addReg(SrcReg).addReg(t4)
14708               .addImm(CC);
14709       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14710       // Replace the original PHI node as mainMBB is changed after CMOV
14711       // lowering.
14712       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14713         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14714       Phi->eraseFromParent();
14715     }
14716     break;
14717   }
14718   }
14719
14720   // Copy PhyReg back from virtual register.
14721   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14722     .addReg(t4);
14723
14724   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14725   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14726     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14727     if (NewMO.isReg())
14728       NewMO.setIsKill(false);
14729     MIB.addOperand(NewMO);
14730   }
14731   MIB.addReg(t2);
14732   MIB.setMemRefs(MMOBegin, MMOEnd);
14733
14734   // Copy PhyReg back to virtual register.
14735   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14736     .addReg(PhyReg);
14737
14738   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14739
14740   mainMBB->addSuccessor(origMainMBB);
14741   mainMBB->addSuccessor(sinkMBB);
14742
14743   // sinkMBB:
14744   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14745           TII->get(TargetOpcode::COPY), DstReg)
14746     .addReg(t3);
14747
14748   MI->eraseFromParent();
14749   return sinkMBB;
14750 }
14751
14752 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14753 // instructions. They will be translated into a spin-loop or compare-exchange
14754 // loop from
14755 //
14756 //    ...
14757 //    dst = atomic-fetch-op MI.addr, MI.val
14758 //    ...
14759 //
14760 // to
14761 //
14762 //    ...
14763 //    t1L = LOAD [MI.addr + 0]
14764 //    t1H = LOAD [MI.addr + 4]
14765 // loop:
14766 //    t4L = phi(t1L, t3L / loop)
14767 //    t4H = phi(t1H, t3H / loop)
14768 //    t2L = OP MI.val.lo, t4L
14769 //    t2H = OP MI.val.hi, t4H
14770 //    EAX = t4L
14771 //    EDX = t4H
14772 //    EBX = t2L
14773 //    ECX = t2H
14774 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14775 //    t3L = EAX
14776 //    t3H = EDX
14777 //    JNE loop
14778 // sink:
14779 //    dstL = t3L
14780 //    dstH = t3H
14781 //    ...
14782 MachineBasicBlock *
14783 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14784                                            MachineBasicBlock *MBB) const {
14785   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14786   DebugLoc DL = MI->getDebugLoc();
14787
14788   MachineFunction *MF = MBB->getParent();
14789   MachineRegisterInfo &MRI = MF->getRegInfo();
14790
14791   const BasicBlock *BB = MBB->getBasicBlock();
14792   MachineFunction::iterator I = MBB;
14793   ++I;
14794
14795   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14796          "Unexpected number of operands");
14797
14798   assert(MI->hasOneMemOperand() &&
14799          "Expected atomic-load-op32 to have one memoperand");
14800
14801   // Memory Reference
14802   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14803   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14804
14805   unsigned DstLoReg, DstHiReg;
14806   unsigned SrcLoReg, SrcHiReg;
14807   unsigned MemOpndSlot;
14808
14809   unsigned CurOp = 0;
14810
14811   DstLoReg = MI->getOperand(CurOp++).getReg();
14812   DstHiReg = MI->getOperand(CurOp++).getReg();
14813   MemOpndSlot = CurOp;
14814   CurOp += X86::AddrNumOperands;
14815   SrcLoReg = MI->getOperand(CurOp++).getReg();
14816   SrcHiReg = MI->getOperand(CurOp++).getReg();
14817
14818   const TargetRegisterClass *RC = &X86::GR32RegClass;
14819   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14820
14821   unsigned t1L = MRI.createVirtualRegister(RC);
14822   unsigned t1H = MRI.createVirtualRegister(RC);
14823   unsigned t2L = MRI.createVirtualRegister(RC);
14824   unsigned t2H = MRI.createVirtualRegister(RC);
14825   unsigned t3L = MRI.createVirtualRegister(RC);
14826   unsigned t3H = MRI.createVirtualRegister(RC);
14827   unsigned t4L = MRI.createVirtualRegister(RC);
14828   unsigned t4H = MRI.createVirtualRegister(RC);
14829
14830   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14831   unsigned LOADOpc = X86::MOV32rm;
14832
14833   // For the atomic load-arith operator, we generate
14834   //
14835   //  thisMBB:
14836   //    t1L = LOAD [MI.addr + 0]
14837   //    t1H = LOAD [MI.addr + 4]
14838   //  mainMBB:
14839   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14840   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14841   //    t2L = OP MI.val.lo, t4L
14842   //    t2H = OP MI.val.hi, t4H
14843   //    EBX = t2L
14844   //    ECX = t2H
14845   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14846   //    t3L = EAX
14847   //    t3H = EDX
14848   //    JNE loop
14849   //  sinkMBB:
14850   //    dstL = t3L
14851   //    dstH = t3H
14852
14853   MachineBasicBlock *thisMBB = MBB;
14854   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14855   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14856   MF->insert(I, mainMBB);
14857   MF->insert(I, sinkMBB);
14858
14859   MachineInstrBuilder MIB;
14860
14861   // Transfer the remainder of BB and its successor edges to sinkMBB.
14862   sinkMBB->splice(sinkMBB->begin(), MBB,
14863                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14864   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14865
14866   // thisMBB:
14867   // Lo
14868   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14869   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14870     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14871     if (NewMO.isReg())
14872       NewMO.setIsKill(false);
14873     MIB.addOperand(NewMO);
14874   }
14875   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14876     unsigned flags = (*MMOI)->getFlags();
14877     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14878     MachineMemOperand *MMO =
14879       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14880                                (*MMOI)->getSize(),
14881                                (*MMOI)->getBaseAlignment(),
14882                                (*MMOI)->getTBAAInfo(),
14883                                (*MMOI)->getRanges());
14884     MIB.addMemOperand(MMO);
14885   };
14886   MachineInstr *LowMI = MIB;
14887
14888   // Hi
14889   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14890   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14891     if (i == X86::AddrDisp) {
14892       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14893     } else {
14894       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14895       if (NewMO.isReg())
14896         NewMO.setIsKill(false);
14897       MIB.addOperand(NewMO);
14898     }
14899   }
14900   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14901
14902   thisMBB->addSuccessor(mainMBB);
14903
14904   // mainMBB:
14905   MachineBasicBlock *origMainMBB = mainMBB;
14906
14907   // Add PHIs.
14908   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14909                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14910   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14911                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14912
14913   unsigned Opc = MI->getOpcode();
14914   switch (Opc) {
14915   default:
14916     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14917   case X86::ATOMAND6432:
14918   case X86::ATOMOR6432:
14919   case X86::ATOMXOR6432:
14920   case X86::ATOMADD6432:
14921   case X86::ATOMSUB6432: {
14922     unsigned HiOpc;
14923     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14924     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14925       .addReg(SrcLoReg);
14926     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14927       .addReg(SrcHiReg);
14928     break;
14929   }
14930   case X86::ATOMNAND6432: {
14931     unsigned HiOpc, NOTOpc;
14932     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14933     unsigned TmpL = MRI.createVirtualRegister(RC);
14934     unsigned TmpH = MRI.createVirtualRegister(RC);
14935     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14936       .addReg(t4L);
14937     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14938       .addReg(t4H);
14939     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14940     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14941     break;
14942   }
14943   case X86::ATOMMAX6432:
14944   case X86::ATOMMIN6432:
14945   case X86::ATOMUMAX6432:
14946   case X86::ATOMUMIN6432: {
14947     unsigned HiOpc;
14948     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14949     unsigned cL = MRI.createVirtualRegister(RC8);
14950     unsigned cH = MRI.createVirtualRegister(RC8);
14951     unsigned cL32 = MRI.createVirtualRegister(RC);
14952     unsigned cH32 = MRI.createVirtualRegister(RC);
14953     unsigned cc = MRI.createVirtualRegister(RC);
14954     // cl := cmp src_lo, lo
14955     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14956       .addReg(SrcLoReg).addReg(t4L);
14957     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14958     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14959     // ch := cmp src_hi, hi
14960     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14961       .addReg(SrcHiReg).addReg(t4H);
14962     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14963     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14964     // cc := if (src_hi == hi) ? cl : ch;
14965     if (Subtarget->hasCMov()) {
14966       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14967         .addReg(cH32).addReg(cL32);
14968     } else {
14969       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14970               .addReg(cH32).addReg(cL32)
14971               .addImm(X86::COND_E);
14972       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14973     }
14974     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14975     if (Subtarget->hasCMov()) {
14976       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14977         .addReg(SrcLoReg).addReg(t4L);
14978       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14979         .addReg(SrcHiReg).addReg(t4H);
14980     } else {
14981       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14982               .addReg(SrcLoReg).addReg(t4L)
14983               .addImm(X86::COND_NE);
14984       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14985       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14986       // 2nd CMOV lowering.
14987       mainMBB->addLiveIn(X86::EFLAGS);
14988       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14989               .addReg(SrcHiReg).addReg(t4H)
14990               .addImm(X86::COND_NE);
14991       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14992       // Replace the original PHI node as mainMBB is changed after CMOV
14993       // lowering.
14994       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14995         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14996       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14997         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14998       PhiL->eraseFromParent();
14999       PhiH->eraseFromParent();
15000     }
15001     break;
15002   }
15003   case X86::ATOMSWAP6432: {
15004     unsigned HiOpc;
15005     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15006     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15007     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15008     break;
15009   }
15010   }
15011
15012   // Copy EDX:EAX back from HiReg:LoReg
15013   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15014   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15015   // Copy ECX:EBX from t1H:t1L
15016   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15017   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15018
15019   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15020   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15021     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15022     if (NewMO.isReg())
15023       NewMO.setIsKill(false);
15024     MIB.addOperand(NewMO);
15025   }
15026   MIB.setMemRefs(MMOBegin, MMOEnd);
15027
15028   // Copy EDX:EAX back to t3H:t3L
15029   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15030   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15031
15032   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15033
15034   mainMBB->addSuccessor(origMainMBB);
15035   mainMBB->addSuccessor(sinkMBB);
15036
15037   // sinkMBB:
15038   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15039           TII->get(TargetOpcode::COPY), DstLoReg)
15040     .addReg(t3L);
15041   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15042           TII->get(TargetOpcode::COPY), DstHiReg)
15043     .addReg(t3H);
15044
15045   MI->eraseFromParent();
15046   return sinkMBB;
15047 }
15048
15049 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15050 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15051 // in the .td file.
15052 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15053                                        const TargetInstrInfo *TII) {
15054   unsigned Opc;
15055   switch (MI->getOpcode()) {
15056   default: llvm_unreachable("illegal opcode!");
15057   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15058   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15059   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15060   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15061   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15062   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15063   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15064   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15065   }
15066
15067   DebugLoc dl = MI->getDebugLoc();
15068   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15069
15070   unsigned NumArgs = MI->getNumOperands();
15071   for (unsigned i = 1; i < NumArgs; ++i) {
15072     MachineOperand &Op = MI->getOperand(i);
15073     if (!(Op.isReg() && Op.isImplicit()))
15074       MIB.addOperand(Op);
15075   }
15076   if (MI->hasOneMemOperand())
15077     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15078
15079   BuildMI(*BB, MI, dl,
15080     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15081     .addReg(X86::XMM0);
15082
15083   MI->eraseFromParent();
15084   return BB;
15085 }
15086
15087 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15088 // defs in an instruction pattern
15089 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15090                                        const TargetInstrInfo *TII) {
15091   unsigned Opc;
15092   switch (MI->getOpcode()) {
15093   default: llvm_unreachable("illegal opcode!");
15094   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15095   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15096   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15097   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15098   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15099   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15100   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15101   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15102   }
15103
15104   DebugLoc dl = MI->getDebugLoc();
15105   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15106
15107   unsigned NumArgs = MI->getNumOperands(); // remove the results
15108   for (unsigned i = 1; i < NumArgs; ++i) {
15109     MachineOperand &Op = MI->getOperand(i);
15110     if (!(Op.isReg() && Op.isImplicit()))
15111       MIB.addOperand(Op);
15112   }
15113   if (MI->hasOneMemOperand())
15114     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15115
15116   BuildMI(*BB, MI, dl,
15117     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15118     .addReg(X86::ECX);
15119
15120   MI->eraseFromParent();
15121   return BB;
15122 }
15123
15124 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15125                                        const TargetInstrInfo *TII,
15126                                        const X86Subtarget* Subtarget) {
15127   DebugLoc dl = MI->getDebugLoc();
15128
15129   // Address into RAX/EAX, other two args into ECX, EDX.
15130   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15131   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15132   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15133   for (int i = 0; i < X86::AddrNumOperands; ++i)
15134     MIB.addOperand(MI->getOperand(i));
15135
15136   unsigned ValOps = X86::AddrNumOperands;
15137   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15138     .addReg(MI->getOperand(ValOps).getReg());
15139   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15140     .addReg(MI->getOperand(ValOps+1).getReg());
15141
15142   // The instruction doesn't actually take any operands though.
15143   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15144
15145   MI->eraseFromParent(); // The pseudo is gone now.
15146   return BB;
15147 }
15148
15149 MachineBasicBlock *
15150 X86TargetLowering::EmitVAARG64WithCustomInserter(
15151                    MachineInstr *MI,
15152                    MachineBasicBlock *MBB) const {
15153   // Emit va_arg instruction on X86-64.
15154
15155   // Operands to this pseudo-instruction:
15156   // 0  ) Output        : destination address (reg)
15157   // 1-5) Input         : va_list address (addr, i64mem)
15158   // 6  ) ArgSize       : Size (in bytes) of vararg type
15159   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15160   // 8  ) Align         : Alignment of type
15161   // 9  ) EFLAGS (implicit-def)
15162
15163   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15164   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15165
15166   unsigned DestReg = MI->getOperand(0).getReg();
15167   MachineOperand &Base = MI->getOperand(1);
15168   MachineOperand &Scale = MI->getOperand(2);
15169   MachineOperand &Index = MI->getOperand(3);
15170   MachineOperand &Disp = MI->getOperand(4);
15171   MachineOperand &Segment = MI->getOperand(5);
15172   unsigned ArgSize = MI->getOperand(6).getImm();
15173   unsigned ArgMode = MI->getOperand(7).getImm();
15174   unsigned Align = MI->getOperand(8).getImm();
15175
15176   // Memory Reference
15177   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15178   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15179   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15180
15181   // Machine Information
15182   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15183   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15184   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15185   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15186   DebugLoc DL = MI->getDebugLoc();
15187
15188   // struct va_list {
15189   //   i32   gp_offset
15190   //   i32   fp_offset
15191   //   i64   overflow_area (address)
15192   //   i64   reg_save_area (address)
15193   // }
15194   // sizeof(va_list) = 24
15195   // alignment(va_list) = 8
15196
15197   unsigned TotalNumIntRegs = 6;
15198   unsigned TotalNumXMMRegs = 8;
15199   bool UseGPOffset = (ArgMode == 1);
15200   bool UseFPOffset = (ArgMode == 2);
15201   unsigned MaxOffset = TotalNumIntRegs * 8 +
15202                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15203
15204   /* Align ArgSize to a multiple of 8 */
15205   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15206   bool NeedsAlign = (Align > 8);
15207
15208   MachineBasicBlock *thisMBB = MBB;
15209   MachineBasicBlock *overflowMBB;
15210   MachineBasicBlock *offsetMBB;
15211   MachineBasicBlock *endMBB;
15212
15213   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15214   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15215   unsigned OffsetReg = 0;
15216
15217   if (!UseGPOffset && !UseFPOffset) {
15218     // If we only pull from the overflow region, we don't create a branch.
15219     // We don't need to alter control flow.
15220     OffsetDestReg = 0; // unused
15221     OverflowDestReg = DestReg;
15222
15223     offsetMBB = NULL;
15224     overflowMBB = thisMBB;
15225     endMBB = thisMBB;
15226   } else {
15227     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15228     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15229     // If not, pull from overflow_area. (branch to overflowMBB)
15230     //
15231     //       thisMBB
15232     //         |     .
15233     //         |        .
15234     //     offsetMBB   overflowMBB
15235     //         |        .
15236     //         |     .
15237     //        endMBB
15238
15239     // Registers for the PHI in endMBB
15240     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15241     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15242
15243     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15244     MachineFunction *MF = MBB->getParent();
15245     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15246     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15247     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15248
15249     MachineFunction::iterator MBBIter = MBB;
15250     ++MBBIter;
15251
15252     // Insert the new basic blocks
15253     MF->insert(MBBIter, offsetMBB);
15254     MF->insert(MBBIter, overflowMBB);
15255     MF->insert(MBBIter, endMBB);
15256
15257     // Transfer the remainder of MBB and its successor edges to endMBB.
15258     endMBB->splice(endMBB->begin(), thisMBB,
15259                     llvm::next(MachineBasicBlock::iterator(MI)),
15260                     thisMBB->end());
15261     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15262
15263     // Make offsetMBB and overflowMBB successors of thisMBB
15264     thisMBB->addSuccessor(offsetMBB);
15265     thisMBB->addSuccessor(overflowMBB);
15266
15267     // endMBB is a successor of both offsetMBB and overflowMBB
15268     offsetMBB->addSuccessor(endMBB);
15269     overflowMBB->addSuccessor(endMBB);
15270
15271     // Load the offset value into a register
15272     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15273     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15274       .addOperand(Base)
15275       .addOperand(Scale)
15276       .addOperand(Index)
15277       .addDisp(Disp, UseFPOffset ? 4 : 0)
15278       .addOperand(Segment)
15279       .setMemRefs(MMOBegin, MMOEnd);
15280
15281     // Check if there is enough room left to pull this argument.
15282     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15283       .addReg(OffsetReg)
15284       .addImm(MaxOffset + 8 - ArgSizeA8);
15285
15286     // Branch to "overflowMBB" if offset >= max
15287     // Fall through to "offsetMBB" otherwise
15288     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15289       .addMBB(overflowMBB);
15290   }
15291
15292   // In offsetMBB, emit code to use the reg_save_area.
15293   if (offsetMBB) {
15294     assert(OffsetReg != 0);
15295
15296     // Read the reg_save_area address.
15297     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15298     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15299       .addOperand(Base)
15300       .addOperand(Scale)
15301       .addOperand(Index)
15302       .addDisp(Disp, 16)
15303       .addOperand(Segment)
15304       .setMemRefs(MMOBegin, MMOEnd);
15305
15306     // Zero-extend the offset
15307     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15308       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15309         .addImm(0)
15310         .addReg(OffsetReg)
15311         .addImm(X86::sub_32bit);
15312
15313     // Add the offset to the reg_save_area to get the final address.
15314     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15315       .addReg(OffsetReg64)
15316       .addReg(RegSaveReg);
15317
15318     // Compute the offset for the next argument
15319     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15320     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15321       .addReg(OffsetReg)
15322       .addImm(UseFPOffset ? 16 : 8);
15323
15324     // Store it back into the va_list.
15325     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15326       .addOperand(Base)
15327       .addOperand(Scale)
15328       .addOperand(Index)
15329       .addDisp(Disp, UseFPOffset ? 4 : 0)
15330       .addOperand(Segment)
15331       .addReg(NextOffsetReg)
15332       .setMemRefs(MMOBegin, MMOEnd);
15333
15334     // Jump to endMBB
15335     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15336       .addMBB(endMBB);
15337   }
15338
15339   //
15340   // Emit code to use overflow area
15341   //
15342
15343   // Load the overflow_area address into a register.
15344   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15345   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15346     .addOperand(Base)
15347     .addOperand(Scale)
15348     .addOperand(Index)
15349     .addDisp(Disp, 8)
15350     .addOperand(Segment)
15351     .setMemRefs(MMOBegin, MMOEnd);
15352
15353   // If we need to align it, do so. Otherwise, just copy the address
15354   // to OverflowDestReg.
15355   if (NeedsAlign) {
15356     // Align the overflow address
15357     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15358     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15359
15360     // aligned_addr = (addr + (align-1)) & ~(align-1)
15361     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15362       .addReg(OverflowAddrReg)
15363       .addImm(Align-1);
15364
15365     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15366       .addReg(TmpReg)
15367       .addImm(~(uint64_t)(Align-1));
15368   } else {
15369     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15370       .addReg(OverflowAddrReg);
15371   }
15372
15373   // Compute the next overflow address after this argument.
15374   // (the overflow address should be kept 8-byte aligned)
15375   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15376   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15377     .addReg(OverflowDestReg)
15378     .addImm(ArgSizeA8);
15379
15380   // Store the new overflow address.
15381   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15382     .addOperand(Base)
15383     .addOperand(Scale)
15384     .addOperand(Index)
15385     .addDisp(Disp, 8)
15386     .addOperand(Segment)
15387     .addReg(NextAddrReg)
15388     .setMemRefs(MMOBegin, MMOEnd);
15389
15390   // If we branched, emit the PHI to the front of endMBB.
15391   if (offsetMBB) {
15392     BuildMI(*endMBB, endMBB->begin(), DL,
15393             TII->get(X86::PHI), DestReg)
15394       .addReg(OffsetDestReg).addMBB(offsetMBB)
15395       .addReg(OverflowDestReg).addMBB(overflowMBB);
15396   }
15397
15398   // Erase the pseudo instruction
15399   MI->eraseFromParent();
15400
15401   return endMBB;
15402 }
15403
15404 MachineBasicBlock *
15405 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15406                                                  MachineInstr *MI,
15407                                                  MachineBasicBlock *MBB) const {
15408   // Emit code to save XMM registers to the stack. The ABI says that the
15409   // number of registers to save is given in %al, so it's theoretically
15410   // possible to do an indirect jump trick to avoid saving all of them,
15411   // however this code takes a simpler approach and just executes all
15412   // of the stores if %al is non-zero. It's less code, and it's probably
15413   // easier on the hardware branch predictor, and stores aren't all that
15414   // expensive anyway.
15415
15416   // Create the new basic blocks. One block contains all the XMM stores,
15417   // and one block is the final destination regardless of whether any
15418   // stores were performed.
15419   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15420   MachineFunction *F = MBB->getParent();
15421   MachineFunction::iterator MBBIter = MBB;
15422   ++MBBIter;
15423   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15424   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15425   F->insert(MBBIter, XMMSaveMBB);
15426   F->insert(MBBIter, EndMBB);
15427
15428   // Transfer the remainder of MBB and its successor edges to EndMBB.
15429   EndMBB->splice(EndMBB->begin(), MBB,
15430                  llvm::next(MachineBasicBlock::iterator(MI)),
15431                  MBB->end());
15432   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15433
15434   // The original block will now fall through to the XMM save block.
15435   MBB->addSuccessor(XMMSaveMBB);
15436   // The XMMSaveMBB will fall through to the end block.
15437   XMMSaveMBB->addSuccessor(EndMBB);
15438
15439   // Now add the instructions.
15440   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15441   DebugLoc DL = MI->getDebugLoc();
15442
15443   unsigned CountReg = MI->getOperand(0).getReg();
15444   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15445   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15446
15447   if (!Subtarget->isTargetWin64()) {
15448     // If %al is 0, branch around the XMM save block.
15449     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15450     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15451     MBB->addSuccessor(EndMBB);
15452   }
15453
15454   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15455   // that was just emitted, but clearly shouldn't be "saved".
15456   assert((MI->getNumOperands() <= 3 ||
15457           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15458           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15459          && "Expected last argument to be EFLAGS");
15460   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15461   // In the XMM save block, save all the XMM argument registers.
15462   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15463     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15464     MachineMemOperand *MMO =
15465       F->getMachineMemOperand(
15466           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15467         MachineMemOperand::MOStore,
15468         /*Size=*/16, /*Align=*/16);
15469     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15470       .addFrameIndex(RegSaveFrameIndex)
15471       .addImm(/*Scale=*/1)
15472       .addReg(/*IndexReg=*/0)
15473       .addImm(/*Disp=*/Offset)
15474       .addReg(/*Segment=*/0)
15475       .addReg(MI->getOperand(i).getReg())
15476       .addMemOperand(MMO);
15477   }
15478
15479   MI->eraseFromParent();   // The pseudo instruction is gone now.
15480
15481   return EndMBB;
15482 }
15483
15484 // The EFLAGS operand of SelectItr might be missing a kill marker
15485 // because there were multiple uses of EFLAGS, and ISel didn't know
15486 // which to mark. Figure out whether SelectItr should have had a
15487 // kill marker, and set it if it should. Returns the correct kill
15488 // marker value.
15489 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15490                                      MachineBasicBlock* BB,
15491                                      const TargetRegisterInfo* TRI) {
15492   // Scan forward through BB for a use/def of EFLAGS.
15493   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
15494   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15495     const MachineInstr& mi = *miI;
15496     if (mi.readsRegister(X86::EFLAGS))
15497       return false;
15498     if (mi.definesRegister(X86::EFLAGS))
15499       break; // Should have kill-flag - update below.
15500   }
15501
15502   // If we hit the end of the block, check whether EFLAGS is live into a
15503   // successor.
15504   if (miI == BB->end()) {
15505     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15506                                           sEnd = BB->succ_end();
15507          sItr != sEnd; ++sItr) {
15508       MachineBasicBlock* succ = *sItr;
15509       if (succ->isLiveIn(X86::EFLAGS))
15510         return false;
15511     }
15512   }
15513
15514   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15515   // out. SelectMI should have a kill flag on EFLAGS.
15516   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15517   return true;
15518 }
15519
15520 MachineBasicBlock *
15521 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15522                                      MachineBasicBlock *BB) const {
15523   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15524   DebugLoc DL = MI->getDebugLoc();
15525
15526   // To "insert" a SELECT_CC instruction, we actually have to insert the
15527   // diamond control-flow pattern.  The incoming instruction knows the
15528   // destination vreg to set, the condition code register to branch on, the
15529   // true/false values to select between, and a branch opcode to use.
15530   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15531   MachineFunction::iterator It = BB;
15532   ++It;
15533
15534   //  thisMBB:
15535   //  ...
15536   //   TrueVal = ...
15537   //   cmpTY ccX, r1, r2
15538   //   bCC copy1MBB
15539   //   fallthrough --> copy0MBB
15540   MachineBasicBlock *thisMBB = BB;
15541   MachineFunction *F = BB->getParent();
15542   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15543   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15544   F->insert(It, copy0MBB);
15545   F->insert(It, sinkMBB);
15546
15547   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15548   // live into the sink and copy blocks.
15549   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15550   if (!MI->killsRegister(X86::EFLAGS) &&
15551       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15552     copy0MBB->addLiveIn(X86::EFLAGS);
15553     sinkMBB->addLiveIn(X86::EFLAGS);
15554   }
15555
15556   // Transfer the remainder of BB and its successor edges to sinkMBB.
15557   sinkMBB->splice(sinkMBB->begin(), BB,
15558                   llvm::next(MachineBasicBlock::iterator(MI)),
15559                   BB->end());
15560   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15561
15562   // Add the true and fallthrough blocks as its successors.
15563   BB->addSuccessor(copy0MBB);
15564   BB->addSuccessor(sinkMBB);
15565
15566   // Create the conditional branch instruction.
15567   unsigned Opc =
15568     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15569   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15570
15571   //  copy0MBB:
15572   //   %FalseValue = ...
15573   //   # fallthrough to sinkMBB
15574   copy0MBB->addSuccessor(sinkMBB);
15575
15576   //  sinkMBB:
15577   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15578   //  ...
15579   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15580           TII->get(X86::PHI), MI->getOperand(0).getReg())
15581     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15582     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15583
15584   MI->eraseFromParent();   // The pseudo instruction is gone now.
15585   return sinkMBB;
15586 }
15587
15588 MachineBasicBlock *
15589 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15590                                         bool Is64Bit) const {
15591   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15592   DebugLoc DL = MI->getDebugLoc();
15593   MachineFunction *MF = BB->getParent();
15594   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15595
15596   assert(getTargetMachine().Options.EnableSegmentedStacks);
15597
15598   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15599   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15600
15601   // BB:
15602   //  ... [Till the alloca]
15603   // If stacklet is not large enough, jump to mallocMBB
15604   //
15605   // bumpMBB:
15606   //  Allocate by subtracting from RSP
15607   //  Jump to continueMBB
15608   //
15609   // mallocMBB:
15610   //  Allocate by call to runtime
15611   //
15612   // continueMBB:
15613   //  ...
15614   //  [rest of original BB]
15615   //
15616
15617   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15618   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15619   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15620
15621   MachineRegisterInfo &MRI = MF->getRegInfo();
15622   const TargetRegisterClass *AddrRegClass =
15623     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15624
15625   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15626     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15627     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15628     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15629     sizeVReg = MI->getOperand(1).getReg(),
15630     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15631
15632   MachineFunction::iterator MBBIter = BB;
15633   ++MBBIter;
15634
15635   MF->insert(MBBIter, bumpMBB);
15636   MF->insert(MBBIter, mallocMBB);
15637   MF->insert(MBBIter, continueMBB);
15638
15639   continueMBB->splice(continueMBB->begin(), BB, llvm::next
15640                       (MachineBasicBlock::iterator(MI)), BB->end());
15641   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15642
15643   // Add code to the main basic block to check if the stack limit has been hit,
15644   // and if so, jump to mallocMBB otherwise to bumpMBB.
15645   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15646   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15647     .addReg(tmpSPVReg).addReg(sizeVReg);
15648   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15649     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15650     .addReg(SPLimitVReg);
15651   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15652
15653   // bumpMBB simply decreases the stack pointer, since we know the current
15654   // stacklet has enough space.
15655   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15656     .addReg(SPLimitVReg);
15657   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15658     .addReg(SPLimitVReg);
15659   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15660
15661   // Calls into a routine in libgcc to allocate more space from the heap.
15662   const uint32_t *RegMask =
15663     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15664   if (Is64Bit) {
15665     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15666       .addReg(sizeVReg);
15667     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15668       .addExternalSymbol("__morestack_allocate_stack_space")
15669       .addRegMask(RegMask)
15670       .addReg(X86::RDI, RegState::Implicit)
15671       .addReg(X86::RAX, RegState::ImplicitDefine);
15672   } else {
15673     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15674       .addImm(12);
15675     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15676     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15677       .addExternalSymbol("__morestack_allocate_stack_space")
15678       .addRegMask(RegMask)
15679       .addReg(X86::EAX, RegState::ImplicitDefine);
15680   }
15681
15682   if (!Is64Bit)
15683     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15684       .addImm(16);
15685
15686   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15687     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15688   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15689
15690   // Set up the CFG correctly.
15691   BB->addSuccessor(bumpMBB);
15692   BB->addSuccessor(mallocMBB);
15693   mallocMBB->addSuccessor(continueMBB);
15694   bumpMBB->addSuccessor(continueMBB);
15695
15696   // Take care of the PHI nodes.
15697   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15698           MI->getOperand(0).getReg())
15699     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15700     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15701
15702   // Delete the original pseudo instruction.
15703   MI->eraseFromParent();
15704
15705   // And we're done.
15706   return continueMBB;
15707 }
15708
15709 MachineBasicBlock *
15710 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15711                                           MachineBasicBlock *BB) const {
15712   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15713   DebugLoc DL = MI->getDebugLoc();
15714
15715   assert(!Subtarget->isTargetMacho());
15716
15717   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15718   // non-trivial part is impdef of ESP.
15719
15720   if (Subtarget->isTargetWin64()) {
15721     if (Subtarget->isTargetCygMing()) {
15722       // ___chkstk(Mingw64):
15723       // Clobbers R10, R11, RAX and EFLAGS.
15724       // Updates RSP.
15725       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15726         .addExternalSymbol("___chkstk")
15727         .addReg(X86::RAX, RegState::Implicit)
15728         .addReg(X86::RSP, RegState::Implicit)
15729         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15730         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15731         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15732     } else {
15733       // __chkstk(MSVCRT): does not update stack pointer.
15734       // Clobbers R10, R11 and EFLAGS.
15735       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15736         .addExternalSymbol("__chkstk")
15737         .addReg(X86::RAX, RegState::Implicit)
15738         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15739       // RAX has the offset to be subtracted from RSP.
15740       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15741         .addReg(X86::RSP)
15742         .addReg(X86::RAX);
15743     }
15744   } else {
15745     const char *StackProbeSymbol =
15746       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15747
15748     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15749       .addExternalSymbol(StackProbeSymbol)
15750       .addReg(X86::EAX, RegState::Implicit)
15751       .addReg(X86::ESP, RegState::Implicit)
15752       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15753       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15754       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15755   }
15756
15757   MI->eraseFromParent();   // The pseudo instruction is gone now.
15758   return BB;
15759 }
15760
15761 MachineBasicBlock *
15762 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15763                                       MachineBasicBlock *BB) const {
15764   // This is pretty easy.  We're taking the value that we received from
15765   // our load from the relocation, sticking it in either RDI (x86-64)
15766   // or EAX and doing an indirect call.  The return value will then
15767   // be in the normal return register.
15768   const X86InstrInfo *TII
15769     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15770   DebugLoc DL = MI->getDebugLoc();
15771   MachineFunction *F = BB->getParent();
15772
15773   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15774   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15775
15776   // Get a register mask for the lowered call.
15777   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15778   // proper register mask.
15779   const uint32_t *RegMask =
15780     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15781   if (Subtarget->is64Bit()) {
15782     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15783                                       TII->get(X86::MOV64rm), X86::RDI)
15784     .addReg(X86::RIP)
15785     .addImm(0).addReg(0)
15786     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15787                       MI->getOperand(3).getTargetFlags())
15788     .addReg(0);
15789     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15790     addDirectMem(MIB, X86::RDI);
15791     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15792   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15793     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15794                                       TII->get(X86::MOV32rm), X86::EAX)
15795     .addReg(0)
15796     .addImm(0).addReg(0)
15797     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15798                       MI->getOperand(3).getTargetFlags())
15799     .addReg(0);
15800     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15801     addDirectMem(MIB, X86::EAX);
15802     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15803   } else {
15804     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15805                                       TII->get(X86::MOV32rm), X86::EAX)
15806     .addReg(TII->getGlobalBaseReg(F))
15807     .addImm(0).addReg(0)
15808     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15809                       MI->getOperand(3).getTargetFlags())
15810     .addReg(0);
15811     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15812     addDirectMem(MIB, X86::EAX);
15813     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15814   }
15815
15816   MI->eraseFromParent(); // The pseudo instruction is gone now.
15817   return BB;
15818 }
15819
15820 MachineBasicBlock *
15821 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15822                                     MachineBasicBlock *MBB) const {
15823   DebugLoc DL = MI->getDebugLoc();
15824   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15825
15826   MachineFunction *MF = MBB->getParent();
15827   MachineRegisterInfo &MRI = MF->getRegInfo();
15828
15829   const BasicBlock *BB = MBB->getBasicBlock();
15830   MachineFunction::iterator I = MBB;
15831   ++I;
15832
15833   // Memory Reference
15834   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15835   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15836
15837   unsigned DstReg;
15838   unsigned MemOpndSlot = 0;
15839
15840   unsigned CurOp = 0;
15841
15842   DstReg = MI->getOperand(CurOp++).getReg();
15843   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15844   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15845   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15846   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15847
15848   MemOpndSlot = CurOp;
15849
15850   MVT PVT = getPointerTy();
15851   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15852          "Invalid Pointer Size!");
15853
15854   // For v = setjmp(buf), we generate
15855   //
15856   // thisMBB:
15857   //  buf[LabelOffset] = restoreMBB
15858   //  SjLjSetup restoreMBB
15859   //
15860   // mainMBB:
15861   //  v_main = 0
15862   //
15863   // sinkMBB:
15864   //  v = phi(main, restore)
15865   //
15866   // restoreMBB:
15867   //  v_restore = 1
15868
15869   MachineBasicBlock *thisMBB = MBB;
15870   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15871   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15872   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15873   MF->insert(I, mainMBB);
15874   MF->insert(I, sinkMBB);
15875   MF->push_back(restoreMBB);
15876
15877   MachineInstrBuilder MIB;
15878
15879   // Transfer the remainder of BB and its successor edges to sinkMBB.
15880   sinkMBB->splice(sinkMBB->begin(), MBB,
15881                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15882   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15883
15884   // thisMBB:
15885   unsigned PtrStoreOpc = 0;
15886   unsigned LabelReg = 0;
15887   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15888   Reloc::Model RM = getTargetMachine().getRelocationModel();
15889   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15890                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15891
15892   // Prepare IP either in reg or imm.
15893   if (!UseImmLabel) {
15894     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15895     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15896     LabelReg = MRI.createVirtualRegister(PtrRC);
15897     if (Subtarget->is64Bit()) {
15898       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15899               .addReg(X86::RIP)
15900               .addImm(0)
15901               .addReg(0)
15902               .addMBB(restoreMBB)
15903               .addReg(0);
15904     } else {
15905       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15906       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15907               .addReg(XII->getGlobalBaseReg(MF))
15908               .addImm(0)
15909               .addReg(0)
15910               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15911               .addReg(0);
15912     }
15913   } else
15914     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15915   // Store IP
15916   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15917   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15918     if (i == X86::AddrDisp)
15919       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15920     else
15921       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15922   }
15923   if (!UseImmLabel)
15924     MIB.addReg(LabelReg);
15925   else
15926     MIB.addMBB(restoreMBB);
15927   MIB.setMemRefs(MMOBegin, MMOEnd);
15928   // Setup
15929   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15930           .addMBB(restoreMBB);
15931
15932   const X86RegisterInfo *RegInfo =
15933     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15934   MIB.addRegMask(RegInfo->getNoPreservedMask());
15935   thisMBB->addSuccessor(mainMBB);
15936   thisMBB->addSuccessor(restoreMBB);
15937
15938   // mainMBB:
15939   //  EAX = 0
15940   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15941   mainMBB->addSuccessor(sinkMBB);
15942
15943   // sinkMBB:
15944   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15945           TII->get(X86::PHI), DstReg)
15946     .addReg(mainDstReg).addMBB(mainMBB)
15947     .addReg(restoreDstReg).addMBB(restoreMBB);
15948
15949   // restoreMBB:
15950   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15951   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15952   restoreMBB->addSuccessor(sinkMBB);
15953
15954   MI->eraseFromParent();
15955   return sinkMBB;
15956 }
15957
15958 MachineBasicBlock *
15959 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15960                                      MachineBasicBlock *MBB) const {
15961   DebugLoc DL = MI->getDebugLoc();
15962   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15963
15964   MachineFunction *MF = MBB->getParent();
15965   MachineRegisterInfo &MRI = MF->getRegInfo();
15966
15967   // Memory Reference
15968   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15969   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15970
15971   MVT PVT = getPointerTy();
15972   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15973          "Invalid Pointer Size!");
15974
15975   const TargetRegisterClass *RC =
15976     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15977   unsigned Tmp = MRI.createVirtualRegister(RC);
15978   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15979   const X86RegisterInfo *RegInfo =
15980     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15981   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15982   unsigned SP = RegInfo->getStackRegister();
15983
15984   MachineInstrBuilder MIB;
15985
15986   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15987   const int64_t SPOffset = 2 * PVT.getStoreSize();
15988
15989   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15990   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15991
15992   // Reload FP
15993   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15994   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15995     MIB.addOperand(MI->getOperand(i));
15996   MIB.setMemRefs(MMOBegin, MMOEnd);
15997   // Reload IP
15998   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15999   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16000     if (i == X86::AddrDisp)
16001       MIB.addDisp(MI->getOperand(i), LabelOffset);
16002     else
16003       MIB.addOperand(MI->getOperand(i));
16004   }
16005   MIB.setMemRefs(MMOBegin, MMOEnd);
16006   // Reload SP
16007   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16008   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16009     if (i == X86::AddrDisp)
16010       MIB.addDisp(MI->getOperand(i), SPOffset);
16011     else
16012       MIB.addOperand(MI->getOperand(i));
16013   }
16014   MIB.setMemRefs(MMOBegin, MMOEnd);
16015   // Jump
16016   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16017
16018   MI->eraseFromParent();
16019   return MBB;
16020 }
16021
16022 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16023 // accumulator loops. Writing back to the accumulator allows the coalescer
16024 // to remove extra copies in the loop.   
16025 MachineBasicBlock *
16026 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16027                                  MachineBasicBlock *MBB) const {
16028   MachineOperand &AddendOp = MI->getOperand(3);
16029
16030   // Bail out early if the addend isn't a register - we can't switch these.
16031   if (!AddendOp.isReg())
16032     return MBB;
16033
16034   MachineFunction &MF = *MBB->getParent();
16035   MachineRegisterInfo &MRI = MF.getRegInfo();
16036
16037   // Check whether the addend is defined by a PHI:
16038   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16039   MachineInstr &AddendDef = *MRI.def_begin(AddendOp.getReg());
16040   if (!AddendDef.isPHI())
16041     return MBB;
16042
16043   // Look for the following pattern:
16044   // loop:
16045   //   %addend = phi [%entry, 0], [%loop, %result]
16046   //   ...
16047   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16048
16049   // Replace with:
16050   //   loop:
16051   //   %addend = phi [%entry, 0], [%loop, %result]
16052   //   ...
16053   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16054
16055   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16056     assert(AddendDef.getOperand(i).isReg());
16057     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16058     MachineInstr &PHISrcInst = *MRI.def_begin(PHISrcOp.getReg());
16059     if (&PHISrcInst == MI) {
16060       // Found a matching instruction.
16061       unsigned NewFMAOpc = 0;
16062       switch (MI->getOpcode()) {
16063         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16064         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16065         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16066         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16067         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16068         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16069         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16070         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16071         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16072         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16073         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16074         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16075         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16076         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16077         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16078         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16079         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16080         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16081         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16082         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16083         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16084         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16085         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16086         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16087         default: llvm_unreachable("Unrecognized FMA variant.");
16088       }
16089
16090       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16091       MachineInstrBuilder MIB =
16092         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16093         .addOperand(MI->getOperand(0))
16094         .addOperand(MI->getOperand(3))
16095         .addOperand(MI->getOperand(2))
16096         .addOperand(MI->getOperand(1));
16097       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16098       MI->eraseFromParent();
16099     }
16100   }
16101
16102   return MBB;
16103 }
16104
16105 MachineBasicBlock *
16106 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16107                                                MachineBasicBlock *BB) const {
16108   switch (MI->getOpcode()) {
16109   default: llvm_unreachable("Unexpected instr type to insert");
16110   case X86::TAILJMPd64:
16111   case X86::TAILJMPr64:
16112   case X86::TAILJMPm64:
16113     llvm_unreachable("TAILJMP64 would not be touched here.");
16114   case X86::TCRETURNdi64:
16115   case X86::TCRETURNri64:
16116   case X86::TCRETURNmi64:
16117     return BB;
16118   case X86::WIN_ALLOCA:
16119     return EmitLoweredWinAlloca(MI, BB);
16120   case X86::SEG_ALLOCA_32:
16121     return EmitLoweredSegAlloca(MI, BB, false);
16122   case X86::SEG_ALLOCA_64:
16123     return EmitLoweredSegAlloca(MI, BB, true);
16124   case X86::TLSCall_32:
16125   case X86::TLSCall_64:
16126     return EmitLoweredTLSCall(MI, BB);
16127   case X86::CMOV_GR8:
16128   case X86::CMOV_FR32:
16129   case X86::CMOV_FR64:
16130   case X86::CMOV_V4F32:
16131   case X86::CMOV_V2F64:
16132   case X86::CMOV_V2I64:
16133   case X86::CMOV_V8F32:
16134   case X86::CMOV_V4F64:
16135   case X86::CMOV_V4I64:
16136   case X86::CMOV_V16F32:
16137   case X86::CMOV_V8F64:
16138   case X86::CMOV_V8I64:
16139   case X86::CMOV_GR16:
16140   case X86::CMOV_GR32:
16141   case X86::CMOV_RFP32:
16142   case X86::CMOV_RFP64:
16143   case X86::CMOV_RFP80:
16144     return EmitLoweredSelect(MI, BB);
16145
16146   case X86::FP32_TO_INT16_IN_MEM:
16147   case X86::FP32_TO_INT32_IN_MEM:
16148   case X86::FP32_TO_INT64_IN_MEM:
16149   case X86::FP64_TO_INT16_IN_MEM:
16150   case X86::FP64_TO_INT32_IN_MEM:
16151   case X86::FP64_TO_INT64_IN_MEM:
16152   case X86::FP80_TO_INT16_IN_MEM:
16153   case X86::FP80_TO_INT32_IN_MEM:
16154   case X86::FP80_TO_INT64_IN_MEM: {
16155     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16156     DebugLoc DL = MI->getDebugLoc();
16157
16158     // Change the floating point control register to use "round towards zero"
16159     // mode when truncating to an integer value.
16160     MachineFunction *F = BB->getParent();
16161     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16162     addFrameReference(BuildMI(*BB, MI, DL,
16163                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16164
16165     // Load the old value of the high byte of the control word...
16166     unsigned OldCW =
16167       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16168     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16169                       CWFrameIdx);
16170
16171     // Set the high part to be round to zero...
16172     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16173       .addImm(0xC7F);
16174
16175     // Reload the modified control word now...
16176     addFrameReference(BuildMI(*BB, MI, DL,
16177                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16178
16179     // Restore the memory image of control word to original value
16180     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16181       .addReg(OldCW);
16182
16183     // Get the X86 opcode to use.
16184     unsigned Opc;
16185     switch (MI->getOpcode()) {
16186     default: llvm_unreachable("illegal opcode!");
16187     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16188     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16189     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16190     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16191     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16192     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16193     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16194     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16195     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16196     }
16197
16198     X86AddressMode AM;
16199     MachineOperand &Op = MI->getOperand(0);
16200     if (Op.isReg()) {
16201       AM.BaseType = X86AddressMode::RegBase;
16202       AM.Base.Reg = Op.getReg();
16203     } else {
16204       AM.BaseType = X86AddressMode::FrameIndexBase;
16205       AM.Base.FrameIndex = Op.getIndex();
16206     }
16207     Op = MI->getOperand(1);
16208     if (Op.isImm())
16209       AM.Scale = Op.getImm();
16210     Op = MI->getOperand(2);
16211     if (Op.isImm())
16212       AM.IndexReg = Op.getImm();
16213     Op = MI->getOperand(3);
16214     if (Op.isGlobal()) {
16215       AM.GV = Op.getGlobal();
16216     } else {
16217       AM.Disp = Op.getImm();
16218     }
16219     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16220                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16221
16222     // Reload the original control word now.
16223     addFrameReference(BuildMI(*BB, MI, DL,
16224                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16225
16226     MI->eraseFromParent();   // The pseudo instruction is gone now.
16227     return BB;
16228   }
16229     // String/text processing lowering.
16230   case X86::PCMPISTRM128REG:
16231   case X86::VPCMPISTRM128REG:
16232   case X86::PCMPISTRM128MEM:
16233   case X86::VPCMPISTRM128MEM:
16234   case X86::PCMPESTRM128REG:
16235   case X86::VPCMPESTRM128REG:
16236   case X86::PCMPESTRM128MEM:
16237   case X86::VPCMPESTRM128MEM:
16238     assert(Subtarget->hasSSE42() &&
16239            "Target must have SSE4.2 or AVX features enabled");
16240     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16241
16242   // String/text processing lowering.
16243   case X86::PCMPISTRIREG:
16244   case X86::VPCMPISTRIREG:
16245   case X86::PCMPISTRIMEM:
16246   case X86::VPCMPISTRIMEM:
16247   case X86::PCMPESTRIREG:
16248   case X86::VPCMPESTRIREG:
16249   case X86::PCMPESTRIMEM:
16250   case X86::VPCMPESTRIMEM:
16251     assert(Subtarget->hasSSE42() &&
16252            "Target must have SSE4.2 or AVX features enabled");
16253     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16254
16255   // Thread synchronization.
16256   case X86::MONITOR:
16257     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16258
16259   // xbegin
16260   case X86::XBEGIN:
16261     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16262
16263   // Atomic Lowering.
16264   case X86::ATOMAND8:
16265   case X86::ATOMAND16:
16266   case X86::ATOMAND32:
16267   case X86::ATOMAND64:
16268     // Fall through
16269   case X86::ATOMOR8:
16270   case X86::ATOMOR16:
16271   case X86::ATOMOR32:
16272   case X86::ATOMOR64:
16273     // Fall through
16274   case X86::ATOMXOR16:
16275   case X86::ATOMXOR8:
16276   case X86::ATOMXOR32:
16277   case X86::ATOMXOR64:
16278     // Fall through
16279   case X86::ATOMNAND8:
16280   case X86::ATOMNAND16:
16281   case X86::ATOMNAND32:
16282   case X86::ATOMNAND64:
16283     // Fall through
16284   case X86::ATOMMAX8:
16285   case X86::ATOMMAX16:
16286   case X86::ATOMMAX32:
16287   case X86::ATOMMAX64:
16288     // Fall through
16289   case X86::ATOMMIN8:
16290   case X86::ATOMMIN16:
16291   case X86::ATOMMIN32:
16292   case X86::ATOMMIN64:
16293     // Fall through
16294   case X86::ATOMUMAX8:
16295   case X86::ATOMUMAX16:
16296   case X86::ATOMUMAX32:
16297   case X86::ATOMUMAX64:
16298     // Fall through
16299   case X86::ATOMUMIN8:
16300   case X86::ATOMUMIN16:
16301   case X86::ATOMUMIN32:
16302   case X86::ATOMUMIN64:
16303     return EmitAtomicLoadArith(MI, BB);
16304
16305   // This group does 64-bit operations on a 32-bit host.
16306   case X86::ATOMAND6432:
16307   case X86::ATOMOR6432:
16308   case X86::ATOMXOR6432:
16309   case X86::ATOMNAND6432:
16310   case X86::ATOMADD6432:
16311   case X86::ATOMSUB6432:
16312   case X86::ATOMMAX6432:
16313   case X86::ATOMMIN6432:
16314   case X86::ATOMUMAX6432:
16315   case X86::ATOMUMIN6432:
16316   case X86::ATOMSWAP6432:
16317     return EmitAtomicLoadArith6432(MI, BB);
16318
16319   case X86::VASTART_SAVE_XMM_REGS:
16320     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16321
16322   case X86::VAARG_64:
16323     return EmitVAARG64WithCustomInserter(MI, BB);
16324
16325   case X86::EH_SjLj_SetJmp32:
16326   case X86::EH_SjLj_SetJmp64:
16327     return emitEHSjLjSetJmp(MI, BB);
16328
16329   case X86::EH_SjLj_LongJmp32:
16330   case X86::EH_SjLj_LongJmp64:
16331     return emitEHSjLjLongJmp(MI, BB);
16332
16333   case TargetOpcode::STACKMAP:
16334   case TargetOpcode::PATCHPOINT:
16335     return emitPatchPoint(MI, BB);
16336
16337   case X86::VFMADDPDr213r:
16338   case X86::VFMADDPSr213r:
16339   case X86::VFMADDSDr213r:
16340   case X86::VFMADDSSr213r:
16341   case X86::VFMSUBPDr213r:
16342   case X86::VFMSUBPSr213r:
16343   case X86::VFMSUBSDr213r:
16344   case X86::VFMSUBSSr213r:
16345   case X86::VFNMADDPDr213r:
16346   case X86::VFNMADDPSr213r:
16347   case X86::VFNMADDSDr213r:
16348   case X86::VFNMADDSSr213r:
16349   case X86::VFNMSUBPDr213r:
16350   case X86::VFNMSUBPSr213r:
16351   case X86::VFNMSUBSDr213r:
16352   case X86::VFNMSUBSSr213r:
16353   case X86::VFMADDPDr213rY:
16354   case X86::VFMADDPSr213rY:
16355   case X86::VFMSUBPDr213rY:
16356   case X86::VFMSUBPSr213rY:
16357   case X86::VFNMADDPDr213rY:
16358   case X86::VFNMADDPSr213rY:
16359   case X86::VFNMSUBPDr213rY:
16360   case X86::VFNMSUBPSr213rY:
16361     return emitFMA3Instr(MI, BB);
16362   }
16363 }
16364
16365 //===----------------------------------------------------------------------===//
16366 //                           X86 Optimization Hooks
16367 //===----------------------------------------------------------------------===//
16368
16369 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16370                                                        APInt &KnownZero,
16371                                                        APInt &KnownOne,
16372                                                        const SelectionDAG &DAG,
16373                                                        unsigned Depth) const {
16374   unsigned BitWidth = KnownZero.getBitWidth();
16375   unsigned Opc = Op.getOpcode();
16376   assert((Opc >= ISD::BUILTIN_OP_END ||
16377           Opc == ISD::INTRINSIC_WO_CHAIN ||
16378           Opc == ISD::INTRINSIC_W_CHAIN ||
16379           Opc == ISD::INTRINSIC_VOID) &&
16380          "Should use MaskedValueIsZero if you don't know whether Op"
16381          " is a target node!");
16382
16383   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16384   switch (Opc) {
16385   default: break;
16386   case X86ISD::ADD:
16387   case X86ISD::SUB:
16388   case X86ISD::ADC:
16389   case X86ISD::SBB:
16390   case X86ISD::SMUL:
16391   case X86ISD::UMUL:
16392   case X86ISD::INC:
16393   case X86ISD::DEC:
16394   case X86ISD::OR:
16395   case X86ISD::XOR:
16396   case X86ISD::AND:
16397     // These nodes' second result is a boolean.
16398     if (Op.getResNo() == 0)
16399       break;
16400     // Fallthrough
16401   case X86ISD::SETCC:
16402     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16403     break;
16404   case ISD::INTRINSIC_WO_CHAIN: {
16405     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16406     unsigned NumLoBits = 0;
16407     switch (IntId) {
16408     default: break;
16409     case Intrinsic::x86_sse_movmsk_ps:
16410     case Intrinsic::x86_avx_movmsk_ps_256:
16411     case Intrinsic::x86_sse2_movmsk_pd:
16412     case Intrinsic::x86_avx_movmsk_pd_256:
16413     case Intrinsic::x86_mmx_pmovmskb:
16414     case Intrinsic::x86_sse2_pmovmskb_128:
16415     case Intrinsic::x86_avx2_pmovmskb: {
16416       // High bits of movmskp{s|d}, pmovmskb are known zero.
16417       switch (IntId) {
16418         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16419         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16420         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16421         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16422         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16423         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16424         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16425         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16426       }
16427       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16428       break;
16429     }
16430     }
16431     break;
16432   }
16433   }
16434 }
16435
16436 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16437                                                          unsigned Depth) const {
16438   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16439   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16440     return Op.getValueType().getScalarType().getSizeInBits();
16441
16442   // Fallback case.
16443   return 1;
16444 }
16445
16446 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16447 /// node is a GlobalAddress + offset.
16448 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16449                                        const GlobalValue* &GA,
16450                                        int64_t &Offset) const {
16451   if (N->getOpcode() == X86ISD::Wrapper) {
16452     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16453       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16454       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16455       return true;
16456     }
16457   }
16458   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16459 }
16460
16461 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16462 /// same as extracting the high 128-bit part of 256-bit vector and then
16463 /// inserting the result into the low part of a new 256-bit vector
16464 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16465   EVT VT = SVOp->getValueType(0);
16466   unsigned NumElems = VT.getVectorNumElements();
16467
16468   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16469   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16470     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16471         SVOp->getMaskElt(j) >= 0)
16472       return false;
16473
16474   return true;
16475 }
16476
16477 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16478 /// same as extracting the low 128-bit part of 256-bit vector and then
16479 /// inserting the result into the high part of a new 256-bit vector
16480 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16481   EVT VT = SVOp->getValueType(0);
16482   unsigned NumElems = VT.getVectorNumElements();
16483
16484   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16485   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16486     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16487         SVOp->getMaskElt(j) >= 0)
16488       return false;
16489
16490   return true;
16491 }
16492
16493 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16494 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16495                                         TargetLowering::DAGCombinerInfo &DCI,
16496                                         const X86Subtarget* Subtarget) {
16497   SDLoc dl(N);
16498   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16499   SDValue V1 = SVOp->getOperand(0);
16500   SDValue V2 = SVOp->getOperand(1);
16501   EVT VT = SVOp->getValueType(0);
16502   unsigned NumElems = VT.getVectorNumElements();
16503
16504   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16505       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16506     //
16507     //                   0,0,0,...
16508     //                      |
16509     //    V      UNDEF    BUILD_VECTOR    UNDEF
16510     //     \      /           \           /
16511     //  CONCAT_VECTOR         CONCAT_VECTOR
16512     //         \                  /
16513     //          \                /
16514     //          RESULT: V + zero extended
16515     //
16516     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16517         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16518         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16519       return SDValue();
16520
16521     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16522       return SDValue();
16523
16524     // To match the shuffle mask, the first half of the mask should
16525     // be exactly the first vector, and all the rest a splat with the
16526     // first element of the second one.
16527     for (unsigned i = 0; i != NumElems/2; ++i)
16528       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16529           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16530         return SDValue();
16531
16532     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16533     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16534       if (Ld->hasNUsesOfValue(1, 0)) {
16535         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16536         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16537         SDValue ResNode =
16538           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16539                                   array_lengthof(Ops),
16540                                   Ld->getMemoryVT(),
16541                                   Ld->getPointerInfo(),
16542                                   Ld->getAlignment(),
16543                                   false/*isVolatile*/, true/*ReadMem*/,
16544                                   false/*WriteMem*/);
16545
16546         // Make sure the newly-created LOAD is in the same position as Ld in
16547         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16548         // and update uses of Ld's output chain to use the TokenFactor.
16549         if (Ld->hasAnyUseOfValue(1)) {
16550           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16551                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16552           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16553           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16554                                  SDValue(ResNode.getNode(), 1));
16555         }
16556
16557         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16558       }
16559     }
16560
16561     // Emit a zeroed vector and insert the desired subvector on its
16562     // first half.
16563     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16564     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16565     return DCI.CombineTo(N, InsV);
16566   }
16567
16568   //===--------------------------------------------------------------------===//
16569   // Combine some shuffles into subvector extracts and inserts:
16570   //
16571
16572   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16573   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16574     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16575     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16576     return DCI.CombineTo(N, InsV);
16577   }
16578
16579   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16580   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16581     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16582     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16583     return DCI.CombineTo(N, InsV);
16584   }
16585
16586   return SDValue();
16587 }
16588
16589 /// PerformShuffleCombine - Performs several different shuffle combines.
16590 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16591                                      TargetLowering::DAGCombinerInfo &DCI,
16592                                      const X86Subtarget *Subtarget) {
16593   SDLoc dl(N);
16594   EVT VT = N->getValueType(0);
16595
16596   // Don't create instructions with illegal types after legalize types has run.
16597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16598   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16599     return SDValue();
16600
16601   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16602   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16603       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16604     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16605
16606   // Only handle 128 wide vector from here on.
16607   if (!VT.is128BitVector())
16608     return SDValue();
16609
16610   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16611   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16612   // consecutive, non-overlapping, and in the right order.
16613   SmallVector<SDValue, 16> Elts;
16614   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16615     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16616
16617   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16618 }
16619
16620 /// PerformTruncateCombine - Converts truncate operation to
16621 /// a sequence of vector shuffle operations.
16622 /// It is possible when we truncate 256-bit vector to 128-bit vector
16623 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16624                                       TargetLowering::DAGCombinerInfo &DCI,
16625                                       const X86Subtarget *Subtarget)  {
16626   return SDValue();
16627 }
16628
16629 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16630 /// specific shuffle of a load can be folded into a single element load.
16631 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16632 /// shuffles have been customed lowered so we need to handle those here.
16633 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16634                                          TargetLowering::DAGCombinerInfo &DCI) {
16635   if (DCI.isBeforeLegalizeOps())
16636     return SDValue();
16637
16638   SDValue InVec = N->getOperand(0);
16639   SDValue EltNo = N->getOperand(1);
16640
16641   if (!isa<ConstantSDNode>(EltNo))
16642     return SDValue();
16643
16644   EVT VT = InVec.getValueType();
16645
16646   bool HasShuffleIntoBitcast = false;
16647   if (InVec.getOpcode() == ISD::BITCAST) {
16648     // Don't duplicate a load with other uses.
16649     if (!InVec.hasOneUse())
16650       return SDValue();
16651     EVT BCVT = InVec.getOperand(0).getValueType();
16652     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16653       return SDValue();
16654     InVec = InVec.getOperand(0);
16655     HasShuffleIntoBitcast = true;
16656   }
16657
16658   if (!isTargetShuffle(InVec.getOpcode()))
16659     return SDValue();
16660
16661   // Don't duplicate a load with other uses.
16662   if (!InVec.hasOneUse())
16663     return SDValue();
16664
16665   SmallVector<int, 16> ShuffleMask;
16666   bool UnaryShuffle;
16667   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16668                             UnaryShuffle))
16669     return SDValue();
16670
16671   // Select the input vector, guarding against out of range extract vector.
16672   unsigned NumElems = VT.getVectorNumElements();
16673   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16674   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16675   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16676                                          : InVec.getOperand(1);
16677
16678   // If inputs to shuffle are the same for both ops, then allow 2 uses
16679   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16680
16681   if (LdNode.getOpcode() == ISD::BITCAST) {
16682     // Don't duplicate a load with other uses.
16683     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16684       return SDValue();
16685
16686     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16687     LdNode = LdNode.getOperand(0);
16688   }
16689
16690   if (!ISD::isNormalLoad(LdNode.getNode()))
16691     return SDValue();
16692
16693   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16694
16695   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16696     return SDValue();
16697
16698   if (HasShuffleIntoBitcast) {
16699     // If there's a bitcast before the shuffle, check if the load type and
16700     // alignment is valid.
16701     unsigned Align = LN0->getAlignment();
16702     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16703     unsigned NewAlign = TLI.getDataLayout()->
16704       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16705
16706     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16707       return SDValue();
16708   }
16709
16710   // All checks match so transform back to vector_shuffle so that DAG combiner
16711   // can finish the job
16712   SDLoc dl(N);
16713
16714   // Create shuffle node taking into account the case that its a unary shuffle
16715   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16716   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16717                                  InVec.getOperand(0), Shuffle,
16718                                  &ShuffleMask[0]);
16719   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16720   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16721                      EltNo);
16722 }
16723
16724 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16725 /// generation and convert it from being a bunch of shuffles and extracts
16726 /// to a simple store and scalar loads to extract the elements.
16727 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16728                                          TargetLowering::DAGCombinerInfo &DCI) {
16729   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16730   if (NewOp.getNode())
16731     return NewOp;
16732
16733   SDValue InputVector = N->getOperand(0);
16734
16735   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16736   // from mmx to v2i32 has a single usage.
16737   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16738       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16739       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16740     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16741                        N->getValueType(0),
16742                        InputVector.getNode()->getOperand(0));
16743
16744   // Only operate on vectors of 4 elements, where the alternative shuffling
16745   // gets to be more expensive.
16746   if (InputVector.getValueType() != MVT::v4i32)
16747     return SDValue();
16748
16749   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16750   // single use which is a sign-extend or zero-extend, and all elements are
16751   // used.
16752   SmallVector<SDNode *, 4> Uses;
16753   unsigned ExtractedElements = 0;
16754   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16755        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16756     if (UI.getUse().getResNo() != InputVector.getResNo())
16757       return SDValue();
16758
16759     SDNode *Extract = *UI;
16760     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16761       return SDValue();
16762
16763     if (Extract->getValueType(0) != MVT::i32)
16764       return SDValue();
16765     if (!Extract->hasOneUse())
16766       return SDValue();
16767     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16768         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16769       return SDValue();
16770     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16771       return SDValue();
16772
16773     // Record which element was extracted.
16774     ExtractedElements |=
16775       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16776
16777     Uses.push_back(Extract);
16778   }
16779
16780   // If not all the elements were used, this may not be worthwhile.
16781   if (ExtractedElements != 15)
16782     return SDValue();
16783
16784   // Ok, we've now decided to do the transformation.
16785   SDLoc dl(InputVector);
16786
16787   // Store the value to a temporary stack slot.
16788   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16789   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16790                             MachinePointerInfo(), false, false, 0);
16791
16792   // Replace each use (extract) with a load of the appropriate element.
16793   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16794        UE = Uses.end(); UI != UE; ++UI) {
16795     SDNode *Extract = *UI;
16796
16797     // cOMpute the element's address.
16798     SDValue Idx = Extract->getOperand(1);
16799     unsigned EltSize =
16800         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16801     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16802     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16803     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16804
16805     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16806                                      StackPtr, OffsetVal);
16807
16808     // Load the scalar.
16809     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16810                                      ScalarAddr, MachinePointerInfo(),
16811                                      false, false, false, 0);
16812
16813     // Replace the exact with the load.
16814     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16815   }
16816
16817   // The replacement was made in place; don't return anything.
16818   return SDValue();
16819 }
16820
16821 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16822 static std::pair<unsigned, bool>
16823 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16824                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16825   if (!VT.isVector())
16826     return std::make_pair(0, false);
16827
16828   bool NeedSplit = false;
16829   switch (VT.getSimpleVT().SimpleTy) {
16830   default: return std::make_pair(0, false);
16831   case MVT::v32i8:
16832   case MVT::v16i16:
16833   case MVT::v8i32:
16834     if (!Subtarget->hasAVX2())
16835       NeedSplit = true;
16836     if (!Subtarget->hasAVX())
16837       return std::make_pair(0, false);
16838     break;
16839   case MVT::v16i8:
16840   case MVT::v8i16:
16841   case MVT::v4i32:
16842     if (!Subtarget->hasSSE2())
16843       return std::make_pair(0, false);
16844   }
16845
16846   // SSE2 has only a small subset of the operations.
16847   bool hasUnsigned = Subtarget->hasSSE41() ||
16848                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16849   bool hasSigned = Subtarget->hasSSE41() ||
16850                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16851
16852   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16853
16854   unsigned Opc = 0;
16855   // Check for x CC y ? x : y.
16856   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16857       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16858     switch (CC) {
16859     default: break;
16860     case ISD::SETULT:
16861     case ISD::SETULE:
16862       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16863     case ISD::SETUGT:
16864     case ISD::SETUGE:
16865       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16866     case ISD::SETLT:
16867     case ISD::SETLE:
16868       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16869     case ISD::SETGT:
16870     case ISD::SETGE:
16871       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16872     }
16873   // Check for x CC y ? y : x -- a min/max with reversed arms.
16874   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16875              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16876     switch (CC) {
16877     default: break;
16878     case ISD::SETULT:
16879     case ISD::SETULE:
16880       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16881     case ISD::SETUGT:
16882     case ISD::SETUGE:
16883       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16884     case ISD::SETLT:
16885     case ISD::SETLE:
16886       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16887     case ISD::SETGT:
16888     case ISD::SETGE:
16889       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16890     }
16891   }
16892
16893   return std::make_pair(Opc, NeedSplit);
16894 }
16895
16896 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16897 /// nodes.
16898 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16899                                     TargetLowering::DAGCombinerInfo &DCI,
16900                                     const X86Subtarget *Subtarget) {
16901   SDLoc DL(N);
16902   SDValue Cond = N->getOperand(0);
16903   // Get the LHS/RHS of the select.
16904   SDValue LHS = N->getOperand(1);
16905   SDValue RHS = N->getOperand(2);
16906   EVT VT = LHS.getValueType();
16907   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16908
16909   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16910   // instructions match the semantics of the common C idiom x<y?x:y but not
16911   // x<=y?x:y, because of how they handle negative zero (which can be
16912   // ignored in unsafe-math mode).
16913   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16914       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
16915       (Subtarget->hasSSE2() ||
16916        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16917     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16918
16919     unsigned Opcode = 0;
16920     // Check for x CC y ? x : y.
16921     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16922         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16923       switch (CC) {
16924       default: break;
16925       case ISD::SETULT:
16926         // Converting this to a min would handle NaNs incorrectly, and swapping
16927         // the operands would cause it to handle comparisons between positive
16928         // and negative zero incorrectly.
16929         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16930           if (!DAG.getTarget().Options.UnsafeFPMath &&
16931               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16932             break;
16933           std::swap(LHS, RHS);
16934         }
16935         Opcode = X86ISD::FMIN;
16936         break;
16937       case ISD::SETOLE:
16938         // Converting this to a min would handle comparisons between positive
16939         // and negative zero incorrectly.
16940         if (!DAG.getTarget().Options.UnsafeFPMath &&
16941             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16942           break;
16943         Opcode = X86ISD::FMIN;
16944         break;
16945       case ISD::SETULE:
16946         // Converting this to a min would handle both negative zeros and NaNs
16947         // incorrectly, but we can swap the operands to fix both.
16948         std::swap(LHS, RHS);
16949       case ISD::SETOLT:
16950       case ISD::SETLT:
16951       case ISD::SETLE:
16952         Opcode = X86ISD::FMIN;
16953         break;
16954
16955       case ISD::SETOGE:
16956         // Converting this to a max would handle comparisons between positive
16957         // and negative zero incorrectly.
16958         if (!DAG.getTarget().Options.UnsafeFPMath &&
16959             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16960           break;
16961         Opcode = X86ISD::FMAX;
16962         break;
16963       case ISD::SETUGT:
16964         // Converting this to a max would handle NaNs incorrectly, and swapping
16965         // the operands would cause it to handle comparisons between positive
16966         // and negative zero incorrectly.
16967         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16968           if (!DAG.getTarget().Options.UnsafeFPMath &&
16969               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16970             break;
16971           std::swap(LHS, RHS);
16972         }
16973         Opcode = X86ISD::FMAX;
16974         break;
16975       case ISD::SETUGE:
16976         // Converting this to a max would handle both negative zeros and NaNs
16977         // incorrectly, but we can swap the operands to fix both.
16978         std::swap(LHS, RHS);
16979       case ISD::SETOGT:
16980       case ISD::SETGT:
16981       case ISD::SETGE:
16982         Opcode = X86ISD::FMAX;
16983         break;
16984       }
16985     // Check for x CC y ? y : x -- a min/max with reversed arms.
16986     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16987                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16988       switch (CC) {
16989       default: break;
16990       case ISD::SETOGE:
16991         // Converting this to a min would handle comparisons between positive
16992         // and negative zero incorrectly, and swapping the operands would
16993         // cause it to handle NaNs incorrectly.
16994         if (!DAG.getTarget().Options.UnsafeFPMath &&
16995             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16996           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16997             break;
16998           std::swap(LHS, RHS);
16999         }
17000         Opcode = X86ISD::FMIN;
17001         break;
17002       case ISD::SETUGT:
17003         // Converting this to a min would handle NaNs incorrectly.
17004         if (!DAG.getTarget().Options.UnsafeFPMath &&
17005             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17006           break;
17007         Opcode = X86ISD::FMIN;
17008         break;
17009       case ISD::SETUGE:
17010         // Converting this to a min would handle both negative zeros and NaNs
17011         // incorrectly, but we can swap the operands to fix both.
17012         std::swap(LHS, RHS);
17013       case ISD::SETOGT:
17014       case ISD::SETGT:
17015       case ISD::SETGE:
17016         Opcode = X86ISD::FMIN;
17017         break;
17018
17019       case ISD::SETULT:
17020         // Converting this to a max would handle NaNs incorrectly.
17021         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17022           break;
17023         Opcode = X86ISD::FMAX;
17024         break;
17025       case ISD::SETOLE:
17026         // Converting this to a max would handle comparisons between positive
17027         // and negative zero incorrectly, and swapping the operands would
17028         // cause it to handle NaNs incorrectly.
17029         if (!DAG.getTarget().Options.UnsafeFPMath &&
17030             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17031           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17032             break;
17033           std::swap(LHS, RHS);
17034         }
17035         Opcode = X86ISD::FMAX;
17036         break;
17037       case ISD::SETULE:
17038         // Converting this to a max would handle both negative zeros and NaNs
17039         // incorrectly, but we can swap the operands to fix both.
17040         std::swap(LHS, RHS);
17041       case ISD::SETOLT:
17042       case ISD::SETLT:
17043       case ISD::SETLE:
17044         Opcode = X86ISD::FMAX;
17045         break;
17046       }
17047     }
17048
17049     if (Opcode)
17050       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17051   }
17052
17053   EVT CondVT = Cond.getValueType();
17054   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17055       CondVT.getVectorElementType() == MVT::i1) {
17056     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17057     // lowering on AVX-512. In this case we convert it to
17058     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17059     // The same situation for all 128 and 256-bit vectors of i8 and i16
17060     EVT OpVT = LHS.getValueType();
17061     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17062         (OpVT.getVectorElementType() == MVT::i8 ||
17063          OpVT.getVectorElementType() == MVT::i16)) {
17064       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17065       DCI.AddToWorklist(Cond.getNode());
17066       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17067     }
17068   }
17069   // If this is a select between two integer constants, try to do some
17070   // optimizations.
17071   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17072     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17073       // Don't do this for crazy integer types.
17074       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17075         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17076         // so that TrueC (the true value) is larger than FalseC.
17077         bool NeedsCondInvert = false;
17078
17079         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17080             // Efficiently invertible.
17081             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17082              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17083               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17084           NeedsCondInvert = true;
17085           std::swap(TrueC, FalseC);
17086         }
17087
17088         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17089         if (FalseC->getAPIntValue() == 0 &&
17090             TrueC->getAPIntValue().isPowerOf2()) {
17091           if (NeedsCondInvert) // Invert the condition if needed.
17092             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17093                                DAG.getConstant(1, Cond.getValueType()));
17094
17095           // Zero extend the condition if needed.
17096           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17097
17098           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17099           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17100                              DAG.getConstant(ShAmt, MVT::i8));
17101         }
17102
17103         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17104         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17105           if (NeedsCondInvert) // Invert the condition if needed.
17106             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17107                                DAG.getConstant(1, Cond.getValueType()));
17108
17109           // Zero extend the condition if needed.
17110           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17111                              FalseC->getValueType(0), Cond);
17112           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17113                              SDValue(FalseC, 0));
17114         }
17115
17116         // Optimize cases that will turn into an LEA instruction.  This requires
17117         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17118         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17119           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17120           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17121
17122           bool isFastMultiplier = false;
17123           if (Diff < 10) {
17124             switch ((unsigned char)Diff) {
17125               default: break;
17126               case 1:  // result = add base, cond
17127               case 2:  // result = lea base(    , cond*2)
17128               case 3:  // result = lea base(cond, cond*2)
17129               case 4:  // result = lea base(    , cond*4)
17130               case 5:  // result = lea base(cond, cond*4)
17131               case 8:  // result = lea base(    , cond*8)
17132               case 9:  // result = lea base(cond, cond*8)
17133                 isFastMultiplier = true;
17134                 break;
17135             }
17136           }
17137
17138           if (isFastMultiplier) {
17139             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17140             if (NeedsCondInvert) // Invert the condition if needed.
17141               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17142                                  DAG.getConstant(1, Cond.getValueType()));
17143
17144             // Zero extend the condition if needed.
17145             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17146                                Cond);
17147             // Scale the condition by the difference.
17148             if (Diff != 1)
17149               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17150                                  DAG.getConstant(Diff, Cond.getValueType()));
17151
17152             // Add the base if non-zero.
17153             if (FalseC->getAPIntValue() != 0)
17154               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17155                                  SDValue(FalseC, 0));
17156             return Cond;
17157           }
17158         }
17159       }
17160   }
17161
17162   // Canonicalize max and min:
17163   // (x > y) ? x : y -> (x >= y) ? x : y
17164   // (x < y) ? x : y -> (x <= y) ? x : y
17165   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17166   // the need for an extra compare
17167   // against zero. e.g.
17168   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17169   // subl   %esi, %edi
17170   // testl  %edi, %edi
17171   // movl   $0, %eax
17172   // cmovgl %edi, %eax
17173   // =>
17174   // xorl   %eax, %eax
17175   // subl   %esi, $edi
17176   // cmovsl %eax, %edi
17177   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17178       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17179       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17180     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17181     switch (CC) {
17182     default: break;
17183     case ISD::SETLT:
17184     case ISD::SETGT: {
17185       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17186       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17187                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17188       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17189     }
17190     }
17191   }
17192
17193   // Early exit check
17194   if (!TLI.isTypeLegal(VT))
17195     return SDValue();
17196
17197   // Match VSELECTs into subs with unsigned saturation.
17198   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17199       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17200       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17201        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17202     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17203
17204     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17205     // left side invert the predicate to simplify logic below.
17206     SDValue Other;
17207     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17208       Other = RHS;
17209       CC = ISD::getSetCCInverse(CC, true);
17210     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17211       Other = LHS;
17212     }
17213
17214     if (Other.getNode() && Other->getNumOperands() == 2 &&
17215         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17216       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17217       SDValue CondRHS = Cond->getOperand(1);
17218
17219       // Look for a general sub with unsigned saturation first.
17220       // x >= y ? x-y : 0 --> subus x, y
17221       // x >  y ? x-y : 0 --> subus x, y
17222       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17223           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17224         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17225
17226       // If the RHS is a constant we have to reverse the const canonicalization.
17227       // x > C-1 ? x+-C : 0 --> subus x, C
17228       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17229           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17230         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17231         if (CondRHS.getConstantOperandVal(0) == -A-1)
17232           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17233                              DAG.getConstant(-A, VT));
17234       }
17235
17236       // Another special case: If C was a sign bit, the sub has been
17237       // canonicalized into a xor.
17238       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17239       //        it's safe to decanonicalize the xor?
17240       // x s< 0 ? x^C : 0 --> subus x, C
17241       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17242           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17243           isSplatVector(OpRHS.getNode())) {
17244         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17245         if (A.isSignBit())
17246           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17247       }
17248     }
17249   }
17250
17251   // Try to match a min/max vector operation.
17252   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17253     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17254     unsigned Opc = ret.first;
17255     bool NeedSplit = ret.second;
17256
17257     if (Opc && NeedSplit) {
17258       unsigned NumElems = VT.getVectorNumElements();
17259       // Extract the LHS vectors
17260       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17261       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17262
17263       // Extract the RHS vectors
17264       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17265       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17266
17267       // Create min/max for each subvector
17268       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17269       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17270
17271       // Merge the result
17272       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17273     } else if (Opc)
17274       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17275   }
17276
17277   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17278   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17279       // Check if SETCC has already been promoted
17280       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17281       // Check that condition value type matches vselect operand type
17282       CondVT == VT) { 
17283
17284     assert(Cond.getValueType().isVector() &&
17285            "vector select expects a vector selector!");
17286
17287     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17288     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17289
17290     if (!TValIsAllOnes && !FValIsAllZeros) {
17291       // Try invert the condition if true value is not all 1s and false value
17292       // is not all 0s.
17293       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17294       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17295
17296       if (TValIsAllZeros || FValIsAllOnes) {
17297         SDValue CC = Cond.getOperand(2);
17298         ISD::CondCode NewCC =
17299           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17300                                Cond.getOperand(0).getValueType().isInteger());
17301         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17302         std::swap(LHS, RHS);
17303         TValIsAllOnes = FValIsAllOnes;
17304         FValIsAllZeros = TValIsAllZeros;
17305       }
17306     }
17307
17308     if (TValIsAllOnes || FValIsAllZeros) {
17309       SDValue Ret;
17310
17311       if (TValIsAllOnes && FValIsAllZeros)
17312         Ret = Cond;
17313       else if (TValIsAllOnes)
17314         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17315                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17316       else if (FValIsAllZeros)
17317         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17318                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17319
17320       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17321     }
17322   }
17323
17324   // Try to fold this VSELECT into a MOVSS/MOVSD
17325   if (N->getOpcode() == ISD::VSELECT &&
17326       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17327     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17328         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17329       bool CanFold = false;
17330       unsigned NumElems = Cond.getNumOperands();
17331       SDValue A = LHS;
17332       SDValue B = RHS;
17333       
17334       if (isZero(Cond.getOperand(0))) {
17335         CanFold = true;
17336
17337         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17338         // fold (vselect <0,-1> -> (movsd A, B)
17339         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17340           CanFold = isAllOnes(Cond.getOperand(i));
17341       } else if (isAllOnes(Cond.getOperand(0))) {
17342         CanFold = true;
17343         std::swap(A, B);
17344
17345         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17346         // fold (vselect <-1,0> -> (movsd B, A)
17347         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17348           CanFold = isZero(Cond.getOperand(i));
17349       }
17350
17351       if (CanFold) {
17352         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17353           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17354         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17355       }
17356
17357       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17358         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17359         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17360         //                             (v2i64 (bitcast B)))))
17361         //
17362         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17363         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17364         //                             (v2f64 (bitcast B)))))
17365         //
17366         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17367         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17368         //                             (v2i64 (bitcast A)))))
17369         //
17370         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17371         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17372         //                             (v2f64 (bitcast A)))))
17373
17374         CanFold = (isZero(Cond.getOperand(0)) &&
17375                    isZero(Cond.getOperand(1)) &&
17376                    isAllOnes(Cond.getOperand(2)) &&
17377                    isAllOnes(Cond.getOperand(3)));
17378
17379         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17380             isAllOnes(Cond.getOperand(1)) &&
17381             isZero(Cond.getOperand(2)) &&
17382             isZero(Cond.getOperand(3))) {
17383           CanFold = true;
17384           std::swap(LHS, RHS);
17385         }
17386
17387         if (CanFold) {
17388           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17389           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17390           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17391           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17392                                                 NewB, DAG);
17393           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17394         }
17395       }
17396     }
17397   }
17398
17399   // If we know that this node is legal then we know that it is going to be
17400   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17401   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17402   // to simplify previous instructions.
17403   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17404       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17405     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17406
17407     // Don't optimize vector selects that map to mask-registers.
17408     if (BitWidth == 1)
17409       return SDValue();
17410
17411     // Check all uses of that condition operand to check whether it will be
17412     // consumed by non-BLEND instructions, which may depend on all bits are set
17413     // properly.
17414     for (SDNode::use_iterator I = Cond->use_begin(),
17415                               E = Cond->use_end(); I != E; ++I)
17416       if (I->getOpcode() != ISD::VSELECT)
17417         // TODO: Add other opcodes eventually lowered into BLEND.
17418         return SDValue();
17419
17420     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17421     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17422
17423     APInt KnownZero, KnownOne;
17424     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17425                                           DCI.isBeforeLegalizeOps());
17426     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17427         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17428       DCI.CommitTargetLoweringOpt(TLO);
17429   }
17430
17431   return SDValue();
17432 }
17433
17434 // Check whether a boolean test is testing a boolean value generated by
17435 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17436 // code.
17437 //
17438 // Simplify the following patterns:
17439 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17440 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17441 // to (Op EFLAGS Cond)
17442 //
17443 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17444 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17445 // to (Op EFLAGS !Cond)
17446 //
17447 // where Op could be BRCOND or CMOV.
17448 //
17449 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17450   // Quit if not CMP and SUB with its value result used.
17451   if (Cmp.getOpcode() != X86ISD::CMP &&
17452       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17453       return SDValue();
17454
17455   // Quit if not used as a boolean value.
17456   if (CC != X86::COND_E && CC != X86::COND_NE)
17457     return SDValue();
17458
17459   // Check CMP operands. One of them should be 0 or 1 and the other should be
17460   // an SetCC or extended from it.
17461   SDValue Op1 = Cmp.getOperand(0);
17462   SDValue Op2 = Cmp.getOperand(1);
17463
17464   SDValue SetCC;
17465   const ConstantSDNode* C = 0;
17466   bool needOppositeCond = (CC == X86::COND_E);
17467   bool checkAgainstTrue = false; // Is it a comparison against 1?
17468
17469   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17470     SetCC = Op2;
17471   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17472     SetCC = Op1;
17473   else // Quit if all operands are not constants.
17474     return SDValue();
17475
17476   if (C->getZExtValue() == 1) {
17477     needOppositeCond = !needOppositeCond;
17478     checkAgainstTrue = true;
17479   } else if (C->getZExtValue() != 0)
17480     // Quit if the constant is neither 0 or 1.
17481     return SDValue();
17482
17483   bool truncatedToBoolWithAnd = false;
17484   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17485   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17486          SetCC.getOpcode() == ISD::TRUNCATE ||
17487          SetCC.getOpcode() == ISD::AND) {
17488     if (SetCC.getOpcode() == ISD::AND) {
17489       int OpIdx = -1;
17490       ConstantSDNode *CS;
17491       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17492           CS->getZExtValue() == 1)
17493         OpIdx = 1;
17494       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17495           CS->getZExtValue() == 1)
17496         OpIdx = 0;
17497       if (OpIdx == -1)
17498         break;
17499       SetCC = SetCC.getOperand(OpIdx);
17500       truncatedToBoolWithAnd = true;
17501     } else
17502       SetCC = SetCC.getOperand(0);
17503   }
17504
17505   switch (SetCC.getOpcode()) {
17506   case X86ISD::SETCC_CARRY:
17507     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17508     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17509     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17510     // truncated to i1 using 'and'.
17511     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17512       break;
17513     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17514            "Invalid use of SETCC_CARRY!");
17515     // FALL THROUGH
17516   case X86ISD::SETCC:
17517     // Set the condition code or opposite one if necessary.
17518     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17519     if (needOppositeCond)
17520       CC = X86::GetOppositeBranchCondition(CC);
17521     return SetCC.getOperand(1);
17522   case X86ISD::CMOV: {
17523     // Check whether false/true value has canonical one, i.e. 0 or 1.
17524     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17525     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17526     // Quit if true value is not a constant.
17527     if (!TVal)
17528       return SDValue();
17529     // Quit if false value is not a constant.
17530     if (!FVal) {
17531       SDValue Op = SetCC.getOperand(0);
17532       // Skip 'zext' or 'trunc' node.
17533       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17534           Op.getOpcode() == ISD::TRUNCATE)
17535         Op = Op.getOperand(0);
17536       // A special case for rdrand/rdseed, where 0 is set if false cond is
17537       // found.
17538       if ((Op.getOpcode() != X86ISD::RDRAND &&
17539            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17540         return SDValue();
17541     }
17542     // Quit if false value is not the constant 0 or 1.
17543     bool FValIsFalse = true;
17544     if (FVal && FVal->getZExtValue() != 0) {
17545       if (FVal->getZExtValue() != 1)
17546         return SDValue();
17547       // If FVal is 1, opposite cond is needed.
17548       needOppositeCond = !needOppositeCond;
17549       FValIsFalse = false;
17550     }
17551     // Quit if TVal is not the constant opposite of FVal.
17552     if (FValIsFalse && TVal->getZExtValue() != 1)
17553       return SDValue();
17554     if (!FValIsFalse && TVal->getZExtValue() != 0)
17555       return SDValue();
17556     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17557     if (needOppositeCond)
17558       CC = X86::GetOppositeBranchCondition(CC);
17559     return SetCC.getOperand(3);
17560   }
17561   }
17562
17563   return SDValue();
17564 }
17565
17566 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17567 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17568                                   TargetLowering::DAGCombinerInfo &DCI,
17569                                   const X86Subtarget *Subtarget) {
17570   SDLoc DL(N);
17571
17572   // If the flag operand isn't dead, don't touch this CMOV.
17573   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17574     return SDValue();
17575
17576   SDValue FalseOp = N->getOperand(0);
17577   SDValue TrueOp = N->getOperand(1);
17578   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17579   SDValue Cond = N->getOperand(3);
17580
17581   if (CC == X86::COND_E || CC == X86::COND_NE) {
17582     switch (Cond.getOpcode()) {
17583     default: break;
17584     case X86ISD::BSR:
17585     case X86ISD::BSF:
17586       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17587       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17588         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17589     }
17590   }
17591
17592   SDValue Flags;
17593
17594   Flags = checkBoolTestSetCCCombine(Cond, CC);
17595   if (Flags.getNode() &&
17596       // Extra check as FCMOV only supports a subset of X86 cond.
17597       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17598     SDValue Ops[] = { FalseOp, TrueOp,
17599                       DAG.getConstant(CC, MVT::i8), Flags };
17600     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17601                        Ops, array_lengthof(Ops));
17602   }
17603
17604   // If this is a select between two integer constants, try to do some
17605   // optimizations.  Note that the operands are ordered the opposite of SELECT
17606   // operands.
17607   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17608     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17609       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17610       // larger than FalseC (the false value).
17611       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17612         CC = X86::GetOppositeBranchCondition(CC);
17613         std::swap(TrueC, FalseC);
17614         std::swap(TrueOp, FalseOp);
17615       }
17616
17617       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17618       // This is efficient for any integer data type (including i8/i16) and
17619       // shift amount.
17620       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17621         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17622                            DAG.getConstant(CC, MVT::i8), Cond);
17623
17624         // Zero extend the condition if needed.
17625         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17626
17627         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17628         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17629                            DAG.getConstant(ShAmt, MVT::i8));
17630         if (N->getNumValues() == 2)  // Dead flag value?
17631           return DCI.CombineTo(N, Cond, SDValue());
17632         return Cond;
17633       }
17634
17635       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17636       // for any integer data type, including i8/i16.
17637       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17638         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17639                            DAG.getConstant(CC, MVT::i8), Cond);
17640
17641         // Zero extend the condition if needed.
17642         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17643                            FalseC->getValueType(0), Cond);
17644         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17645                            SDValue(FalseC, 0));
17646
17647         if (N->getNumValues() == 2)  // Dead flag value?
17648           return DCI.CombineTo(N, Cond, SDValue());
17649         return Cond;
17650       }
17651
17652       // Optimize cases that will turn into an LEA instruction.  This requires
17653       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17654       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17655         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17656         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17657
17658         bool isFastMultiplier = false;
17659         if (Diff < 10) {
17660           switch ((unsigned char)Diff) {
17661           default: break;
17662           case 1:  // result = add base, cond
17663           case 2:  // result = lea base(    , cond*2)
17664           case 3:  // result = lea base(cond, cond*2)
17665           case 4:  // result = lea base(    , cond*4)
17666           case 5:  // result = lea base(cond, cond*4)
17667           case 8:  // result = lea base(    , cond*8)
17668           case 9:  // result = lea base(cond, cond*8)
17669             isFastMultiplier = true;
17670             break;
17671           }
17672         }
17673
17674         if (isFastMultiplier) {
17675           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17676           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17677                              DAG.getConstant(CC, MVT::i8), Cond);
17678           // Zero extend the condition if needed.
17679           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17680                              Cond);
17681           // Scale the condition by the difference.
17682           if (Diff != 1)
17683             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17684                                DAG.getConstant(Diff, Cond.getValueType()));
17685
17686           // Add the base if non-zero.
17687           if (FalseC->getAPIntValue() != 0)
17688             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17689                                SDValue(FalseC, 0));
17690           if (N->getNumValues() == 2)  // Dead flag value?
17691             return DCI.CombineTo(N, Cond, SDValue());
17692           return Cond;
17693         }
17694       }
17695     }
17696   }
17697
17698   // Handle these cases:
17699   //   (select (x != c), e, c) -> select (x != c), e, x),
17700   //   (select (x == c), c, e) -> select (x == c), x, e)
17701   // where the c is an integer constant, and the "select" is the combination
17702   // of CMOV and CMP.
17703   //
17704   // The rationale for this change is that the conditional-move from a constant
17705   // needs two instructions, however, conditional-move from a register needs
17706   // only one instruction.
17707   //
17708   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17709   //  some instruction-combining opportunities. This opt needs to be
17710   //  postponed as late as possible.
17711   //
17712   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17713     // the DCI.xxxx conditions are provided to postpone the optimization as
17714     // late as possible.
17715
17716     ConstantSDNode *CmpAgainst = 0;
17717     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17718         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17719         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17720
17721       if (CC == X86::COND_NE &&
17722           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17723         CC = X86::GetOppositeBranchCondition(CC);
17724         std::swap(TrueOp, FalseOp);
17725       }
17726
17727       if (CC == X86::COND_E &&
17728           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17729         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17730                           DAG.getConstant(CC, MVT::i8), Cond };
17731         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17732                            array_lengthof(Ops));
17733       }
17734     }
17735   }
17736
17737   return SDValue();
17738 }
17739
17740 /// PerformMulCombine - Optimize a single multiply with constant into two
17741 /// in order to implement it with two cheaper instructions, e.g.
17742 /// LEA + SHL, LEA + LEA.
17743 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17744                                  TargetLowering::DAGCombinerInfo &DCI) {
17745   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17746     return SDValue();
17747
17748   EVT VT = N->getValueType(0);
17749   if (VT != MVT::i64)
17750     return SDValue();
17751
17752   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17753   if (!C)
17754     return SDValue();
17755   uint64_t MulAmt = C->getZExtValue();
17756   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17757     return SDValue();
17758
17759   uint64_t MulAmt1 = 0;
17760   uint64_t MulAmt2 = 0;
17761   if ((MulAmt % 9) == 0) {
17762     MulAmt1 = 9;
17763     MulAmt2 = MulAmt / 9;
17764   } else if ((MulAmt % 5) == 0) {
17765     MulAmt1 = 5;
17766     MulAmt2 = MulAmt / 5;
17767   } else if ((MulAmt % 3) == 0) {
17768     MulAmt1 = 3;
17769     MulAmt2 = MulAmt / 3;
17770   }
17771   if (MulAmt2 &&
17772       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17773     SDLoc DL(N);
17774
17775     if (isPowerOf2_64(MulAmt2) &&
17776         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17777       // If second multiplifer is pow2, issue it first. We want the multiply by
17778       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17779       // is an add.
17780       std::swap(MulAmt1, MulAmt2);
17781
17782     SDValue NewMul;
17783     if (isPowerOf2_64(MulAmt1))
17784       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17785                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17786     else
17787       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17788                            DAG.getConstant(MulAmt1, VT));
17789
17790     if (isPowerOf2_64(MulAmt2))
17791       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17792                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17793     else
17794       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17795                            DAG.getConstant(MulAmt2, VT));
17796
17797     // Do not add new nodes to DAG combiner worklist.
17798     DCI.CombineTo(N, NewMul, false);
17799   }
17800   return SDValue();
17801 }
17802
17803 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17804   SDValue N0 = N->getOperand(0);
17805   SDValue N1 = N->getOperand(1);
17806   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17807   EVT VT = N0.getValueType();
17808
17809   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17810   // since the result of setcc_c is all zero's or all ones.
17811   if (VT.isInteger() && !VT.isVector() &&
17812       N1C && N0.getOpcode() == ISD::AND &&
17813       N0.getOperand(1).getOpcode() == ISD::Constant) {
17814     SDValue N00 = N0.getOperand(0);
17815     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17816         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17817           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17818          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17819       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17820       APInt ShAmt = N1C->getAPIntValue();
17821       Mask = Mask.shl(ShAmt);
17822       if (Mask != 0)
17823         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17824                            N00, DAG.getConstant(Mask, VT));
17825     }
17826   }
17827
17828   // Hardware support for vector shifts is sparse which makes us scalarize the
17829   // vector operations in many cases. Also, on sandybridge ADD is faster than
17830   // shl.
17831   // (shl V, 1) -> add V,V
17832   if (isSplatVector(N1.getNode())) {
17833     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17834     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17835     // We shift all of the values by one. In many cases we do not have
17836     // hardware support for this operation. This is better expressed as an ADD
17837     // of two values.
17838     if (N1C && (1 == N1C->getZExtValue())) {
17839       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17840     }
17841   }
17842
17843   return SDValue();
17844 }
17845
17846 /// \brief Returns a vector of 0s if the node in input is a vector logical
17847 /// shift by a constant amount which is known to be bigger than or equal
17848 /// to the vector element size in bits.
17849 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17850                                       const X86Subtarget *Subtarget) {
17851   EVT VT = N->getValueType(0);
17852
17853   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17854       (!Subtarget->hasInt256() ||
17855        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17856     return SDValue();
17857
17858   SDValue Amt = N->getOperand(1);
17859   SDLoc DL(N);
17860   if (isSplatVector(Amt.getNode())) {
17861     SDValue SclrAmt = Amt->getOperand(0);
17862     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17863       APInt ShiftAmt = C->getAPIntValue();
17864       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17865
17866       // SSE2/AVX2 logical shifts always return a vector of 0s
17867       // if the shift amount is bigger than or equal to
17868       // the element size. The constant shift amount will be
17869       // encoded as a 8-bit immediate.
17870       if (ShiftAmt.trunc(8).uge(MaxAmount))
17871         return getZeroVector(VT, Subtarget, DAG, DL);
17872     }
17873   }
17874
17875   return SDValue();
17876 }
17877
17878 /// PerformShiftCombine - Combine shifts.
17879 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17880                                    TargetLowering::DAGCombinerInfo &DCI,
17881                                    const X86Subtarget *Subtarget) {
17882   if (N->getOpcode() == ISD::SHL) {
17883     SDValue V = PerformSHLCombine(N, DAG);
17884     if (V.getNode()) return V;
17885   }
17886
17887   if (N->getOpcode() != ISD::SRA) {
17888     // Try to fold this logical shift into a zero vector.
17889     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17890     if (V.getNode()) return V;
17891   }
17892
17893   return SDValue();
17894 }
17895
17896 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
17897 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17898 // and friends.  Likewise for OR -> CMPNEQSS.
17899 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17900                             TargetLowering::DAGCombinerInfo &DCI,
17901                             const X86Subtarget *Subtarget) {
17902   unsigned opcode;
17903
17904   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17905   // we're requiring SSE2 for both.
17906   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17907     SDValue N0 = N->getOperand(0);
17908     SDValue N1 = N->getOperand(1);
17909     SDValue CMP0 = N0->getOperand(1);
17910     SDValue CMP1 = N1->getOperand(1);
17911     SDLoc DL(N);
17912
17913     // The SETCCs should both refer to the same CMP.
17914     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
17915       return SDValue();
17916
17917     SDValue CMP00 = CMP0->getOperand(0);
17918     SDValue CMP01 = CMP0->getOperand(1);
17919     EVT     VT    = CMP00.getValueType();
17920
17921     if (VT == MVT::f32 || VT == MVT::f64) {
17922       bool ExpectingFlags = false;
17923       // Check for any users that want flags:
17924       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
17925            !ExpectingFlags && UI != UE; ++UI)
17926         switch (UI->getOpcode()) {
17927         default:
17928         case ISD::BR_CC:
17929         case ISD::BRCOND:
17930         case ISD::SELECT:
17931           ExpectingFlags = true;
17932           break;
17933         case ISD::CopyToReg:
17934         case ISD::SIGN_EXTEND:
17935         case ISD::ZERO_EXTEND:
17936         case ISD::ANY_EXTEND:
17937           break;
17938         }
17939
17940       if (!ExpectingFlags) {
17941         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
17942         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
17943
17944         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
17945           X86::CondCode tmp = cc0;
17946           cc0 = cc1;
17947           cc1 = tmp;
17948         }
17949
17950         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
17951             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17952           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17953           // FIXME: need symbolic constants for these magic numbers.
17954           // See X86ATTInstPrinter.cpp:printSSECC().
17955           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17956           if (Subtarget->hasAVX512()) {
17957             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
17958                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
17959             if (N->getValueType(0) != MVT::i1)
17960               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
17961                                  FSetCC);
17962             return FSetCC;
17963           }
17964           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
17965                                               CMP00.getValueType(), CMP00, CMP01,
17966                                               DAG.getConstant(x86cc, MVT::i8));
17967           MVT IntVT = (is64BitFP ? MVT::i64 : MVT::i32); 
17968           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
17969                                               OnesOrZeroesF);
17970           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
17971                                       DAG.getConstant(1, IntVT));
17972           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17973           return OneBitOfTruth;
17974         }
17975       }
17976     }
17977   }
17978   return SDValue();
17979 }
17980
17981 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17982 /// so it can be folded inside ANDNP.
17983 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17984   EVT VT = N->getValueType(0);
17985
17986   // Match direct AllOnes for 128 and 256-bit vectors
17987   if (ISD::isBuildVectorAllOnes(N))
17988     return true;
17989
17990   // Look through a bit convert.
17991   if (N->getOpcode() == ISD::BITCAST)
17992     N = N->getOperand(0).getNode();
17993
17994   // Sometimes the operand may come from a insert_subvector building a 256-bit
17995   // allones vector
17996   if (VT.is256BitVector() &&
17997       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17998     SDValue V1 = N->getOperand(0);
17999     SDValue V2 = N->getOperand(1);
18000
18001     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18002         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18003         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18004         ISD::isBuildVectorAllOnes(V2.getNode()))
18005       return true;
18006   }
18007
18008   return false;
18009 }
18010
18011 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18012 // register. In most cases we actually compare or select YMM-sized registers
18013 // and mixing the two types creates horrible code. This method optimizes
18014 // some of the transition sequences.
18015 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18016                                  TargetLowering::DAGCombinerInfo &DCI,
18017                                  const X86Subtarget *Subtarget) {
18018   EVT VT = N->getValueType(0);
18019   if (!VT.is256BitVector())
18020     return SDValue();
18021
18022   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18023           N->getOpcode() == ISD::ZERO_EXTEND ||
18024           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18025
18026   SDValue Narrow = N->getOperand(0);
18027   EVT NarrowVT = Narrow->getValueType(0);
18028   if (!NarrowVT.is128BitVector())
18029     return SDValue();
18030
18031   if (Narrow->getOpcode() != ISD::XOR &&
18032       Narrow->getOpcode() != ISD::AND &&
18033       Narrow->getOpcode() != ISD::OR)
18034     return SDValue();
18035
18036   SDValue N0  = Narrow->getOperand(0);
18037   SDValue N1  = Narrow->getOperand(1);
18038   SDLoc DL(Narrow);
18039
18040   // The Left side has to be a trunc.
18041   if (N0.getOpcode() != ISD::TRUNCATE)
18042     return SDValue();
18043
18044   // The type of the truncated inputs.
18045   EVT WideVT = N0->getOperand(0)->getValueType(0);
18046   if (WideVT != VT)
18047     return SDValue();
18048
18049   // The right side has to be a 'trunc' or a constant vector.
18050   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18051   bool RHSConst = (isSplatVector(N1.getNode()) &&
18052                    isa<ConstantSDNode>(N1->getOperand(0)));
18053   if (!RHSTrunc && !RHSConst)
18054     return SDValue();
18055
18056   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18057
18058   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18059     return SDValue();
18060
18061   // Set N0 and N1 to hold the inputs to the new wide operation.
18062   N0 = N0->getOperand(0);
18063   if (RHSConst) {
18064     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18065                      N1->getOperand(0));
18066     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18067     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18068   } else if (RHSTrunc) {
18069     N1 = N1->getOperand(0);
18070   }
18071
18072   // Generate the wide operation.
18073   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18074   unsigned Opcode = N->getOpcode();
18075   switch (Opcode) {
18076   case ISD::ANY_EXTEND:
18077     return Op;
18078   case ISD::ZERO_EXTEND: {
18079     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18080     APInt Mask = APInt::getAllOnesValue(InBits);
18081     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18082     return DAG.getNode(ISD::AND, DL, VT,
18083                        Op, DAG.getConstant(Mask, VT));
18084   }
18085   case ISD::SIGN_EXTEND:
18086     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18087                        Op, DAG.getValueType(NarrowVT));
18088   default:
18089     llvm_unreachable("Unexpected opcode");
18090   }
18091 }
18092
18093 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18094                                  TargetLowering::DAGCombinerInfo &DCI,
18095                                  const X86Subtarget *Subtarget) {
18096   EVT VT = N->getValueType(0);
18097   if (DCI.isBeforeLegalizeOps())
18098     return SDValue();
18099
18100   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18101   if (R.getNode())
18102     return R;
18103
18104   // Create BEXTR and BZHI instructions
18105   // BZHI is X & ((1 << Y) - 1)
18106   // BEXTR is ((X >> imm) & (2**size-1))
18107   if (VT == MVT::i32 || VT == MVT::i64) {
18108     SDValue N0 = N->getOperand(0);
18109     SDValue N1 = N->getOperand(1);
18110     SDLoc DL(N);
18111
18112     if (Subtarget->hasBMI2()) {
18113       // Check for (and (add (shl 1, Y), -1), X)
18114       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
18115         SDValue N00 = N0.getOperand(0);
18116         if (N00.getOpcode() == ISD::SHL) {
18117           SDValue N001 = N00.getOperand(1);
18118           assert(N001.getValueType() == MVT::i8 && "unexpected type");
18119           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
18120           if (C && C->getZExtValue() == 1)
18121             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
18122         }
18123       }
18124
18125       // Check for (and X, (add (shl 1, Y), -1))
18126       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
18127         SDValue N10 = N1.getOperand(0);
18128         if (N10.getOpcode() == ISD::SHL) {
18129           SDValue N101 = N10.getOperand(1);
18130           assert(N101.getValueType() == MVT::i8 && "unexpected type");
18131           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
18132           if (C && C->getZExtValue() == 1)
18133             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
18134         }
18135       }
18136     }
18137
18138     // Check for BEXTR.
18139     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18140         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18141       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18142       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18143       if (MaskNode && ShiftNode) {
18144         uint64_t Mask = MaskNode->getZExtValue();
18145         uint64_t Shift = ShiftNode->getZExtValue();
18146         if (isMask_64(Mask)) {
18147           uint64_t MaskSize = CountPopulation_64(Mask);
18148           if (Shift + MaskSize <= VT.getSizeInBits())
18149             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18150                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18151         }
18152       }
18153     } // BEXTR
18154
18155     return SDValue();
18156   }
18157
18158   // Want to form ANDNP nodes:
18159   // 1) In the hopes of then easily combining them with OR and AND nodes
18160   //    to form PBLEND/PSIGN.
18161   // 2) To match ANDN packed intrinsics
18162   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18163     return SDValue();
18164
18165   SDValue N0 = N->getOperand(0);
18166   SDValue N1 = N->getOperand(1);
18167   SDLoc DL(N);
18168
18169   // Check LHS for vnot
18170   if (N0.getOpcode() == ISD::XOR &&
18171       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18172       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18173     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18174
18175   // Check RHS for vnot
18176   if (N1.getOpcode() == ISD::XOR &&
18177       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18178       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18179     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18180
18181   return SDValue();
18182 }
18183
18184 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18185                                 TargetLowering::DAGCombinerInfo &DCI,
18186                                 const X86Subtarget *Subtarget) {
18187   if (DCI.isBeforeLegalizeOps())
18188     return SDValue();
18189
18190   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18191   if (R.getNode())
18192     return R;
18193
18194   SDValue N0 = N->getOperand(0);
18195   SDValue N1 = N->getOperand(1);
18196   EVT VT = N->getValueType(0);
18197
18198   // look for psign/blend
18199   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18200     if (!Subtarget->hasSSSE3() ||
18201         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18202       return SDValue();
18203
18204     // Canonicalize pandn to RHS
18205     if (N0.getOpcode() == X86ISD::ANDNP)
18206       std::swap(N0, N1);
18207     // or (and (m, y), (pandn m, x))
18208     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18209       SDValue Mask = N1.getOperand(0);
18210       SDValue X    = N1.getOperand(1);
18211       SDValue Y;
18212       if (N0.getOperand(0) == Mask)
18213         Y = N0.getOperand(1);
18214       if (N0.getOperand(1) == Mask)
18215         Y = N0.getOperand(0);
18216
18217       // Check to see if the mask appeared in both the AND and ANDNP and
18218       if (!Y.getNode())
18219         return SDValue();
18220
18221       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18222       // Look through mask bitcast.
18223       if (Mask.getOpcode() == ISD::BITCAST)
18224         Mask = Mask.getOperand(0);
18225       if (X.getOpcode() == ISD::BITCAST)
18226         X = X.getOperand(0);
18227       if (Y.getOpcode() == ISD::BITCAST)
18228         Y = Y.getOperand(0);
18229
18230       EVT MaskVT = Mask.getValueType();
18231
18232       // Validate that the Mask operand is a vector sra node.
18233       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18234       // there is no psrai.b
18235       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18236       unsigned SraAmt = ~0;
18237       if (Mask.getOpcode() == ISD::SRA) {
18238         SDValue Amt = Mask.getOperand(1);
18239         if (isSplatVector(Amt.getNode())) {
18240           SDValue SclrAmt = Amt->getOperand(0);
18241           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18242             SraAmt = C->getZExtValue();
18243         }
18244       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18245         SDValue SraC = Mask.getOperand(1);
18246         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18247       }
18248       if ((SraAmt + 1) != EltBits)
18249         return SDValue();
18250
18251       SDLoc DL(N);
18252
18253       // Now we know we at least have a plendvb with the mask val.  See if
18254       // we can form a psignb/w/d.
18255       // psign = x.type == y.type == mask.type && y = sub(0, x);
18256       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18257           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18258           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18259         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18260                "Unsupported VT for PSIGN");
18261         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18262         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18263       }
18264       // PBLENDVB only available on SSE 4.1
18265       if (!Subtarget->hasSSE41())
18266         return SDValue();
18267
18268       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18269
18270       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18271       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18272       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18273       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18274       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18275     }
18276   }
18277
18278   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18279     return SDValue();
18280
18281   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18282   MachineFunction &MF = DAG.getMachineFunction();
18283   bool OptForSize = MF.getFunction()->getAttributes().
18284     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18285
18286   // SHLD/SHRD instructions have lower register pressure, but on some
18287   // platforms they have higher latency than the equivalent
18288   // series of shifts/or that would otherwise be generated.
18289   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18290   // have higher latencies and we are not optimizing for size.
18291   if (!OptForSize && Subtarget->isSHLDSlow())
18292     return SDValue();
18293
18294   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18295     std::swap(N0, N1);
18296   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18297     return SDValue();
18298   if (!N0.hasOneUse() || !N1.hasOneUse())
18299     return SDValue();
18300
18301   SDValue ShAmt0 = N0.getOperand(1);
18302   if (ShAmt0.getValueType() != MVT::i8)
18303     return SDValue();
18304   SDValue ShAmt1 = N1.getOperand(1);
18305   if (ShAmt1.getValueType() != MVT::i8)
18306     return SDValue();
18307   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18308     ShAmt0 = ShAmt0.getOperand(0);
18309   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18310     ShAmt1 = ShAmt1.getOperand(0);
18311
18312   SDLoc DL(N);
18313   unsigned Opc = X86ISD::SHLD;
18314   SDValue Op0 = N0.getOperand(0);
18315   SDValue Op1 = N1.getOperand(0);
18316   if (ShAmt0.getOpcode() == ISD::SUB) {
18317     Opc = X86ISD::SHRD;
18318     std::swap(Op0, Op1);
18319     std::swap(ShAmt0, ShAmt1);
18320   }
18321
18322   unsigned Bits = VT.getSizeInBits();
18323   if (ShAmt1.getOpcode() == ISD::SUB) {
18324     SDValue Sum = ShAmt1.getOperand(0);
18325     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18326       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18327       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18328         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18329       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18330         return DAG.getNode(Opc, DL, VT,
18331                            Op0, Op1,
18332                            DAG.getNode(ISD::TRUNCATE, DL,
18333                                        MVT::i8, ShAmt0));
18334     }
18335   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18336     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18337     if (ShAmt0C &&
18338         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18339       return DAG.getNode(Opc, DL, VT,
18340                          N0.getOperand(0), N1.getOperand(0),
18341                          DAG.getNode(ISD::TRUNCATE, DL,
18342                                        MVT::i8, ShAmt0));
18343   }
18344
18345   return SDValue();
18346 }
18347
18348 // Generate NEG and CMOV for integer abs.
18349 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18350   EVT VT = N->getValueType(0);
18351
18352   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18353   // 8-bit integer abs to NEG and CMOV.
18354   if (VT.isInteger() && VT.getSizeInBits() == 8)
18355     return SDValue();
18356
18357   SDValue N0 = N->getOperand(0);
18358   SDValue N1 = N->getOperand(1);
18359   SDLoc DL(N);
18360
18361   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18362   // and change it to SUB and CMOV.
18363   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18364       N0.getOpcode() == ISD::ADD &&
18365       N0.getOperand(1) == N1 &&
18366       N1.getOpcode() == ISD::SRA &&
18367       N1.getOperand(0) == N0.getOperand(0))
18368     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18369       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18370         // Generate SUB & CMOV.
18371         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18372                                   DAG.getConstant(0, VT), N0.getOperand(0));
18373
18374         SDValue Ops[] = { N0.getOperand(0), Neg,
18375                           DAG.getConstant(X86::COND_GE, MVT::i8),
18376                           SDValue(Neg.getNode(), 1) };
18377         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18378                            Ops, array_lengthof(Ops));
18379       }
18380   return SDValue();
18381 }
18382
18383 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18384 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18385                                  TargetLowering::DAGCombinerInfo &DCI,
18386                                  const X86Subtarget *Subtarget) {
18387   if (DCI.isBeforeLegalizeOps())
18388     return SDValue();
18389
18390   if (Subtarget->hasCMov()) {
18391     SDValue RV = performIntegerAbsCombine(N, DAG);
18392     if (RV.getNode())
18393       return RV;
18394   }
18395
18396   return SDValue();
18397 }
18398
18399 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18400 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18401                                   TargetLowering::DAGCombinerInfo &DCI,
18402                                   const X86Subtarget *Subtarget) {
18403   LoadSDNode *Ld = cast<LoadSDNode>(N);
18404   EVT RegVT = Ld->getValueType(0);
18405   EVT MemVT = Ld->getMemoryVT();
18406   SDLoc dl(Ld);
18407   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18408   unsigned RegSz = RegVT.getSizeInBits();
18409
18410   // On Sandybridge unaligned 256bit loads are inefficient.
18411   ISD::LoadExtType Ext = Ld->getExtensionType();
18412   unsigned Alignment = Ld->getAlignment();
18413   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18414   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18415       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18416     unsigned NumElems = RegVT.getVectorNumElements();
18417     if (NumElems < 2)
18418       return SDValue();
18419
18420     SDValue Ptr = Ld->getBasePtr();
18421     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18422
18423     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18424                                   NumElems/2);
18425     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18426                                 Ld->getPointerInfo(), Ld->isVolatile(),
18427                                 Ld->isNonTemporal(), Ld->isInvariant(),
18428                                 Alignment);
18429     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18430     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18431                                 Ld->getPointerInfo(), Ld->isVolatile(),
18432                                 Ld->isNonTemporal(), Ld->isInvariant(),
18433                                 std::min(16U, Alignment));
18434     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18435                              Load1.getValue(1),
18436                              Load2.getValue(1));
18437
18438     SDValue NewVec = DAG.getUNDEF(RegVT);
18439     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18440     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18441     return DCI.CombineTo(N, NewVec, TF, true);
18442   }
18443
18444   // If this is a vector EXT Load then attempt to optimize it using a
18445   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18446   // expansion is still better than scalar code.
18447   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18448   // emit a shuffle and a arithmetic shift.
18449   // TODO: It is possible to support ZExt by zeroing the undef values
18450   // during the shuffle phase or after the shuffle.
18451   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18452       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18453     assert(MemVT != RegVT && "Cannot extend to the same type");
18454     assert(MemVT.isVector() && "Must load a vector from memory");
18455
18456     unsigned NumElems = RegVT.getVectorNumElements();
18457     unsigned MemSz = MemVT.getSizeInBits();
18458     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18459
18460     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18461       return SDValue();
18462
18463     // All sizes must be a power of two.
18464     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18465       return SDValue();
18466
18467     // Attempt to load the original value using scalar loads.
18468     // Find the largest scalar type that divides the total loaded size.
18469     MVT SclrLoadTy = MVT::i8;
18470     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18471          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18472       MVT Tp = (MVT::SimpleValueType)tp;
18473       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18474         SclrLoadTy = Tp;
18475       }
18476     }
18477
18478     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18479     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18480         (64 <= MemSz))
18481       SclrLoadTy = MVT::f64;
18482
18483     // Calculate the number of scalar loads that we need to perform
18484     // in order to load our vector from memory.
18485     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18486     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18487       return SDValue();
18488
18489     unsigned loadRegZize = RegSz;
18490     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18491       loadRegZize /= 2;
18492
18493     // Represent our vector as a sequence of elements which are the
18494     // largest scalar that we can load.
18495     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18496       loadRegZize/SclrLoadTy.getSizeInBits());
18497
18498     // Represent the data using the same element type that is stored in
18499     // memory. In practice, we ''widen'' MemVT.
18500     EVT WideVecVT =
18501           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18502                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18503
18504     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18505       "Invalid vector type");
18506
18507     // We can't shuffle using an illegal type.
18508     if (!TLI.isTypeLegal(WideVecVT))
18509       return SDValue();
18510
18511     SmallVector<SDValue, 8> Chains;
18512     SDValue Ptr = Ld->getBasePtr();
18513     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18514                                         TLI.getPointerTy());
18515     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18516
18517     for (unsigned i = 0; i < NumLoads; ++i) {
18518       // Perform a single load.
18519       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18520                                        Ptr, Ld->getPointerInfo(),
18521                                        Ld->isVolatile(), Ld->isNonTemporal(),
18522                                        Ld->isInvariant(), Ld->getAlignment());
18523       Chains.push_back(ScalarLoad.getValue(1));
18524       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18525       // another round of DAGCombining.
18526       if (i == 0)
18527         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18528       else
18529         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18530                           ScalarLoad, DAG.getIntPtrConstant(i));
18531
18532       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18533     }
18534
18535     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18536                                Chains.size());
18537
18538     // Bitcast the loaded value to a vector of the original element type, in
18539     // the size of the target vector type.
18540     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18541     unsigned SizeRatio = RegSz/MemSz;
18542
18543     if (Ext == ISD::SEXTLOAD) {
18544       // If we have SSE4.1 we can directly emit a VSEXT node.
18545       if (Subtarget->hasSSE41()) {
18546         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18547         return DCI.CombineTo(N, Sext, TF, true);
18548       }
18549
18550       // Otherwise we'll shuffle the small elements in the high bits of the
18551       // larger type and perform an arithmetic shift. If the shift is not legal
18552       // it's better to scalarize.
18553       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18554         return SDValue();
18555
18556       // Redistribute the loaded elements into the different locations.
18557       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18558       for (unsigned i = 0; i != NumElems; ++i)
18559         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18560
18561       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18562                                            DAG.getUNDEF(WideVecVT),
18563                                            &ShuffleVec[0]);
18564
18565       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18566
18567       // Build the arithmetic shift.
18568       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18569                      MemVT.getVectorElementType().getSizeInBits();
18570       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18571                           DAG.getConstant(Amt, RegVT));
18572
18573       return DCI.CombineTo(N, Shuff, TF, true);
18574     }
18575
18576     // Redistribute the loaded elements into the different locations.
18577     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18578     for (unsigned i = 0; i != NumElems; ++i)
18579       ShuffleVec[i*SizeRatio] = i;
18580
18581     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18582                                          DAG.getUNDEF(WideVecVT),
18583                                          &ShuffleVec[0]);
18584
18585     // Bitcast to the requested type.
18586     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18587     // Replace the original load with the new sequence
18588     // and return the new chain.
18589     return DCI.CombineTo(N, Shuff, TF, true);
18590   }
18591
18592   return SDValue();
18593 }
18594
18595 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18596 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18597                                    const X86Subtarget *Subtarget) {
18598   StoreSDNode *St = cast<StoreSDNode>(N);
18599   EVT VT = St->getValue().getValueType();
18600   EVT StVT = St->getMemoryVT();
18601   SDLoc dl(St);
18602   SDValue StoredVal = St->getOperand(1);
18603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18604
18605   // If we are saving a concatenation of two XMM registers, perform two stores.
18606   // On Sandy Bridge, 256-bit memory operations are executed by two
18607   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18608   // memory  operation.
18609   unsigned Alignment = St->getAlignment();
18610   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18611   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18612       StVT == VT && !IsAligned) {
18613     unsigned NumElems = VT.getVectorNumElements();
18614     if (NumElems < 2)
18615       return SDValue();
18616
18617     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18618     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18619
18620     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18621     SDValue Ptr0 = St->getBasePtr();
18622     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18623
18624     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18625                                 St->getPointerInfo(), St->isVolatile(),
18626                                 St->isNonTemporal(), Alignment);
18627     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18628                                 St->getPointerInfo(), St->isVolatile(),
18629                                 St->isNonTemporal(),
18630                                 std::min(16U, Alignment));
18631     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18632   }
18633
18634   // Optimize trunc store (of multiple scalars) to shuffle and store.
18635   // First, pack all of the elements in one place. Next, store to memory
18636   // in fewer chunks.
18637   if (St->isTruncatingStore() && VT.isVector()) {
18638     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18639     unsigned NumElems = VT.getVectorNumElements();
18640     assert(StVT != VT && "Cannot truncate to the same type");
18641     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18642     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18643
18644     // From, To sizes and ElemCount must be pow of two
18645     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18646     // We are going to use the original vector elt for storing.
18647     // Accumulated smaller vector elements must be a multiple of the store size.
18648     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18649
18650     unsigned SizeRatio  = FromSz / ToSz;
18651
18652     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18653
18654     // Create a type on which we perform the shuffle
18655     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18656             StVT.getScalarType(), NumElems*SizeRatio);
18657
18658     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18659
18660     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18661     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18662     for (unsigned i = 0; i != NumElems; ++i)
18663       ShuffleVec[i] = i * SizeRatio;
18664
18665     // Can't shuffle using an illegal type.
18666     if (!TLI.isTypeLegal(WideVecVT))
18667       return SDValue();
18668
18669     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18670                                          DAG.getUNDEF(WideVecVT),
18671                                          &ShuffleVec[0]);
18672     // At this point all of the data is stored at the bottom of the
18673     // register. We now need to save it to mem.
18674
18675     // Find the largest store unit
18676     MVT StoreType = MVT::i8;
18677     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18678          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18679       MVT Tp = (MVT::SimpleValueType)tp;
18680       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18681         StoreType = Tp;
18682     }
18683
18684     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18685     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18686         (64 <= NumElems * ToSz))
18687       StoreType = MVT::f64;
18688
18689     // Bitcast the original vector into a vector of store-size units
18690     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18691             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18692     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18693     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18694     SmallVector<SDValue, 8> Chains;
18695     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18696                                         TLI.getPointerTy());
18697     SDValue Ptr = St->getBasePtr();
18698
18699     // Perform one or more big stores into memory.
18700     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18701       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18702                                    StoreType, ShuffWide,
18703                                    DAG.getIntPtrConstant(i));
18704       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18705                                 St->getPointerInfo(), St->isVolatile(),
18706                                 St->isNonTemporal(), St->getAlignment());
18707       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18708       Chains.push_back(Ch);
18709     }
18710
18711     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18712                                Chains.size());
18713   }
18714
18715   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18716   // the FP state in cases where an emms may be missing.
18717   // A preferable solution to the general problem is to figure out the right
18718   // places to insert EMMS.  This qualifies as a quick hack.
18719
18720   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18721   if (VT.getSizeInBits() != 64)
18722     return SDValue();
18723
18724   const Function *F = DAG.getMachineFunction().getFunction();
18725   bool NoImplicitFloatOps = F->getAttributes().
18726     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18727   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18728                      && Subtarget->hasSSE2();
18729   if ((VT.isVector() ||
18730        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18731       isa<LoadSDNode>(St->getValue()) &&
18732       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18733       St->getChain().hasOneUse() && !St->isVolatile()) {
18734     SDNode* LdVal = St->getValue().getNode();
18735     LoadSDNode *Ld = 0;
18736     int TokenFactorIndex = -1;
18737     SmallVector<SDValue, 8> Ops;
18738     SDNode* ChainVal = St->getChain().getNode();
18739     // Must be a store of a load.  We currently handle two cases:  the load
18740     // is a direct child, and it's under an intervening TokenFactor.  It is
18741     // possible to dig deeper under nested TokenFactors.
18742     if (ChainVal == LdVal)
18743       Ld = cast<LoadSDNode>(St->getChain());
18744     else if (St->getValue().hasOneUse() &&
18745              ChainVal->getOpcode() == ISD::TokenFactor) {
18746       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18747         if (ChainVal->getOperand(i).getNode() == LdVal) {
18748           TokenFactorIndex = i;
18749           Ld = cast<LoadSDNode>(St->getValue());
18750         } else
18751           Ops.push_back(ChainVal->getOperand(i));
18752       }
18753     }
18754
18755     if (!Ld || !ISD::isNormalLoad(Ld))
18756       return SDValue();
18757
18758     // If this is not the MMX case, i.e. we are just turning i64 load/store
18759     // into f64 load/store, avoid the transformation if there are multiple
18760     // uses of the loaded value.
18761     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18762       return SDValue();
18763
18764     SDLoc LdDL(Ld);
18765     SDLoc StDL(N);
18766     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18767     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18768     // pair instead.
18769     if (Subtarget->is64Bit() || F64IsLegal) {
18770       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18771       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18772                                   Ld->getPointerInfo(), Ld->isVolatile(),
18773                                   Ld->isNonTemporal(), Ld->isInvariant(),
18774                                   Ld->getAlignment());
18775       SDValue NewChain = NewLd.getValue(1);
18776       if (TokenFactorIndex != -1) {
18777         Ops.push_back(NewChain);
18778         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18779                                Ops.size());
18780       }
18781       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18782                           St->getPointerInfo(),
18783                           St->isVolatile(), St->isNonTemporal(),
18784                           St->getAlignment());
18785     }
18786
18787     // Otherwise, lower to two pairs of 32-bit loads / stores.
18788     SDValue LoAddr = Ld->getBasePtr();
18789     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18790                                  DAG.getConstant(4, MVT::i32));
18791
18792     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18793                                Ld->getPointerInfo(),
18794                                Ld->isVolatile(), Ld->isNonTemporal(),
18795                                Ld->isInvariant(), Ld->getAlignment());
18796     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18797                                Ld->getPointerInfo().getWithOffset(4),
18798                                Ld->isVolatile(), Ld->isNonTemporal(),
18799                                Ld->isInvariant(),
18800                                MinAlign(Ld->getAlignment(), 4));
18801
18802     SDValue NewChain = LoLd.getValue(1);
18803     if (TokenFactorIndex != -1) {
18804       Ops.push_back(LoLd);
18805       Ops.push_back(HiLd);
18806       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18807                              Ops.size());
18808     }
18809
18810     LoAddr = St->getBasePtr();
18811     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18812                          DAG.getConstant(4, MVT::i32));
18813
18814     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18815                                 St->getPointerInfo(),
18816                                 St->isVolatile(), St->isNonTemporal(),
18817                                 St->getAlignment());
18818     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18819                                 St->getPointerInfo().getWithOffset(4),
18820                                 St->isVolatile(),
18821                                 St->isNonTemporal(),
18822                                 MinAlign(St->getAlignment(), 4));
18823     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18824   }
18825   return SDValue();
18826 }
18827
18828 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18829 /// and return the operands for the horizontal operation in LHS and RHS.  A
18830 /// horizontal operation performs the binary operation on successive elements
18831 /// of its first operand, then on successive elements of its second operand,
18832 /// returning the resulting values in a vector.  For example, if
18833 ///   A = < float a0, float a1, float a2, float a3 >
18834 /// and
18835 ///   B = < float b0, float b1, float b2, float b3 >
18836 /// then the result of doing a horizontal operation on A and B is
18837 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18838 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18839 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18840 /// set to A, RHS to B, and the routine returns 'true'.
18841 /// Note that the binary operation should have the property that if one of the
18842 /// operands is UNDEF then the result is UNDEF.
18843 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18844   // Look for the following pattern: if
18845   //   A = < float a0, float a1, float a2, float a3 >
18846   //   B = < float b0, float b1, float b2, float b3 >
18847   // and
18848   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18849   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18850   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18851   // which is A horizontal-op B.
18852
18853   // At least one of the operands should be a vector shuffle.
18854   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18855       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18856     return false;
18857
18858   MVT VT = LHS.getSimpleValueType();
18859
18860   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18861          "Unsupported vector type for horizontal add/sub");
18862
18863   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18864   // operate independently on 128-bit lanes.
18865   unsigned NumElts = VT.getVectorNumElements();
18866   unsigned NumLanes = VT.getSizeInBits()/128;
18867   unsigned NumLaneElts = NumElts / NumLanes;
18868   assert((NumLaneElts % 2 == 0) &&
18869          "Vector type should have an even number of elements in each lane");
18870   unsigned HalfLaneElts = NumLaneElts/2;
18871
18872   // View LHS in the form
18873   //   LHS = VECTOR_SHUFFLE A, B, LMask
18874   // If LHS is not a shuffle then pretend it is the shuffle
18875   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18876   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18877   // type VT.
18878   SDValue A, B;
18879   SmallVector<int, 16> LMask(NumElts);
18880   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18881     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18882       A = LHS.getOperand(0);
18883     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18884       B = LHS.getOperand(1);
18885     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18886     std::copy(Mask.begin(), Mask.end(), LMask.begin());
18887   } else {
18888     if (LHS.getOpcode() != ISD::UNDEF)
18889       A = LHS;
18890     for (unsigned i = 0; i != NumElts; ++i)
18891       LMask[i] = i;
18892   }
18893
18894   // Likewise, view RHS in the form
18895   //   RHS = VECTOR_SHUFFLE C, D, RMask
18896   SDValue C, D;
18897   SmallVector<int, 16> RMask(NumElts);
18898   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18899     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
18900       C = RHS.getOperand(0);
18901     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
18902       D = RHS.getOperand(1);
18903     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
18904     std::copy(Mask.begin(), Mask.end(), RMask.begin());
18905   } else {
18906     if (RHS.getOpcode() != ISD::UNDEF)
18907       C = RHS;
18908     for (unsigned i = 0; i != NumElts; ++i)
18909       RMask[i] = i;
18910   }
18911
18912   // Check that the shuffles are both shuffling the same vectors.
18913   if (!(A == C && B == D) && !(A == D && B == C))
18914     return false;
18915
18916   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
18917   if (!A.getNode() && !B.getNode())
18918     return false;
18919
18920   // If A and B occur in reverse order in RHS, then "swap" them (which means
18921   // rewriting the mask).
18922   if (A != C)
18923     CommuteVectorShuffleMask(RMask, NumElts);
18924
18925   // At this point LHS and RHS are equivalent to
18926   //   LHS = VECTOR_SHUFFLE A, B, LMask
18927   //   RHS = VECTOR_SHUFFLE A, B, RMask
18928   // Check that the masks correspond to performing a horizontal operation.
18929   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
18930     for (unsigned i = 0; i != NumLaneElts; ++i) {
18931       int LIdx = LMask[i+l], RIdx = RMask[i+l];
18932
18933       // Ignore any UNDEF components.
18934       if (LIdx < 0 || RIdx < 0 ||
18935           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
18936           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
18937         continue;
18938
18939       // Check that successive elements are being operated on.  If not, this is
18940       // not a horizontal operation.
18941       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
18942       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
18943       if (!(LIdx == Index && RIdx == Index + 1) &&
18944           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
18945         return false;
18946     }
18947   }
18948
18949   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
18950   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
18951   return true;
18952 }
18953
18954 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
18955 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
18956                                   const X86Subtarget *Subtarget) {
18957   EVT VT = N->getValueType(0);
18958   SDValue LHS = N->getOperand(0);
18959   SDValue RHS = N->getOperand(1);
18960
18961   // Try to synthesize horizontal adds from adds of shuffles.
18962   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18963        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18964       isHorizontalBinOp(LHS, RHS, true))
18965     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
18966   return SDValue();
18967 }
18968
18969 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
18970 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
18971                                   const X86Subtarget *Subtarget) {
18972   EVT VT = N->getValueType(0);
18973   SDValue LHS = N->getOperand(0);
18974   SDValue RHS = N->getOperand(1);
18975
18976   // Try to synthesize horizontal subs from subs of shuffles.
18977   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18978        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18979       isHorizontalBinOp(LHS, RHS, false))
18980     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18981   return SDValue();
18982 }
18983
18984 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18985 /// X86ISD::FXOR nodes.
18986 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18987   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18988   // F[X]OR(0.0, x) -> x
18989   // F[X]OR(x, 0.0) -> x
18990   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18991     if (C->getValueAPF().isPosZero())
18992       return N->getOperand(1);
18993   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18994     if (C->getValueAPF().isPosZero())
18995       return N->getOperand(0);
18996   return SDValue();
18997 }
18998
18999 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19000 /// X86ISD::FMAX nodes.
19001 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19002   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19003
19004   // Only perform optimizations if UnsafeMath is used.
19005   if (!DAG.getTarget().Options.UnsafeFPMath)
19006     return SDValue();
19007
19008   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19009   // into FMINC and FMAXC, which are Commutative operations.
19010   unsigned NewOp = 0;
19011   switch (N->getOpcode()) {
19012     default: llvm_unreachable("unknown opcode");
19013     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19014     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19015   }
19016
19017   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19018                      N->getOperand(0), N->getOperand(1));
19019 }
19020
19021 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19022 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19023   // FAND(0.0, x) -> 0.0
19024   // FAND(x, 0.0) -> 0.0
19025   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19026     if (C->getValueAPF().isPosZero())
19027       return N->getOperand(0);
19028   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19029     if (C->getValueAPF().isPosZero())
19030       return N->getOperand(1);
19031   return SDValue();
19032 }
19033
19034 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19035 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19036   // FANDN(x, 0.0) -> 0.0
19037   // FANDN(0.0, x) -> x
19038   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19039     if (C->getValueAPF().isPosZero())
19040       return N->getOperand(1);
19041   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19042     if (C->getValueAPF().isPosZero())
19043       return N->getOperand(1);
19044   return SDValue();
19045 }
19046
19047 static SDValue PerformBTCombine(SDNode *N,
19048                                 SelectionDAG &DAG,
19049                                 TargetLowering::DAGCombinerInfo &DCI) {
19050   // BT ignores high bits in the bit index operand.
19051   SDValue Op1 = N->getOperand(1);
19052   if (Op1.hasOneUse()) {
19053     unsigned BitWidth = Op1.getValueSizeInBits();
19054     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19055     APInt KnownZero, KnownOne;
19056     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19057                                           !DCI.isBeforeLegalizeOps());
19058     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19059     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19060         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19061       DCI.CommitTargetLoweringOpt(TLO);
19062   }
19063   return SDValue();
19064 }
19065
19066 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19067   SDValue Op = N->getOperand(0);
19068   if (Op.getOpcode() == ISD::BITCAST)
19069     Op = Op.getOperand(0);
19070   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19071   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19072       VT.getVectorElementType().getSizeInBits() ==
19073       OpVT.getVectorElementType().getSizeInBits()) {
19074     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19075   }
19076   return SDValue();
19077 }
19078
19079 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19080                                                const X86Subtarget *Subtarget) {
19081   EVT VT = N->getValueType(0);
19082   if (!VT.isVector())
19083     return SDValue();
19084
19085   SDValue N0 = N->getOperand(0);
19086   SDValue N1 = N->getOperand(1);
19087   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19088   SDLoc dl(N);
19089
19090   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19091   // both SSE and AVX2 since there is no sign-extended shift right
19092   // operation on a vector with 64-bit elements.
19093   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19094   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19095   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19096       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19097     SDValue N00 = N0.getOperand(0);
19098
19099     // EXTLOAD has a better solution on AVX2,
19100     // it may be replaced with X86ISD::VSEXT node.
19101     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19102       if (!ISD::isNormalLoad(N00.getNode()))
19103         return SDValue();
19104
19105     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19106         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19107                                   N00, N1);
19108       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19109     }
19110   }
19111   return SDValue();
19112 }
19113
19114 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19115                                   TargetLowering::DAGCombinerInfo &DCI,
19116                                   const X86Subtarget *Subtarget) {
19117   if (!DCI.isBeforeLegalizeOps())
19118     return SDValue();
19119
19120   if (!Subtarget->hasFp256())
19121     return SDValue();
19122
19123   EVT VT = N->getValueType(0);
19124   if (VT.isVector() && VT.getSizeInBits() == 256) {
19125     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19126     if (R.getNode())
19127       return R;
19128   }
19129
19130   return SDValue();
19131 }
19132
19133 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19134                                  const X86Subtarget* Subtarget) {
19135   SDLoc dl(N);
19136   EVT VT = N->getValueType(0);
19137
19138   // Let legalize expand this if it isn't a legal type yet.
19139   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19140     return SDValue();
19141
19142   EVT ScalarVT = VT.getScalarType();
19143   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19144       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19145     return SDValue();
19146
19147   SDValue A = N->getOperand(0);
19148   SDValue B = N->getOperand(1);
19149   SDValue C = N->getOperand(2);
19150
19151   bool NegA = (A.getOpcode() == ISD::FNEG);
19152   bool NegB = (B.getOpcode() == ISD::FNEG);
19153   bool NegC = (C.getOpcode() == ISD::FNEG);
19154
19155   // Negative multiplication when NegA xor NegB
19156   bool NegMul = (NegA != NegB);
19157   if (NegA)
19158     A = A.getOperand(0);
19159   if (NegB)
19160     B = B.getOperand(0);
19161   if (NegC)
19162     C = C.getOperand(0);
19163
19164   unsigned Opcode;
19165   if (!NegMul)
19166     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19167   else
19168     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19169
19170   return DAG.getNode(Opcode, dl, VT, A, B, C);
19171 }
19172
19173 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19174                                   TargetLowering::DAGCombinerInfo &DCI,
19175                                   const X86Subtarget *Subtarget) {
19176   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19177   //           (and (i32 x86isd::setcc_carry), 1)
19178   // This eliminates the zext. This transformation is necessary because
19179   // ISD::SETCC is always legalized to i8.
19180   SDLoc dl(N);
19181   SDValue N0 = N->getOperand(0);
19182   EVT VT = N->getValueType(0);
19183
19184   if (N0.getOpcode() == ISD::AND &&
19185       N0.hasOneUse() &&
19186       N0.getOperand(0).hasOneUse()) {
19187     SDValue N00 = N0.getOperand(0);
19188     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19189       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19190       if (!C || C->getZExtValue() != 1)
19191         return SDValue();
19192       return DAG.getNode(ISD::AND, dl, VT,
19193                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19194                                      N00.getOperand(0), N00.getOperand(1)),
19195                          DAG.getConstant(1, VT));
19196     }
19197   }
19198
19199   if (N0.getOpcode() == ISD::TRUNCATE &&
19200       N0.hasOneUse() &&
19201       N0.getOperand(0).hasOneUse()) {
19202     SDValue N00 = N0.getOperand(0);
19203     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19204       return DAG.getNode(ISD::AND, dl, VT,
19205                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19206                                      N00.getOperand(0), N00.getOperand(1)),
19207                          DAG.getConstant(1, VT));
19208     }
19209   }
19210   if (VT.is256BitVector()) {
19211     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19212     if (R.getNode())
19213       return R;
19214   }
19215
19216   return SDValue();
19217 }
19218
19219 // Optimize x == -y --> x+y == 0
19220 //          x != -y --> x+y != 0
19221 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19222                                       const X86Subtarget* Subtarget) {
19223   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19224   SDValue LHS = N->getOperand(0);
19225   SDValue RHS = N->getOperand(1);
19226   EVT VT = N->getValueType(0);
19227   SDLoc DL(N);
19228
19229   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19230     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19231       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19232         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19233                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19234         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19235                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19236       }
19237   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19238     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19239       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19240         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19241                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19242         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19243                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19244       }
19245
19246   if (VT.getScalarType() == MVT::i1) {
19247     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19248       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19249     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19250     if (!IsSEXT0 && !IsVZero0)
19251       return SDValue();
19252     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19253       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19254     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19255
19256     if (!IsSEXT1 && !IsVZero1)
19257       return SDValue();
19258
19259     if (IsSEXT0 && IsVZero1) {
19260       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19261       if (CC == ISD::SETEQ)
19262         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19263       return LHS.getOperand(0);
19264     }
19265     if (IsSEXT1 && IsVZero0) {
19266       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19267       if (CC == ISD::SETEQ)
19268         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19269       return RHS.getOperand(0);
19270     }
19271   }
19272
19273   return SDValue();
19274 }
19275
19276 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19277 // as "sbb reg,reg", since it can be extended without zext and produces
19278 // an all-ones bit which is more useful than 0/1 in some cases.
19279 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19280                                MVT VT) {
19281   if (VT == MVT::i8)
19282     return DAG.getNode(ISD::AND, DL, VT,
19283                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19284                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19285                        DAG.getConstant(1, VT));
19286   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19287   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19288                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19289                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19290 }
19291
19292 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19293 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19294                                    TargetLowering::DAGCombinerInfo &DCI,
19295                                    const X86Subtarget *Subtarget) {
19296   SDLoc DL(N);
19297   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19298   SDValue EFLAGS = N->getOperand(1);
19299
19300   if (CC == X86::COND_A) {
19301     // Try to convert COND_A into COND_B in an attempt to facilitate
19302     // materializing "setb reg".
19303     //
19304     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19305     // cannot take an immediate as its first operand.
19306     //
19307     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19308         EFLAGS.getValueType().isInteger() &&
19309         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19310       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19311                                    EFLAGS.getNode()->getVTList(),
19312                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19313       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19314       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19315     }
19316   }
19317
19318   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19319   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19320   // cases.
19321   if (CC == X86::COND_B)
19322     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19323
19324   SDValue Flags;
19325
19326   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19327   if (Flags.getNode()) {
19328     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19329     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19330   }
19331
19332   return SDValue();
19333 }
19334
19335 // Optimize branch condition evaluation.
19336 //
19337 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19338                                     TargetLowering::DAGCombinerInfo &DCI,
19339                                     const X86Subtarget *Subtarget) {
19340   SDLoc DL(N);
19341   SDValue Chain = N->getOperand(0);
19342   SDValue Dest = N->getOperand(1);
19343   SDValue EFLAGS = N->getOperand(3);
19344   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19345
19346   SDValue Flags;
19347
19348   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19349   if (Flags.getNode()) {
19350     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19351     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19352                        Flags);
19353   }
19354
19355   return SDValue();
19356 }
19357
19358 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19359                                         const X86TargetLowering *XTLI) {
19360   SDValue Op0 = N->getOperand(0);
19361   EVT InVT = Op0->getValueType(0);
19362
19363   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19364   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19365     SDLoc dl(N);
19366     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19367     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19368     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19369   }
19370
19371   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19372   // a 32-bit target where SSE doesn't support i64->FP operations.
19373   if (Op0.getOpcode() == ISD::LOAD) {
19374     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19375     EVT VT = Ld->getValueType(0);
19376     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19377         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19378         !XTLI->getSubtarget()->is64Bit() &&
19379         VT == MVT::i64) {
19380       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19381                                           Ld->getChain(), Op0, DAG);
19382       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19383       return FILDChain;
19384     }
19385   }
19386   return SDValue();
19387 }
19388
19389 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19390 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19391                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19392   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19393   // the result is either zero or one (depending on the input carry bit).
19394   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19395   if (X86::isZeroNode(N->getOperand(0)) &&
19396       X86::isZeroNode(N->getOperand(1)) &&
19397       // We don't have a good way to replace an EFLAGS use, so only do this when
19398       // dead right now.
19399       SDValue(N, 1).use_empty()) {
19400     SDLoc DL(N);
19401     EVT VT = N->getValueType(0);
19402     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19403     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19404                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19405                                            DAG.getConstant(X86::COND_B,MVT::i8),
19406                                            N->getOperand(2)),
19407                                DAG.getConstant(1, VT));
19408     return DCI.CombineTo(N, Res1, CarryOut);
19409   }
19410
19411   return SDValue();
19412 }
19413
19414 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19415 //      (add Y, (setne X, 0)) -> sbb -1, Y
19416 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19417 //      (sub (setne X, 0), Y) -> adc -1, Y
19418 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19419   SDLoc DL(N);
19420
19421   // Look through ZExts.
19422   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19423   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19424     return SDValue();
19425
19426   SDValue SetCC = Ext.getOperand(0);
19427   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19428     return SDValue();
19429
19430   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19431   if (CC != X86::COND_E && CC != X86::COND_NE)
19432     return SDValue();
19433
19434   SDValue Cmp = SetCC.getOperand(1);
19435   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19436       !X86::isZeroNode(Cmp.getOperand(1)) ||
19437       !Cmp.getOperand(0).getValueType().isInteger())
19438     return SDValue();
19439
19440   SDValue CmpOp0 = Cmp.getOperand(0);
19441   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19442                                DAG.getConstant(1, CmpOp0.getValueType()));
19443
19444   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19445   if (CC == X86::COND_NE)
19446     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19447                        DL, OtherVal.getValueType(), OtherVal,
19448                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19449   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19450                      DL, OtherVal.getValueType(), OtherVal,
19451                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19452 }
19453
19454 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19455 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19456                                  const X86Subtarget *Subtarget) {
19457   EVT VT = N->getValueType(0);
19458   SDValue Op0 = N->getOperand(0);
19459   SDValue Op1 = N->getOperand(1);
19460
19461   // Try to synthesize horizontal adds from adds of shuffles.
19462   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19463        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19464       isHorizontalBinOp(Op0, Op1, true))
19465     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19466
19467   return OptimizeConditionalInDecrement(N, DAG);
19468 }
19469
19470 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19471                                  const X86Subtarget *Subtarget) {
19472   SDValue Op0 = N->getOperand(0);
19473   SDValue Op1 = N->getOperand(1);
19474
19475   // X86 can't encode an immediate LHS of a sub. See if we can push the
19476   // negation into a preceding instruction.
19477   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19478     // If the RHS of the sub is a XOR with one use and a constant, invert the
19479     // immediate. Then add one to the LHS of the sub so we can turn
19480     // X-Y -> X+~Y+1, saving one register.
19481     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19482         isa<ConstantSDNode>(Op1.getOperand(1))) {
19483       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19484       EVT VT = Op0.getValueType();
19485       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19486                                    Op1.getOperand(0),
19487                                    DAG.getConstant(~XorC, VT));
19488       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19489                          DAG.getConstant(C->getAPIntValue()+1, VT));
19490     }
19491   }
19492
19493   // Try to synthesize horizontal adds from adds of shuffles.
19494   EVT VT = N->getValueType(0);
19495   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19496        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19497       isHorizontalBinOp(Op0, Op1, true))
19498     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19499
19500   return OptimizeConditionalInDecrement(N, DAG);
19501 }
19502
19503 /// performVZEXTCombine - Performs build vector combines
19504 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19505                                         TargetLowering::DAGCombinerInfo &DCI,
19506                                         const X86Subtarget *Subtarget) {
19507   // (vzext (bitcast (vzext (x)) -> (vzext x)
19508   SDValue In = N->getOperand(0);
19509   while (In.getOpcode() == ISD::BITCAST)
19510     In = In.getOperand(0);
19511
19512   if (In.getOpcode() != X86ISD::VZEXT)
19513     return SDValue();
19514
19515   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19516                      In.getOperand(0));
19517 }
19518
19519 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19520                                              DAGCombinerInfo &DCI) const {
19521   SelectionDAG &DAG = DCI.DAG;
19522   switch (N->getOpcode()) {
19523   default: break;
19524   case ISD::EXTRACT_VECTOR_ELT:
19525     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19526   case ISD::VSELECT:
19527   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19528   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19529   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19530   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19531   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19532   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19533   case ISD::SHL:
19534   case ISD::SRA:
19535   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19536   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19537   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19538   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19539   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19540   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19541   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19542   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19543   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19544   case X86ISD::FXOR:
19545   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19546   case X86ISD::FMIN:
19547   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19548   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19549   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19550   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19551   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19552   case ISD::ANY_EXTEND:
19553   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19554   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19555   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19556   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19557   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
19558   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19559   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19560   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19561   case X86ISD::SHUFP:       // Handle all target specific shuffles
19562   case X86ISD::PALIGNR:
19563   case X86ISD::UNPCKH:
19564   case X86ISD::UNPCKL:
19565   case X86ISD::MOVHLPS:
19566   case X86ISD::MOVLHPS:
19567   case X86ISD::PSHUFD:
19568   case X86ISD::PSHUFHW:
19569   case X86ISD::PSHUFLW:
19570   case X86ISD::MOVSS:
19571   case X86ISD::MOVSD:
19572   case X86ISD::VPERMILP:
19573   case X86ISD::VPERM2X128:
19574   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19575   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19576   }
19577
19578   return SDValue();
19579 }
19580
19581 /// isTypeDesirableForOp - Return true if the target has native support for
19582 /// the specified value type and it is 'desirable' to use the type for the
19583 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19584 /// instruction encodings are longer and some i16 instructions are slow.
19585 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19586   if (!isTypeLegal(VT))
19587     return false;
19588   if (VT != MVT::i16)
19589     return true;
19590
19591   switch (Opc) {
19592   default:
19593     return true;
19594   case ISD::LOAD:
19595   case ISD::SIGN_EXTEND:
19596   case ISD::ZERO_EXTEND:
19597   case ISD::ANY_EXTEND:
19598   case ISD::SHL:
19599   case ISD::SRL:
19600   case ISD::SUB:
19601   case ISD::ADD:
19602   case ISD::MUL:
19603   case ISD::AND:
19604   case ISD::OR:
19605   case ISD::XOR:
19606     return false;
19607   }
19608 }
19609
19610 /// IsDesirableToPromoteOp - This method query the target whether it is
19611 /// beneficial for dag combiner to promote the specified node. If true, it
19612 /// should return the desired promotion type by reference.
19613 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19614   EVT VT = Op.getValueType();
19615   if (VT != MVT::i16)
19616     return false;
19617
19618   bool Promote = false;
19619   bool Commute = false;
19620   switch (Op.getOpcode()) {
19621   default: break;
19622   case ISD::LOAD: {
19623     LoadSDNode *LD = cast<LoadSDNode>(Op);
19624     // If the non-extending load has a single use and it's not live out, then it
19625     // might be folded.
19626     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19627                                                      Op.hasOneUse()*/) {
19628       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19629              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19630         // The only case where we'd want to promote LOAD (rather then it being
19631         // promoted as an operand is when it's only use is liveout.
19632         if (UI->getOpcode() != ISD::CopyToReg)
19633           return false;
19634       }
19635     }
19636     Promote = true;
19637     break;
19638   }
19639   case ISD::SIGN_EXTEND:
19640   case ISD::ZERO_EXTEND:
19641   case ISD::ANY_EXTEND:
19642     Promote = true;
19643     break;
19644   case ISD::SHL:
19645   case ISD::SRL: {
19646     SDValue N0 = Op.getOperand(0);
19647     // Look out for (store (shl (load), x)).
19648     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19649       return false;
19650     Promote = true;
19651     break;
19652   }
19653   case ISD::ADD:
19654   case ISD::MUL:
19655   case ISD::AND:
19656   case ISD::OR:
19657   case ISD::XOR:
19658     Commute = true;
19659     // fallthrough
19660   case ISD::SUB: {
19661     SDValue N0 = Op.getOperand(0);
19662     SDValue N1 = Op.getOperand(1);
19663     if (!Commute && MayFoldLoad(N1))
19664       return false;
19665     // Avoid disabling potential load folding opportunities.
19666     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19667       return false;
19668     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19669       return false;
19670     Promote = true;
19671   }
19672   }
19673
19674   PVT = MVT::i32;
19675   return Promote;
19676 }
19677
19678 //===----------------------------------------------------------------------===//
19679 //                           X86 Inline Assembly Support
19680 //===----------------------------------------------------------------------===//
19681
19682 namespace {
19683   // Helper to match a string separated by whitespace.
19684   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19685     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19686
19687     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19688       StringRef piece(*args[i]);
19689       if (!s.startswith(piece)) // Check if the piece matches.
19690         return false;
19691
19692       s = s.substr(piece.size());
19693       StringRef::size_type pos = s.find_first_not_of(" \t");
19694       if (pos == 0) // We matched a prefix.
19695         return false;
19696
19697       s = s.substr(pos);
19698     }
19699
19700     return s.empty();
19701   }
19702   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19703 }
19704
19705 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19706
19707   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19708     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19709         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19710         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19711
19712       if (AsmPieces.size() == 3)
19713         return true;
19714       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19715         return true;
19716     }
19717   }
19718   return false;
19719 }
19720
19721 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19722   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19723
19724   std::string AsmStr = IA->getAsmString();
19725
19726   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19727   if (!Ty || Ty->getBitWidth() % 16 != 0)
19728     return false;
19729
19730   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19731   SmallVector<StringRef, 4> AsmPieces;
19732   SplitString(AsmStr, AsmPieces, ";\n");
19733
19734   switch (AsmPieces.size()) {
19735   default: return false;
19736   case 1:
19737     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19738     // we will turn this bswap into something that will be lowered to logical
19739     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19740     // lower so don't worry about this.
19741     // bswap $0
19742     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19743         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19744         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19745         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19746         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19747         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19748       // No need to check constraints, nothing other than the equivalent of
19749       // "=r,0" would be valid here.
19750       return IntrinsicLowering::LowerToByteSwap(CI);
19751     }
19752
19753     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19754     if (CI->getType()->isIntegerTy(16) &&
19755         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19756         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19757          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19758       AsmPieces.clear();
19759       const std::string &ConstraintsStr = IA->getConstraintString();
19760       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19761       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19762       if (clobbersFlagRegisters(AsmPieces))
19763         return IntrinsicLowering::LowerToByteSwap(CI);
19764     }
19765     break;
19766   case 3:
19767     if (CI->getType()->isIntegerTy(32) &&
19768         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19769         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19770         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19771         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19772       AsmPieces.clear();
19773       const std::string &ConstraintsStr = IA->getConstraintString();
19774       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19775       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19776       if (clobbersFlagRegisters(AsmPieces))
19777         return IntrinsicLowering::LowerToByteSwap(CI);
19778     }
19779
19780     if (CI->getType()->isIntegerTy(64)) {
19781       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19782       if (Constraints.size() >= 2 &&
19783           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19784           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19785         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19786         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19787             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19788             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19789           return IntrinsicLowering::LowerToByteSwap(CI);
19790       }
19791     }
19792     break;
19793   }
19794   return false;
19795 }
19796
19797 /// getConstraintType - Given a constraint letter, return the type of
19798 /// constraint it is for this target.
19799 X86TargetLowering::ConstraintType
19800 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19801   if (Constraint.size() == 1) {
19802     switch (Constraint[0]) {
19803     case 'R':
19804     case 'q':
19805     case 'Q':
19806     case 'f':
19807     case 't':
19808     case 'u':
19809     case 'y':
19810     case 'x':
19811     case 'Y':
19812     case 'l':
19813       return C_RegisterClass;
19814     case 'a':
19815     case 'b':
19816     case 'c':
19817     case 'd':
19818     case 'S':
19819     case 'D':
19820     case 'A':
19821       return C_Register;
19822     case 'I':
19823     case 'J':
19824     case 'K':
19825     case 'L':
19826     case 'M':
19827     case 'N':
19828     case 'G':
19829     case 'C':
19830     case 'e':
19831     case 'Z':
19832       return C_Other;
19833     default:
19834       break;
19835     }
19836   }
19837   return TargetLowering::getConstraintType(Constraint);
19838 }
19839
19840 /// Examine constraint type and operand type and determine a weight value.
19841 /// This object must already have been set up with the operand type
19842 /// and the current alternative constraint selected.
19843 TargetLowering::ConstraintWeight
19844   X86TargetLowering::getSingleConstraintMatchWeight(
19845     AsmOperandInfo &info, const char *constraint) const {
19846   ConstraintWeight weight = CW_Invalid;
19847   Value *CallOperandVal = info.CallOperandVal;
19848     // If we don't have a value, we can't do a match,
19849     // but allow it at the lowest weight.
19850   if (CallOperandVal == NULL)
19851     return CW_Default;
19852   Type *type = CallOperandVal->getType();
19853   // Look at the constraint type.
19854   switch (*constraint) {
19855   default:
19856     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19857   case 'R':
19858   case 'q':
19859   case 'Q':
19860   case 'a':
19861   case 'b':
19862   case 'c':
19863   case 'd':
19864   case 'S':
19865   case 'D':
19866   case 'A':
19867     if (CallOperandVal->getType()->isIntegerTy())
19868       weight = CW_SpecificReg;
19869     break;
19870   case 'f':
19871   case 't':
19872   case 'u':
19873     if (type->isFloatingPointTy())
19874       weight = CW_SpecificReg;
19875     break;
19876   case 'y':
19877     if (type->isX86_MMXTy() && Subtarget->hasMMX())
19878       weight = CW_SpecificReg;
19879     break;
19880   case 'x':
19881   case 'Y':
19882     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19883         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19884       weight = CW_Register;
19885     break;
19886   case 'I':
19887     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19888       if (C->getZExtValue() <= 31)
19889         weight = CW_Constant;
19890     }
19891     break;
19892   case 'J':
19893     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19894       if (C->getZExtValue() <= 63)
19895         weight = CW_Constant;
19896     }
19897     break;
19898   case 'K':
19899     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19900       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
19901         weight = CW_Constant;
19902     }
19903     break;
19904   case 'L':
19905     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19906       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
19907         weight = CW_Constant;
19908     }
19909     break;
19910   case 'M':
19911     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19912       if (C->getZExtValue() <= 3)
19913         weight = CW_Constant;
19914     }
19915     break;
19916   case 'N':
19917     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19918       if (C->getZExtValue() <= 0xff)
19919         weight = CW_Constant;
19920     }
19921     break;
19922   case 'G':
19923   case 'C':
19924     if (dyn_cast<ConstantFP>(CallOperandVal)) {
19925       weight = CW_Constant;
19926     }
19927     break;
19928   case 'e':
19929     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19930       if ((C->getSExtValue() >= -0x80000000LL) &&
19931           (C->getSExtValue() <= 0x7fffffffLL))
19932         weight = CW_Constant;
19933     }
19934     break;
19935   case 'Z':
19936     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19937       if (C->getZExtValue() <= 0xffffffff)
19938         weight = CW_Constant;
19939     }
19940     break;
19941   }
19942   return weight;
19943 }
19944
19945 /// LowerXConstraint - try to replace an X constraint, which matches anything,
19946 /// with another that has more specific requirements based on the type of the
19947 /// corresponding operand.
19948 const char *X86TargetLowering::
19949 LowerXConstraint(EVT ConstraintVT) const {
19950   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
19951   // 'f' like normal targets.
19952   if (ConstraintVT.isFloatingPoint()) {
19953     if (Subtarget->hasSSE2())
19954       return "Y";
19955     if (Subtarget->hasSSE1())
19956       return "x";
19957   }
19958
19959   return TargetLowering::LowerXConstraint(ConstraintVT);
19960 }
19961
19962 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19963 /// vector.  If it is invalid, don't add anything to Ops.
19964 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19965                                                      std::string &Constraint,
19966                                                      std::vector<SDValue>&Ops,
19967                                                      SelectionDAG &DAG) const {
19968   SDValue Result(0, 0);
19969
19970   // Only support length 1 constraints for now.
19971   if (Constraint.length() > 1) return;
19972
19973   char ConstraintLetter = Constraint[0];
19974   switch (ConstraintLetter) {
19975   default: break;
19976   case 'I':
19977     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19978       if (C->getZExtValue() <= 31) {
19979         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19980         break;
19981       }
19982     }
19983     return;
19984   case 'J':
19985     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19986       if (C->getZExtValue() <= 63) {
19987         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19988         break;
19989       }
19990     }
19991     return;
19992   case 'K':
19993     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19994       if (isInt<8>(C->getSExtValue())) {
19995         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19996         break;
19997       }
19998     }
19999     return;
20000   case 'N':
20001     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20002       if (C->getZExtValue() <= 255) {
20003         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20004         break;
20005       }
20006     }
20007     return;
20008   case 'e': {
20009     // 32-bit signed value
20010     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20011       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20012                                            C->getSExtValue())) {
20013         // Widen to 64 bits here to get it sign extended.
20014         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20015         break;
20016       }
20017     // FIXME gcc accepts some relocatable values here too, but only in certain
20018     // memory models; it's complicated.
20019     }
20020     return;
20021   }
20022   case 'Z': {
20023     // 32-bit unsigned value
20024     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20025       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20026                                            C->getZExtValue())) {
20027         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20028         break;
20029       }
20030     }
20031     // FIXME gcc accepts some relocatable values here too, but only in certain
20032     // memory models; it's complicated.
20033     return;
20034   }
20035   case 'i': {
20036     // Literal immediates are always ok.
20037     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20038       // Widen to 64 bits here to get it sign extended.
20039       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20040       break;
20041     }
20042
20043     // In any sort of PIC mode addresses need to be computed at runtime by
20044     // adding in a register or some sort of table lookup.  These can't
20045     // be used as immediates.
20046     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20047       return;
20048
20049     // If we are in non-pic codegen mode, we allow the address of a global (with
20050     // an optional displacement) to be used with 'i'.
20051     GlobalAddressSDNode *GA = 0;
20052     int64_t Offset = 0;
20053
20054     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20055     while (1) {
20056       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20057         Offset += GA->getOffset();
20058         break;
20059       } else if (Op.getOpcode() == ISD::ADD) {
20060         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20061           Offset += C->getZExtValue();
20062           Op = Op.getOperand(0);
20063           continue;
20064         }
20065       } else if (Op.getOpcode() == ISD::SUB) {
20066         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20067           Offset += -C->getZExtValue();
20068           Op = Op.getOperand(0);
20069           continue;
20070         }
20071       }
20072
20073       // Otherwise, this isn't something we can handle, reject it.
20074       return;
20075     }
20076
20077     const GlobalValue *GV = GA->getGlobal();
20078     // If we require an extra load to get this address, as in PIC mode, we
20079     // can't accept it.
20080     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20081                                                         getTargetMachine())))
20082       return;
20083
20084     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20085                                         GA->getValueType(0), Offset);
20086     break;
20087   }
20088   }
20089
20090   if (Result.getNode()) {
20091     Ops.push_back(Result);
20092     return;
20093   }
20094   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20095 }
20096
20097 std::pair<unsigned, const TargetRegisterClass*>
20098 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20099                                                 MVT VT) const {
20100   // First, see if this is a constraint that directly corresponds to an LLVM
20101   // register class.
20102   if (Constraint.size() == 1) {
20103     // GCC Constraint Letters
20104     switch (Constraint[0]) {
20105     default: break;
20106       // TODO: Slight differences here in allocation order and leaving
20107       // RIP in the class. Do they matter any more here than they do
20108       // in the normal allocation?
20109     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20110       if (Subtarget->is64Bit()) {
20111         if (VT == MVT::i32 || VT == MVT::f32)
20112           return std::make_pair(0U, &X86::GR32RegClass);
20113         if (VT == MVT::i16)
20114           return std::make_pair(0U, &X86::GR16RegClass);
20115         if (VT == MVT::i8 || VT == MVT::i1)
20116           return std::make_pair(0U, &X86::GR8RegClass);
20117         if (VT == MVT::i64 || VT == MVT::f64)
20118           return std::make_pair(0U, &X86::GR64RegClass);
20119         break;
20120       }
20121       // 32-bit fallthrough
20122     case 'Q':   // Q_REGS
20123       if (VT == MVT::i32 || VT == MVT::f32)
20124         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20125       if (VT == MVT::i16)
20126         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20127       if (VT == MVT::i8 || VT == MVT::i1)
20128         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20129       if (VT == MVT::i64)
20130         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20131       break;
20132     case 'r':   // GENERAL_REGS
20133     case 'l':   // INDEX_REGS
20134       if (VT == MVT::i8 || VT == MVT::i1)
20135         return std::make_pair(0U, &X86::GR8RegClass);
20136       if (VT == MVT::i16)
20137         return std::make_pair(0U, &X86::GR16RegClass);
20138       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20139         return std::make_pair(0U, &X86::GR32RegClass);
20140       return std::make_pair(0U, &X86::GR64RegClass);
20141     case 'R':   // LEGACY_REGS
20142       if (VT == MVT::i8 || VT == MVT::i1)
20143         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20144       if (VT == MVT::i16)
20145         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20146       if (VT == MVT::i32 || !Subtarget->is64Bit())
20147         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20148       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20149     case 'f':  // FP Stack registers.
20150       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20151       // value to the correct fpstack register class.
20152       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20153         return std::make_pair(0U, &X86::RFP32RegClass);
20154       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20155         return std::make_pair(0U, &X86::RFP64RegClass);
20156       return std::make_pair(0U, &X86::RFP80RegClass);
20157     case 'y':   // MMX_REGS if MMX allowed.
20158       if (!Subtarget->hasMMX()) break;
20159       return std::make_pair(0U, &X86::VR64RegClass);
20160     case 'Y':   // SSE_REGS if SSE2 allowed
20161       if (!Subtarget->hasSSE2()) break;
20162       // FALL THROUGH.
20163     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20164       if (!Subtarget->hasSSE1()) break;
20165
20166       switch (VT.SimpleTy) {
20167       default: break;
20168       // Scalar SSE types.
20169       case MVT::f32:
20170       case MVT::i32:
20171         return std::make_pair(0U, &X86::FR32RegClass);
20172       case MVT::f64:
20173       case MVT::i64:
20174         return std::make_pair(0U, &X86::FR64RegClass);
20175       // Vector types.
20176       case MVT::v16i8:
20177       case MVT::v8i16:
20178       case MVT::v4i32:
20179       case MVT::v2i64:
20180       case MVT::v4f32:
20181       case MVT::v2f64:
20182         return std::make_pair(0U, &X86::VR128RegClass);
20183       // AVX types.
20184       case MVT::v32i8:
20185       case MVT::v16i16:
20186       case MVT::v8i32:
20187       case MVT::v4i64:
20188       case MVT::v8f32:
20189       case MVT::v4f64:
20190         return std::make_pair(0U, &X86::VR256RegClass);
20191       case MVT::v8f64:
20192       case MVT::v16f32:
20193       case MVT::v16i32:
20194       case MVT::v8i64:
20195         return std::make_pair(0U, &X86::VR512RegClass);
20196       }
20197       break;
20198     }
20199   }
20200
20201   // Use the default implementation in TargetLowering to convert the register
20202   // constraint into a member of a register class.
20203   std::pair<unsigned, const TargetRegisterClass*> Res;
20204   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20205
20206   // Not found as a standard register?
20207   if (Res.second == 0) {
20208     // Map st(0) -> st(7) -> ST0
20209     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20210         tolower(Constraint[1]) == 's' &&
20211         tolower(Constraint[2]) == 't' &&
20212         Constraint[3] == '(' &&
20213         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20214         Constraint[5] == ')' &&
20215         Constraint[6] == '}') {
20216
20217       Res.first = X86::ST0+Constraint[4]-'0';
20218       Res.second = &X86::RFP80RegClass;
20219       return Res;
20220     }
20221
20222     // GCC allows "st(0)" to be called just plain "st".
20223     if (StringRef("{st}").equals_lower(Constraint)) {
20224       Res.first = X86::ST0;
20225       Res.second = &X86::RFP80RegClass;
20226       return Res;
20227     }
20228
20229     // flags -> EFLAGS
20230     if (StringRef("{flags}").equals_lower(Constraint)) {
20231       Res.first = X86::EFLAGS;
20232       Res.second = &X86::CCRRegClass;
20233       return Res;
20234     }
20235
20236     // 'A' means EAX + EDX.
20237     if (Constraint == "A") {
20238       Res.first = X86::EAX;
20239       Res.second = &X86::GR32_ADRegClass;
20240       return Res;
20241     }
20242     return Res;
20243   }
20244
20245   // Otherwise, check to see if this is a register class of the wrong value
20246   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20247   // turn into {ax},{dx}.
20248   if (Res.second->hasType(VT))
20249     return Res;   // Correct type already, nothing to do.
20250
20251   // All of the single-register GCC register classes map their values onto
20252   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20253   // really want an 8-bit or 32-bit register, map to the appropriate register
20254   // class and return the appropriate register.
20255   if (Res.second == &X86::GR16RegClass) {
20256     if (VT == MVT::i8 || VT == MVT::i1) {
20257       unsigned DestReg = 0;
20258       switch (Res.first) {
20259       default: break;
20260       case X86::AX: DestReg = X86::AL; break;
20261       case X86::DX: DestReg = X86::DL; break;
20262       case X86::CX: DestReg = X86::CL; break;
20263       case X86::BX: DestReg = X86::BL; break;
20264       }
20265       if (DestReg) {
20266         Res.first = DestReg;
20267         Res.second = &X86::GR8RegClass;
20268       }
20269     } else if (VT == MVT::i32 || VT == MVT::f32) {
20270       unsigned DestReg = 0;
20271       switch (Res.first) {
20272       default: break;
20273       case X86::AX: DestReg = X86::EAX; break;
20274       case X86::DX: DestReg = X86::EDX; break;
20275       case X86::CX: DestReg = X86::ECX; break;
20276       case X86::BX: DestReg = X86::EBX; break;
20277       case X86::SI: DestReg = X86::ESI; break;
20278       case X86::DI: DestReg = X86::EDI; break;
20279       case X86::BP: DestReg = X86::EBP; break;
20280       case X86::SP: DestReg = X86::ESP; break;
20281       }
20282       if (DestReg) {
20283         Res.first = DestReg;
20284         Res.second = &X86::GR32RegClass;
20285       }
20286     } else if (VT == MVT::i64 || VT == MVT::f64) {
20287       unsigned DestReg = 0;
20288       switch (Res.first) {
20289       default: break;
20290       case X86::AX: DestReg = X86::RAX; break;
20291       case X86::DX: DestReg = X86::RDX; break;
20292       case X86::CX: DestReg = X86::RCX; break;
20293       case X86::BX: DestReg = X86::RBX; break;
20294       case X86::SI: DestReg = X86::RSI; break;
20295       case X86::DI: DestReg = X86::RDI; break;
20296       case X86::BP: DestReg = X86::RBP; break;
20297       case X86::SP: DestReg = X86::RSP; break;
20298       }
20299       if (DestReg) {
20300         Res.first = DestReg;
20301         Res.second = &X86::GR64RegClass;
20302       }
20303     }
20304   } else if (Res.second == &X86::FR32RegClass ||
20305              Res.second == &X86::FR64RegClass ||
20306              Res.second == &X86::VR128RegClass ||
20307              Res.second == &X86::VR256RegClass ||
20308              Res.second == &X86::FR32XRegClass ||
20309              Res.second == &X86::FR64XRegClass ||
20310              Res.second == &X86::VR128XRegClass ||
20311              Res.second == &X86::VR256XRegClass ||
20312              Res.second == &X86::VR512RegClass) {
20313     // Handle references to XMM physical registers that got mapped into the
20314     // wrong class.  This can happen with constraints like {xmm0} where the
20315     // target independent register mapper will just pick the first match it can
20316     // find, ignoring the required type.
20317
20318     if (VT == MVT::f32 || VT == MVT::i32)
20319       Res.second = &X86::FR32RegClass;
20320     else if (VT == MVT::f64 || VT == MVT::i64)
20321       Res.second = &X86::FR64RegClass;
20322     else if (X86::VR128RegClass.hasType(VT))
20323       Res.second = &X86::VR128RegClass;
20324     else if (X86::VR256RegClass.hasType(VT))
20325       Res.second = &X86::VR256RegClass;
20326     else if (X86::VR512RegClass.hasType(VT))
20327       Res.second = &X86::VR512RegClass;
20328   }
20329
20330   return Res;
20331 }