Fix for PR18045:
[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/IR/LLVMContext.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <cctype>
54 using namespace llvm;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
60                        SDValue V2);
61
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63                                 SelectionDAG &DAG, SDLoc dl,
64                                 unsigned vectorWidth) {
65   assert((vectorWidth == 128 || vectorWidth == 256) &&
66          "Unsupported vector width");
67   EVT VT = Vec.getValueType();
68   EVT ElVT = VT.getVectorElementType();
69   unsigned Factor = VT.getSizeInBits()/vectorWidth;
70   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71                                   VT.getVectorNumElements()/Factor);
72
73   // Extract from UNDEF is UNDEF.
74   if (Vec.getOpcode() == ISD::UNDEF)
75     return DAG.getUNDEF(ResultVT);
76
77   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
78   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79
80   // This is the index of the first element of the vectorWidth-bit chunk
81   // we want.
82   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
83                                * ElemsPerChunk);
84
85   // If the input is a buildvector just emit a smaller one.
86   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89
90   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
92                                VecIdx);
93
94   return Result;
95
96 }
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104                                    SelectionDAG &DAG, SDLoc dl) {
105   assert((Vec.getValueType().is256BitVector() ||
106           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
108 }
109
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112                                    SelectionDAG &DAG, SDLoc dl) {
113   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
115 }
116
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118                                unsigned IdxVal, SelectionDAG &DAG,
119                                SDLoc dl, unsigned vectorWidth) {
120   assert((vectorWidth == 128 || vectorWidth == 256) &&
121          "Unsupported vector width");
122   // Inserting UNDEF is Result
123   if (Vec.getOpcode() == ISD::UNDEF)
124     return Result;
125   EVT VT = Vec.getValueType();
126   EVT ElVT = VT.getVectorElementType();
127   EVT ResultVT = Result.getValueType();
128
129   // Insert the relevant vectorWidth bits.
130   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131
132   // This is the index of the first element of the vectorWidth-bit chunk
133   // we want.
134   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
135                                * ElemsPerChunk);
136
137   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
139                      VecIdx);
140 }
141 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference.  Idx is an index in the 128 bits
145 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148                                   unsigned IdxVal, SelectionDAG &DAG,
149                                   SDLoc dl) {
150   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
152 }
153
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155                                   unsigned IdxVal, SelectionDAG &DAG,
156                                   SDLoc dl) {
157   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
159 }
160
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166                                    unsigned NumElems, SelectionDAG &DAG,
167                                    SDLoc dl) {
168   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
170 }
171
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173                                    unsigned NumElems, SelectionDAG &DAG,
174                                    SDLoc dl) {
175   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
177 }
178
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181   bool is64Bit = Subtarget->is64Bit();
182
183   if (Subtarget->isTargetMacho()) {
184     if (is64Bit)
185       return new X86_64MachoTargetObjectFile();
186     return new TargetLoweringObjectFileMachO();
187   }
188
189   if (Subtarget->isTargetLinux())
190     return new X86LinuxTargetObjectFile();
191   if (Subtarget->isTargetELF())
192     return new TargetLoweringObjectFileELF();
193   if (Subtarget->isTargetCOFF())
194     return new TargetLoweringObjectFileCOFF();
195   llvm_unreachable("unknown subtarget type");
196 }
197
198 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
199   : TargetLowering(TM, createTLOF(TM)) {
200   Subtarget = &TM.getSubtarget<X86Subtarget>();
201   X86ScalarSSEf64 = Subtarget->hasSSE2();
202   X86ScalarSSEf32 = Subtarget->hasSSE1();
203   TD = getDataLayout();
204
205   resetOperationActions();
206 }
207
208 void X86TargetLowering::resetOperationActions() {
209   const TargetMachine &TM = getTargetMachine();
210   static bool FirstTimeThrough = true;
211
212   // If none of the target options have changed, then we don't need to reset the
213   // operation actions.
214   if (!FirstTimeThrough && TO == TM.Options) return;
215
216   if (!FirstTimeThrough) {
217     // Reinitialize the actions.
218     initActions();
219     FirstTimeThrough = false;
220   }
221
222   TO = TM.Options;
223
224   // Set up the TargetLowering object.
225   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
226
227   // X86 is weird, it always uses i8 for shift amounts and setcc results.
228   setBooleanContents(ZeroOrOneBooleanContent);
229   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
230   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
231
232   // For 64-bit since we have so many registers use the ILP scheduler, for
233   // 32-bit code use the register pressure specific scheduling.
234   // For Atom, always use ILP scheduling.
235   if (Subtarget->isAtom())
236     setSchedulingPreference(Sched::ILP);
237   else if (Subtarget->is64Bit())
238     setSchedulingPreference(Sched::ILP);
239   else
240     setSchedulingPreference(Sched::RegPressure);
241   const X86RegisterInfo *RegInfo =
242     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
243   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
244
245   // Bypass expensive divides on Atom when compiling with O2
246   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
247     addBypassSlowDiv(32, 8);
248     if (Subtarget->is64Bit())
249       addBypassSlowDiv(64, 16);
250   }
251
252   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
253     // Setup Windows compiler runtime calls.
254     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
255     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
256     setLibcallName(RTLIB::SREM_I64, "_allrem");
257     setLibcallName(RTLIB::UREM_I64, "_aullrem");
258     setLibcallName(RTLIB::MUL_I64, "_allmul");
259     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
260     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
264
265     // The _ftol2 runtime function has an unusual calling conv, which
266     // is modeled by a special pseudo-instruction.
267     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
268     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
269     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
270     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
271   }
272
273   if (Subtarget->isTargetDarwin()) {
274     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
275     setUseUnderscoreSetJmp(false);
276     setUseUnderscoreLongJmp(false);
277   } else if (Subtarget->isTargetMingw()) {
278     // MS runtime is weird: it exports _setjmp, but longjmp!
279     setUseUnderscoreSetJmp(true);
280     setUseUnderscoreLongJmp(false);
281   } else {
282     setUseUnderscoreSetJmp(true);
283     setUseUnderscoreLongJmp(true);
284   }
285
286   // Set up the register classes.
287   addRegisterClass(MVT::i8, &X86::GR8RegClass);
288   addRegisterClass(MVT::i16, &X86::GR16RegClass);
289   addRegisterClass(MVT::i32, &X86::GR32RegClass);
290   if (Subtarget->is64Bit())
291     addRegisterClass(MVT::i64, &X86::GR64RegClass);
292
293   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
294
295   // We don't accept any truncstore of integer registers.
296   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
297   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
298   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
299   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
302
303   // SETOEQ and SETUNE require checking two conditions.
304   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
305   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
306   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
307   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
310
311   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
312   // operation.
313   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
316
317   if (Subtarget->is64Bit()) {
318     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
319     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
320   } else if (!TM.Options.UseSoftFloat) {
321     // We have an algorithm for SSE2->double, and we turn this into a
322     // 64-bit FILD followed by conditional FADD for other targets.
323     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
324     // We have an algorithm for SSE2, and we turn this into a 64-bit
325     // FILD for other targets.
326     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
327   }
328
329   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
330   // this operation.
331   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
332   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
333
334   if (!TM.Options.UseSoftFloat) {
335     // SSE has no i16 to fp conversion, only i32
336     if (X86ScalarSSEf32) {
337       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
338       // f32 and f64 cases are Legal, f80 case is not
339       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
340     } else {
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
343     }
344   } else {
345     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
346     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
347   }
348
349   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
350   // are Legal, f80 is custom lowered.
351   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
352   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
353
354   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
355   // this operation.
356   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
357   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
358
359   if (X86ScalarSSEf32) {
360     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
361     // f32 and f64 cases are Legal, f80 case is not
362     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
363   } else {
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
366   }
367
368   // Handle FP_TO_UINT by promoting the destination to a larger signed
369   // conversion.
370   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
373
374   if (Subtarget->is64Bit()) {
375     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
376     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
377   } else if (!TM.Options.UseSoftFloat) {
378     // Since AVX is a superset of SSE3, only check for SSE here.
379     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
380       // Expand FP_TO_UINT into a select.
381       // FIXME: We would like to use a Custom expander here eventually to do
382       // the optimal thing for SSE vs. the default expansion in the legalizer.
383       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
384     else
385       // With SSE3 we can use fisttpll to convert to a signed i64; without
386       // SSE, we're stuck with a fistpll.
387       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
388   }
389
390   if (isTargetFTOL()) {
391     // Use the _ftol2 runtime function, which has a pseudo-instruction
392     // to handle its weird calling convention.
393     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
394   }
395
396   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
397   if (!X86ScalarSSEf64) {
398     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
399     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
400     if (Subtarget->is64Bit()) {
401       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
402       // Without SSE, i64->f64 goes through memory.
403       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
404     }
405   }
406
407   // Scalar integer divide and remainder are lowered to use operations that
408   // produce two results, to match the available instructions. This exposes
409   // the two-result form to trivial CSE, which is able to combine x/y and x%y
410   // into a single instruction.
411   //
412   // Scalar integer multiply-high is also lowered to use two-result
413   // operations, to match the available instructions. However, plain multiply
414   // (low) operations are left as Legal, as there are single-result
415   // instructions for this in x86. Using the two-result multiply instructions
416   // when both high and low results are needed must be arranged by dagcombine.
417   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
418     MVT VT = IntVTs[i];
419     setOperationAction(ISD::MULHS, VT, Expand);
420     setOperationAction(ISD::MULHU, VT, Expand);
421     setOperationAction(ISD::SDIV, VT, Expand);
422     setOperationAction(ISD::UDIV, VT, Expand);
423     setOperationAction(ISD::SREM, VT, Expand);
424     setOperationAction(ISD::UREM, VT, Expand);
425
426     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
427     setOperationAction(ISD::ADDC, VT, Custom);
428     setOperationAction(ISD::ADDE, VT, Custom);
429     setOperationAction(ISD::SUBC, VT, Custom);
430     setOperationAction(ISD::SUBE, VT, Custom);
431   }
432
433   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
434   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
435   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
436   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
442   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
443   if (Subtarget->is64Bit())
444     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
445   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
448   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
449   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
452   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
453
454   // Promote the i8 variants and force them on up to i32 which has a shorter
455   // encoding.
456   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
457   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
458   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
459   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
460   if (Subtarget->hasBMI()) {
461     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
462     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
463     if (Subtarget->is64Bit())
464       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
465   } else {
466     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
467     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
468     if (Subtarget->is64Bit())
469       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
470   }
471
472   if (Subtarget->hasLZCNT()) {
473     // When promoting the i8 variants, force them to i32 for a shorter
474     // encoding.
475     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
476     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
477     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
478     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
480     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
481     if (Subtarget->is64Bit())
482       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
483   } else {
484     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
485     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
486     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
490     if (Subtarget->is64Bit()) {
491       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
492       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
493     }
494   }
495
496   if (Subtarget->hasPOPCNT()) {
497     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
498   } else {
499     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
500     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
501     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
502     if (Subtarget->is64Bit())
503       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
504   }
505
506   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
507   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
508
509   // These should be promoted to a larger select which is supported.
510   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
511   // X86 wants to expand cmov itself.
512   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
513   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
514   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
515   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
516   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
517   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
518   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
519   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
520   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
523   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
524   if (Subtarget->is64Bit()) {
525     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
526     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
527   }
528   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
529   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
530   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
531   // support continuation, user-level threading, and etc.. As a result, no
532   // other SjLj exception interfaces are implemented and please don't build
533   // your own exception handling based on them.
534   // LLVM/Clang supports zero-cost DWARF exception handling.
535   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
536   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
537
538   // Darwin ABI issue.
539   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
540   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
541   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
542   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
543   if (Subtarget->is64Bit())
544     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
545   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
546   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
547   if (Subtarget->is64Bit()) {
548     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
549     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
550     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
551     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
552     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
553   }
554   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
555   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
556   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
557   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
558   if (Subtarget->is64Bit()) {
559     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
560     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
561     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
562   }
563
564   if (Subtarget->hasSSE1())
565     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
566
567   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
568
569   // Expand certain atomics
570   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
571     MVT VT = IntVTs[i];
572     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
573     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
574     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
575   }
576
577   if (!Subtarget->is64Bit()) {
578     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
590   }
591
592   if (Subtarget->hasCmpxchg16b()) {
593     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
594   }
595
596   // FIXME - use subtarget debug flags
597   if (!Subtarget->isTargetDarwin() &&
598       !Subtarget->isTargetELF() &&
599       !Subtarget->isTargetCygMing()) {
600     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
601   }
602
603   if (Subtarget->is64Bit()) {
604     setExceptionPointerRegister(X86::RAX);
605     setExceptionSelectorRegister(X86::RDX);
606   } else {
607     setExceptionPointerRegister(X86::EAX);
608     setExceptionSelectorRegister(X86::EDX);
609   }
610   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
611   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
612
613   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
614   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
615
616   setOperationAction(ISD::TRAP, MVT::Other, Legal);
617   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
618
619   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
620   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
621   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
622   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
623     // TargetInfo::X86_64ABIBuiltinVaList
624     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
625     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
626   } else {
627     // TargetInfo::CharPtrBuiltinVaList
628     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
629     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
630   }
631
632   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
633   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
634
635   if (Subtarget->isOSWindows() && !Subtarget->isTargetMacho())
636     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
637                        MVT::i64 : MVT::i32, Custom);
638   else if (TM.Options.EnableSegmentedStacks)
639     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640                        MVT::i64 : MVT::i32, Custom);
641   else
642     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
643                        MVT::i64 : MVT::i32, Expand);
644
645   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
646     // f32 and f64 use SSE.
647     // Set up the FP register classes.
648     addRegisterClass(MVT::f32, &X86::FR32RegClass);
649     addRegisterClass(MVT::f64, &X86::FR64RegClass);
650
651     // Use ANDPD to simulate FABS.
652     setOperationAction(ISD::FABS , MVT::f64, Custom);
653     setOperationAction(ISD::FABS , MVT::f32, Custom);
654
655     // Use XORP to simulate FNEG.
656     setOperationAction(ISD::FNEG , MVT::f64, Custom);
657     setOperationAction(ISD::FNEG , MVT::f32, Custom);
658
659     // Use ANDPD and ORPD to simulate FCOPYSIGN.
660     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
661     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
662
663     // Lower this to FGETSIGNx86 plus an AND.
664     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
665     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
666
667     // We don't support sin/cos/fmod
668     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
669     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
670     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
671     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
672     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
673     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
674
675     // Expand FP immediates into loads from the stack, except for the special
676     // cases we handle.
677     addLegalFPImmediate(APFloat(+0.0)); // xorpd
678     addLegalFPImmediate(APFloat(+0.0f)); // xorps
679   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
680     // Use SSE for f32, x87 for f64.
681     // Set up the FP register classes.
682     addRegisterClass(MVT::f32, &X86::FR32RegClass);
683     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
684
685     // Use ANDPS to simulate FABS.
686     setOperationAction(ISD::FABS , MVT::f32, Custom);
687
688     // Use XORP to simulate FNEG.
689     setOperationAction(ISD::FNEG , MVT::f32, Custom);
690
691     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
692
693     // Use ANDPS and ORPS to simulate FCOPYSIGN.
694     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
695     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
696
697     // We don't support sin/cos/fmod
698     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
699     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
700     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
701
702     // Special cases we handle for FP constants.
703     addLegalFPImmediate(APFloat(+0.0f)); // xorps
704     addLegalFPImmediate(APFloat(+0.0)); // FLD0
705     addLegalFPImmediate(APFloat(+1.0)); // FLD1
706     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
707     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
708
709     if (!TM.Options.UnsafeFPMath) {
710       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
711       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
712       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
713     }
714   } else if (!TM.Options.UseSoftFloat) {
715     // f32 and f64 in x87.
716     // Set up the FP register classes.
717     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
718     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
719
720     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
721     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
723     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
724
725     if (!TM.Options.UnsafeFPMath) {
726       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
727       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
728       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
729       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
730       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
731       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
732     }
733     addLegalFPImmediate(APFloat(+0.0)); // FLD0
734     addLegalFPImmediate(APFloat(+1.0)); // FLD1
735     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
736     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
737     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
738     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
739     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
740     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
741   }
742
743   // We don't support FMA.
744   setOperationAction(ISD::FMA, MVT::f64, Expand);
745   setOperationAction(ISD::FMA, MVT::f32, Expand);
746
747   // Long double always uses X87.
748   if (!TM.Options.UseSoftFloat) {
749     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
750     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
751     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
752     {
753       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
754       addLegalFPImmediate(TmpFlt);  // FLD0
755       TmpFlt.changeSign();
756       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
757
758       bool ignored;
759       APFloat TmpFlt2(+1.0);
760       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
761                       &ignored);
762       addLegalFPImmediate(TmpFlt2);  // FLD1
763       TmpFlt2.changeSign();
764       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
765     }
766
767     if (!TM.Options.UnsafeFPMath) {
768       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
769       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
770       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
771     }
772
773     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
774     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
775     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
776     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
777     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
778     setOperationAction(ISD::FMA, MVT::f80, Expand);
779   }
780
781   // Always use a library call for pow.
782   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
783   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
784   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
785
786   setOperationAction(ISD::FLOG, MVT::f80, Expand);
787   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
788   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
789   setOperationAction(ISD::FEXP, MVT::f80, Expand);
790   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
791
792   // First set operation action for all vector types to either promote
793   // (for widening) or expand (for scalarization). Then we will selectively
794   // turn on ones that can be effectively codegen'd.
795   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
796            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
797     MVT VT = (MVT::SimpleValueType)i;
798     setOperationAction(ISD::ADD , VT, Expand);
799     setOperationAction(ISD::SUB , VT, Expand);
800     setOperationAction(ISD::FADD, VT, Expand);
801     setOperationAction(ISD::FNEG, VT, Expand);
802     setOperationAction(ISD::FSUB, VT, Expand);
803     setOperationAction(ISD::MUL , VT, Expand);
804     setOperationAction(ISD::FMUL, VT, Expand);
805     setOperationAction(ISD::SDIV, VT, Expand);
806     setOperationAction(ISD::UDIV, VT, Expand);
807     setOperationAction(ISD::FDIV, VT, Expand);
808     setOperationAction(ISD::SREM, VT, Expand);
809     setOperationAction(ISD::UREM, VT, Expand);
810     setOperationAction(ISD::LOAD, VT, Expand);
811     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
812     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
813     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
814     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
815     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
816     setOperationAction(ISD::FABS, VT, Expand);
817     setOperationAction(ISD::FSIN, VT, Expand);
818     setOperationAction(ISD::FSINCOS, VT, Expand);
819     setOperationAction(ISD::FCOS, VT, Expand);
820     setOperationAction(ISD::FSINCOS, VT, Expand);
821     setOperationAction(ISD::FREM, VT, Expand);
822     setOperationAction(ISD::FMA,  VT, Expand);
823     setOperationAction(ISD::FPOWI, VT, Expand);
824     setOperationAction(ISD::FSQRT, VT, Expand);
825     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
826     setOperationAction(ISD::FFLOOR, VT, Expand);
827     setOperationAction(ISD::FCEIL, VT, Expand);
828     setOperationAction(ISD::FTRUNC, VT, Expand);
829     setOperationAction(ISD::FRINT, VT, Expand);
830     setOperationAction(ISD::FNEARBYINT, VT, Expand);
831     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
832     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833     setOperationAction(ISD::SDIVREM, VT, Expand);
834     setOperationAction(ISD::UDIVREM, VT, Expand);
835     setOperationAction(ISD::FPOW, VT, Expand);
836     setOperationAction(ISD::CTPOP, VT, Expand);
837     setOperationAction(ISD::CTTZ, VT, Expand);
838     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
839     setOperationAction(ISD::CTLZ, VT, Expand);
840     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
841     setOperationAction(ISD::SHL, VT, Expand);
842     setOperationAction(ISD::SRA, VT, Expand);
843     setOperationAction(ISD::SRL, VT, Expand);
844     setOperationAction(ISD::ROTL, VT, Expand);
845     setOperationAction(ISD::ROTR, VT, Expand);
846     setOperationAction(ISD::BSWAP, VT, Expand);
847     setOperationAction(ISD::SETCC, VT, Expand);
848     setOperationAction(ISD::FLOG, VT, Expand);
849     setOperationAction(ISD::FLOG2, VT, Expand);
850     setOperationAction(ISD::FLOG10, VT, Expand);
851     setOperationAction(ISD::FEXP, VT, Expand);
852     setOperationAction(ISD::FEXP2, VT, Expand);
853     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
854     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
855     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
856     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
857     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
858     setOperationAction(ISD::TRUNCATE, VT, Expand);
859     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
860     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
861     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
862     setOperationAction(ISD::VSELECT, VT, Expand);
863     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
864              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
865       setTruncStoreAction(VT,
866                           (MVT::SimpleValueType)InnerVT, Expand);
867     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
868     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
869     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
870   }
871
872   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
873   // with -msoft-float, disable use of MMX as well.
874   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
875     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
876     // No operations on x86mmx supported, everything uses intrinsics.
877   }
878
879   // MMX-sized vectors (other than x86mmx) are expected to be expanded
880   // into smaller operations.
881   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
882   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
883   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
884   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
885   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
886   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
887   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
888   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
889   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
890   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
891   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
892   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
893   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
894   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
895   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
896   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
901   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
902   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
903   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
904   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
910
911   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
912     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
913
914     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
919     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
920     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
921     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
922     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
923     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
924     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
925     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
926   }
927
928   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
929     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
930
931     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
932     // registers cannot be used even for integer operations.
933     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
934     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
935     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
936     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
937
938     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
939     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
940     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
941     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
942     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
943     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
944     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
945     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
946     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
947     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
948     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
949     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
954     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
955     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
956
957     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
961
962     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
963     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
967
968     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
969     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
970       MVT VT = (MVT::SimpleValueType)i;
971       // Do not attempt to custom lower non-power-of-2 vectors
972       if (!isPowerOf2_32(VT.getVectorNumElements()))
973         continue;
974       // Do not attempt to custom lower non-128-bit vectors
975       if (!VT.is128BitVector())
976         continue;
977       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
978       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
979       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
980     }
981
982     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
983     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
984     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
985     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
987     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
988
989     if (Subtarget->is64Bit()) {
990       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
991       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
992     }
993
994     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
995     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
996       MVT VT = (MVT::SimpleValueType)i;
997
998       // Do not attempt to promote non-128-bit vectors
999       if (!VT.is128BitVector())
1000         continue;
1001
1002       setOperationAction(ISD::AND,    VT, Promote);
1003       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1004       setOperationAction(ISD::OR,     VT, Promote);
1005       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1006       setOperationAction(ISD::XOR,    VT, Promote);
1007       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1008       setOperationAction(ISD::LOAD,   VT, Promote);
1009       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1010       setOperationAction(ISD::SELECT, VT, Promote);
1011       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1012     }
1013
1014     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1015
1016     // Custom lower v2i64 and v2f64 selects.
1017     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1019     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1020     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1021
1022     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1023     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1024
1025     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1026     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1027     // As there is no 64-bit GPR available, we need build a special custom
1028     // sequence to convert from v2i32 to v2f32.
1029     if (!Subtarget->is64Bit())
1030       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1031
1032     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1033     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1034
1035     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1036   }
1037
1038   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1039     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1040     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1041     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1042     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1043     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1044     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1045     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1046     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1047     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1048     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1049
1050     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1051     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1052     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1053     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1054     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1055     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1056     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1057     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1058     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1059     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1060
1061     // FIXME: Do we need to handle scalar-to-vector here?
1062     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1063
1064     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1068     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1069
1070     // i8 and i16 vectors are custom , because the source register and source
1071     // source memory operand types are not the same width.  f32 vectors are
1072     // custom since the immediate controlling the insert encodes additional
1073     // information.
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1077     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1078
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1082     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1083
1084     // FIXME: these should be Legal but thats only for the case where
1085     // the index is constant.  For now custom expand to deal with that.
1086     if (Subtarget->is64Bit()) {
1087       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1088       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1089     }
1090   }
1091
1092   if (Subtarget->hasSSE2()) {
1093     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1101
1102     // In the customized shift lowering, the legal cases in AVX2 will be
1103     // recognized.
1104     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1105     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1106
1107     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1108     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1109
1110     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1111
1112     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1113     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1114   }
1115
1116   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1117     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1118     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1119     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1120     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1122     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1123
1124     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1125     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1126     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1127
1128     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1132     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1133     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1134     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1135     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1136     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1137     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1138     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1139     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1140
1141     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1145     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1146     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1147     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1148     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1149     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1150     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1151     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1152     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1153
1154     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1155
1156     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1157     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1158     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1159     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1160
1161     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1162     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1163
1164     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1165
1166     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1167     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1168
1169     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1176
1177     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1178     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1181
1182     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1183     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1184     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1185
1186     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1187     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1190
1191     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1194     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1197     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1200     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1202     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1203
1204     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1205       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1206       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1208       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1209       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1210       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1211     }
1212
1213     if (Subtarget->hasInt256()) {
1214       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1215       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1217       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1218
1219       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1220       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1222       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1223
1224       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1225       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1226       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1227       // Don't lower v32i8 because there is no 128-bit byte mul
1228
1229       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1230
1231       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1232     } else {
1233       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1234       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1235       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1236       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1237
1238       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1239       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1240       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1241       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1242
1243       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1244       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1245       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1246       // Don't lower v32i8 because there is no 128-bit byte mul
1247     }
1248
1249     // In the customized shift lowering, the legal cases in AVX2 will be
1250     // recognized.
1251     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1253
1254     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1255     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1256
1257     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1258
1259     // Custom lower several nodes for 256-bit types.
1260     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1261              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1262       MVT VT = (MVT::SimpleValueType)i;
1263
1264       // Extract subvector is special because the value type
1265       // (result) is 128-bit but the source is 256-bit wide.
1266       if (VT.is128BitVector())
1267         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1268
1269       // Do not attempt to custom lower other non-256-bit vectors
1270       if (!VT.is256BitVector())
1271         continue;
1272
1273       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1274       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1275       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1276       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1277       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1278       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1279       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1280     }
1281
1282     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284       MVT VT = (MVT::SimpleValueType)i;
1285
1286       // Do not attempt to promote non-256-bit vectors
1287       if (!VT.is256BitVector())
1288         continue;
1289
1290       setOperationAction(ISD::AND,    VT, Promote);
1291       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1292       setOperationAction(ISD::OR,     VT, Promote);
1293       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1294       setOperationAction(ISD::XOR,    VT, Promote);
1295       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1296       setOperationAction(ISD::LOAD,   VT, Promote);
1297       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1298       setOperationAction(ISD::SELECT, VT, Promote);
1299       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300     }
1301   }
1302
1303   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1304     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1308
1309     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1310     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1311     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1312
1313     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1314     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1315     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1316     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1317     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1322
1323     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1324     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1328     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1329
1330     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1331     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1335     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1336     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1337     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1338     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1339
1340     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1341     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1344     if (Subtarget->is64Bit()) {
1345       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1346       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1347       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1348       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1349     }
1350     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1351     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1352     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1353     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1356     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1357     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1358
1359     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1360     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1361     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1362     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1363     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1364     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1365     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1366     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1367     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1368     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1369     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1370     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1371
1372     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1373     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1374     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1375     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1376     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1377     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1378
1379     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1380     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1381
1382     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1383
1384     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1385     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1386     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1387     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1388     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1389     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1390     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1391
1392     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1393     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1394
1395     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1396     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1397
1398     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1399
1400     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1401     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1402
1403     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1404     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1405
1406     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1407     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1408
1409     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1410     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1411     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1412     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1413     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1414     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1415
1416     // Custom lower several nodes.
1417     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1418              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1419       MVT VT = (MVT::SimpleValueType)i;
1420
1421       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1422       // Extract subvector is special because the value type
1423       // (result) is 256/128-bit but the source is 512-bit wide.
1424       if (VT.is128BitVector() || VT.is256BitVector())
1425         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1426
1427       if (VT.getVectorElementType() == MVT::i1)
1428         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1429
1430       // Do not attempt to custom lower other non-512-bit vectors
1431       if (!VT.is512BitVector())
1432         continue;
1433
1434       if ( EltSize >= 32) {
1435         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1436         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1437         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1438         setOperationAction(ISD::VSELECT,             VT, Legal);
1439         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1440         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1441         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1442       }
1443     }
1444     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1445       MVT VT = (MVT::SimpleValueType)i;
1446
1447       // Do not attempt to promote non-256-bit vectors
1448       if (!VT.is512BitVector())
1449         continue;
1450
1451       setOperationAction(ISD::SELECT, VT, Promote);
1452       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1453     }
1454   }// has  AVX-512
1455
1456   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1457   // of this type with custom code.
1458   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1459            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1460     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1461                        Custom);
1462   }
1463
1464   // We want to custom lower some of our intrinsics.
1465   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1466   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1467   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1468
1469   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1470   // handle type legalization for these operations here.
1471   //
1472   // FIXME: We really should do custom legalization for addition and
1473   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1474   // than generic legalization for 64-bit multiplication-with-overflow, though.
1475   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1476     // Add/Sub/Mul with overflow operations are custom lowered.
1477     MVT VT = IntVTs[i];
1478     setOperationAction(ISD::SADDO, VT, Custom);
1479     setOperationAction(ISD::UADDO, VT, Custom);
1480     setOperationAction(ISD::SSUBO, VT, Custom);
1481     setOperationAction(ISD::USUBO, VT, Custom);
1482     setOperationAction(ISD::SMULO, VT, Custom);
1483     setOperationAction(ISD::UMULO, VT, Custom);
1484   }
1485
1486   // There are no 8-bit 3-address imul/mul instructions
1487   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1488   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1489
1490   if (!Subtarget->is64Bit()) {
1491     // These libcalls are not available in 32-bit.
1492     setLibcallName(RTLIB::SHL_I128, 0);
1493     setLibcallName(RTLIB::SRL_I128, 0);
1494     setLibcallName(RTLIB::SRA_I128, 0);
1495   }
1496
1497   // Combine sin / cos into one node or libcall if possible.
1498   if (Subtarget->hasSinCos()) {
1499     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1500     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1501     if (Subtarget->isTargetDarwin()) {
1502       // For MacOSX, we don't want to the normal expansion of a libcall to
1503       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1504       // traffic.
1505       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1506       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1507     }
1508   }
1509
1510   // We have target-specific dag combine patterns for the following nodes:
1511   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1512   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1513   setTargetDAGCombine(ISD::VSELECT);
1514   setTargetDAGCombine(ISD::SELECT);
1515   setTargetDAGCombine(ISD::SHL);
1516   setTargetDAGCombine(ISD::SRA);
1517   setTargetDAGCombine(ISD::SRL);
1518   setTargetDAGCombine(ISD::OR);
1519   setTargetDAGCombine(ISD::AND);
1520   setTargetDAGCombine(ISD::ADD);
1521   setTargetDAGCombine(ISD::FADD);
1522   setTargetDAGCombine(ISD::FSUB);
1523   setTargetDAGCombine(ISD::FMA);
1524   setTargetDAGCombine(ISD::SUB);
1525   setTargetDAGCombine(ISD::LOAD);
1526   setTargetDAGCombine(ISD::STORE);
1527   setTargetDAGCombine(ISD::ZERO_EXTEND);
1528   setTargetDAGCombine(ISD::ANY_EXTEND);
1529   setTargetDAGCombine(ISD::SIGN_EXTEND);
1530   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1531   setTargetDAGCombine(ISD::TRUNCATE);
1532   setTargetDAGCombine(ISD::SINT_TO_FP);
1533   setTargetDAGCombine(ISD::SETCC);
1534   if (Subtarget->is64Bit())
1535     setTargetDAGCombine(ISD::MUL);
1536   setTargetDAGCombine(ISD::XOR);
1537
1538   computeRegisterProperties();
1539
1540   // On Darwin, -Os means optimize for size without hurting performance,
1541   // do not reduce the limit.
1542   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1543   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1544   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1545   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1546   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1547   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1548   setPrefLoopAlignment(4); // 2^4 bytes.
1549
1550   // Predictable cmov don't hurt on atom because it's in-order.
1551   PredictableSelectIsExpensive = !Subtarget->isAtom();
1552
1553   setPrefFunctionAlignment(4); // 2^4 bytes.
1554 }
1555
1556 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1557   if (!VT.isVector())
1558     return MVT::i8;
1559
1560   const TargetMachine &TM = getTargetMachine();
1561   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512())
1562     switch(VT.getVectorNumElements()) {
1563     case  8: return MVT::v8i1;
1564     case 16: return MVT::v16i1;
1565     }
1566
1567   return VT.changeVectorElementTypeToInteger();
1568 }
1569
1570 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1571 /// the desired ByVal argument alignment.
1572 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1573   if (MaxAlign == 16)
1574     return;
1575   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1576     if (VTy->getBitWidth() == 128)
1577       MaxAlign = 16;
1578   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1579     unsigned EltAlign = 0;
1580     getMaxByValAlign(ATy->getElementType(), EltAlign);
1581     if (EltAlign > MaxAlign)
1582       MaxAlign = EltAlign;
1583   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1584     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1585       unsigned EltAlign = 0;
1586       getMaxByValAlign(STy->getElementType(i), EltAlign);
1587       if (EltAlign > MaxAlign)
1588         MaxAlign = EltAlign;
1589       if (MaxAlign == 16)
1590         break;
1591     }
1592   }
1593 }
1594
1595 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1596 /// function arguments in the caller parameter area. For X86, aggregates
1597 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1598 /// are at 4-byte boundaries.
1599 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1600   if (Subtarget->is64Bit()) {
1601     // Max of 8 and alignment of type.
1602     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1603     if (TyAlign > 8)
1604       return TyAlign;
1605     return 8;
1606   }
1607
1608   unsigned Align = 4;
1609   if (Subtarget->hasSSE1())
1610     getMaxByValAlign(Ty, Align);
1611   return Align;
1612 }
1613
1614 /// getOptimalMemOpType - Returns the target specific optimal type for load
1615 /// and store operations as a result of memset, memcpy, and memmove
1616 /// lowering. If DstAlign is zero that means it's safe to destination
1617 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1618 /// means there isn't a need to check it against alignment requirement,
1619 /// probably because the source does not need to be loaded. If 'IsMemset' is
1620 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1621 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1622 /// source is constant so it does not need to be loaded.
1623 /// It returns EVT::Other if the type should be determined using generic
1624 /// target-independent logic.
1625 EVT
1626 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1627                                        unsigned DstAlign, unsigned SrcAlign,
1628                                        bool IsMemset, bool ZeroMemset,
1629                                        bool MemcpyStrSrc,
1630                                        MachineFunction &MF) const {
1631   const Function *F = MF.getFunction();
1632   if ((!IsMemset || ZeroMemset) &&
1633       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1634                                        Attribute::NoImplicitFloat)) {
1635     if (Size >= 16 &&
1636         (Subtarget->isUnalignedMemAccessFast() ||
1637          ((DstAlign == 0 || DstAlign >= 16) &&
1638           (SrcAlign == 0 || SrcAlign >= 16)))) {
1639       if (Size >= 32) {
1640         if (Subtarget->hasInt256())
1641           return MVT::v8i32;
1642         if (Subtarget->hasFp256())
1643           return MVT::v8f32;
1644       }
1645       if (Subtarget->hasSSE2())
1646         return MVT::v4i32;
1647       if (Subtarget->hasSSE1())
1648         return MVT::v4f32;
1649     } else if (!MemcpyStrSrc && Size >= 8 &&
1650                !Subtarget->is64Bit() &&
1651                Subtarget->hasSSE2()) {
1652       // Do not use f64 to lower memcpy if source is string constant. It's
1653       // better to use i32 to avoid the loads.
1654       return MVT::f64;
1655     }
1656   }
1657   if (Subtarget->is64Bit() && Size >= 8)
1658     return MVT::i64;
1659   return MVT::i32;
1660 }
1661
1662 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1663   if (VT == MVT::f32)
1664     return X86ScalarSSEf32;
1665   else if (VT == MVT::f64)
1666     return X86ScalarSSEf64;
1667   return true;
1668 }
1669
1670 bool
1671 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1672   if (Fast)
1673     *Fast = Subtarget->isUnalignedMemAccessFast();
1674   return true;
1675 }
1676
1677 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1678 /// current function.  The returned value is a member of the
1679 /// MachineJumpTableInfo::JTEntryKind enum.
1680 unsigned X86TargetLowering::getJumpTableEncoding() const {
1681   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1682   // symbol.
1683   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1684       Subtarget->isPICStyleGOT())
1685     return MachineJumpTableInfo::EK_Custom32;
1686
1687   // Otherwise, use the normal jump table encoding heuristics.
1688   return TargetLowering::getJumpTableEncoding();
1689 }
1690
1691 const MCExpr *
1692 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1693                                              const MachineBasicBlock *MBB,
1694                                              unsigned uid,MCContext &Ctx) const{
1695   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1696          Subtarget->isPICStyleGOT());
1697   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1698   // entries.
1699   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1700                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1701 }
1702
1703 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1704 /// jumptable.
1705 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1706                                                     SelectionDAG &DAG) const {
1707   if (!Subtarget->is64Bit())
1708     // This doesn't have SDLoc associated with it, but is not really the
1709     // same as a Register.
1710     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1711   return Table;
1712 }
1713
1714 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1715 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1716 /// MCExpr.
1717 const MCExpr *X86TargetLowering::
1718 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1719                              MCContext &Ctx) const {
1720   // X86-64 uses RIP relative addressing based on the jump table label.
1721   if (Subtarget->isPICStyleRIPRel())
1722     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1723
1724   // Otherwise, the reference is relative to the PIC base.
1725   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1726 }
1727
1728 // FIXME: Why this routine is here? Move to RegInfo!
1729 std::pair<const TargetRegisterClass*, uint8_t>
1730 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1731   const TargetRegisterClass *RRC = 0;
1732   uint8_t Cost = 1;
1733   switch (VT.SimpleTy) {
1734   default:
1735     return TargetLowering::findRepresentativeClass(VT);
1736   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1737     RRC = Subtarget->is64Bit() ?
1738       (const TargetRegisterClass*)&X86::GR64RegClass :
1739       (const TargetRegisterClass*)&X86::GR32RegClass;
1740     break;
1741   case MVT::x86mmx:
1742     RRC = &X86::VR64RegClass;
1743     break;
1744   case MVT::f32: case MVT::f64:
1745   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1746   case MVT::v4f32: case MVT::v2f64:
1747   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1748   case MVT::v4f64:
1749     RRC = &X86::VR128RegClass;
1750     break;
1751   }
1752   return std::make_pair(RRC, Cost);
1753 }
1754
1755 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1756                                                unsigned &Offset) const {
1757   if (!Subtarget->isTargetLinux())
1758     return false;
1759
1760   if (Subtarget->is64Bit()) {
1761     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1762     Offset = 0x28;
1763     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1764       AddressSpace = 256;
1765     else
1766       AddressSpace = 257;
1767   } else {
1768     // %gs:0x14 on i386
1769     Offset = 0x14;
1770     AddressSpace = 256;
1771   }
1772   return true;
1773 }
1774
1775 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1776                                             unsigned DestAS) const {
1777   assert(SrcAS != DestAS && "Expected different address spaces!");
1778
1779   return SrcAS < 256 && DestAS < 256;
1780 }
1781
1782 //===----------------------------------------------------------------------===//
1783 //               Return Value Calling Convention Implementation
1784 //===----------------------------------------------------------------------===//
1785
1786 #include "X86GenCallingConv.inc"
1787
1788 bool
1789 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1790                                   MachineFunction &MF, bool isVarArg,
1791                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1792                         LLVMContext &Context) const {
1793   SmallVector<CCValAssign, 16> RVLocs;
1794   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1795                  RVLocs, Context);
1796   return CCInfo.CheckReturn(Outs, RetCC_X86);
1797 }
1798
1799 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1800   static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1801   return ScratchRegs;
1802 }
1803
1804 SDValue
1805 X86TargetLowering::LowerReturn(SDValue Chain,
1806                                CallingConv::ID CallConv, bool isVarArg,
1807                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1808                                const SmallVectorImpl<SDValue> &OutVals,
1809                                SDLoc dl, SelectionDAG &DAG) const {
1810   MachineFunction &MF = DAG.getMachineFunction();
1811   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1812
1813   SmallVector<CCValAssign, 16> RVLocs;
1814   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1815                  RVLocs, *DAG.getContext());
1816   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1817
1818   SDValue Flag;
1819   SmallVector<SDValue, 6> RetOps;
1820   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1821   // Operand #1 = Bytes To Pop
1822   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1823                    MVT::i16));
1824
1825   // Copy the result values into the output registers.
1826   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1827     CCValAssign &VA = RVLocs[i];
1828     assert(VA.isRegLoc() && "Can only return in registers!");
1829     SDValue ValToCopy = OutVals[i];
1830     EVT ValVT = ValToCopy.getValueType();
1831
1832     // Promote values to the appropriate types
1833     if (VA.getLocInfo() == CCValAssign::SExt)
1834       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1835     else if (VA.getLocInfo() == CCValAssign::ZExt)
1836       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1837     else if (VA.getLocInfo() == CCValAssign::AExt)
1838       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1839     else if (VA.getLocInfo() == CCValAssign::BCvt)
1840       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1841
1842     // If this is x86-64, and we disabled SSE, we can't return FP values,
1843     // or SSE or MMX vectors.
1844     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1845          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1846           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1847       report_fatal_error("SSE register return with SSE disabled");
1848     }
1849     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1850     // llvm-gcc has never done it right and no one has noticed, so this
1851     // should be OK for now.
1852     if (ValVT == MVT::f64 &&
1853         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1854       report_fatal_error("SSE2 register return with SSE2 disabled");
1855
1856     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1857     // the RET instruction and handled by the FP Stackifier.
1858     if (VA.getLocReg() == X86::ST0 ||
1859         VA.getLocReg() == X86::ST1) {
1860       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1861       // change the value to the FP stack register class.
1862       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1863         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1864       RetOps.push_back(ValToCopy);
1865       // Don't emit a copytoreg.
1866       continue;
1867     }
1868
1869     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1870     // which is returned in RAX / RDX.
1871     if (Subtarget->is64Bit()) {
1872       if (ValVT == MVT::x86mmx) {
1873         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1874           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1875           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1876                                   ValToCopy);
1877           // If we don't have SSE2 available, convert to v4f32 so the generated
1878           // register is legal.
1879           if (!Subtarget->hasSSE2())
1880             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1881         }
1882       }
1883     }
1884
1885     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1886     Flag = Chain.getValue(1);
1887     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1888   }
1889
1890   // The x86-64 ABIs require that for returning structs by value we copy
1891   // the sret argument into %rax/%eax (depending on ABI) for the return.
1892   // Win32 requires us to put the sret argument to %eax as well.
1893   // We saved the argument into a virtual register in the entry block,
1894   // so now we copy the value out and into %rax/%eax.
1895   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1896       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1897     MachineFunction &MF = DAG.getMachineFunction();
1898     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1899     unsigned Reg = FuncInfo->getSRetReturnReg();
1900     assert(Reg &&
1901            "SRetReturnReg should have been set in LowerFormalArguments().");
1902     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1903
1904     unsigned RetValReg
1905         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1906           X86::RAX : X86::EAX;
1907     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1908     Flag = Chain.getValue(1);
1909
1910     // RAX/EAX now acts like a return value.
1911     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1912   }
1913
1914   RetOps[0] = Chain;  // Update chain.
1915
1916   // Add the flag if we have it.
1917   if (Flag.getNode())
1918     RetOps.push_back(Flag);
1919
1920   return DAG.getNode(X86ISD::RET_FLAG, dl,
1921                      MVT::Other, &RetOps[0], RetOps.size());
1922 }
1923
1924 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1925   if (N->getNumValues() != 1)
1926     return false;
1927   if (!N->hasNUsesOfValue(1, 0))
1928     return false;
1929
1930   SDValue TCChain = Chain;
1931   SDNode *Copy = *N->use_begin();
1932   if (Copy->getOpcode() == ISD::CopyToReg) {
1933     // If the copy has a glue operand, we conservatively assume it isn't safe to
1934     // perform a tail call.
1935     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1936       return false;
1937     TCChain = Copy->getOperand(0);
1938   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1939     return false;
1940
1941   bool HasRet = false;
1942   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1943        UI != UE; ++UI) {
1944     if (UI->getOpcode() != X86ISD::RET_FLAG)
1945       return false;
1946     HasRet = true;
1947   }
1948
1949   if (!HasRet)
1950     return false;
1951
1952   Chain = TCChain;
1953   return true;
1954 }
1955
1956 MVT
1957 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1958                                             ISD::NodeType ExtendKind) const {
1959   MVT ReturnMVT;
1960   // TODO: Is this also valid on 32-bit?
1961   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1962     ReturnMVT = MVT::i8;
1963   else
1964     ReturnMVT = MVT::i32;
1965
1966   MVT MinVT = getRegisterType(ReturnMVT);
1967   return VT.bitsLT(MinVT) ? MinVT : VT;
1968 }
1969
1970 /// LowerCallResult - Lower the result values of a call into the
1971 /// appropriate copies out of appropriate physical registers.
1972 ///
1973 SDValue
1974 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1975                                    CallingConv::ID CallConv, bool isVarArg,
1976                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1977                                    SDLoc dl, SelectionDAG &DAG,
1978                                    SmallVectorImpl<SDValue> &InVals) const {
1979
1980   // Assign locations to each value returned by this call.
1981   SmallVector<CCValAssign, 16> RVLocs;
1982   bool Is64Bit = Subtarget->is64Bit();
1983   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1984                  getTargetMachine(), RVLocs, *DAG.getContext());
1985   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1986
1987   // Copy all of the result registers out of their specified physreg.
1988   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1989     CCValAssign &VA = RVLocs[i];
1990     EVT CopyVT = VA.getValVT();
1991
1992     // If this is x86-64, and we disabled SSE, we can't return FP values
1993     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1994         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1995       report_fatal_error("SSE register return with SSE disabled");
1996     }
1997
1998     SDValue Val;
1999
2000     // If this is a call to a function that returns an fp value on the floating
2001     // point stack, we must guarantee the value is popped from the stack, so
2002     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2003     // if the return value is not used. We use the FpPOP_RETVAL instruction
2004     // instead.
2005     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2006       // If we prefer to use the value in xmm registers, copy it out as f80 and
2007       // use a truncate to move it from fp stack reg to xmm reg.
2008       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2009       SDValue Ops[] = { Chain, InFlag };
2010       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2011                                          MVT::Other, MVT::Glue, Ops), 1);
2012       Val = Chain.getValue(0);
2013
2014       // Round the f80 to the right size, which also moves it to the appropriate
2015       // xmm register.
2016       if (CopyVT != VA.getValVT())
2017         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2018                           // This truncation won't change the value.
2019                           DAG.getIntPtrConstant(1));
2020     } else {
2021       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2022                                  CopyVT, InFlag).getValue(1);
2023       Val = Chain.getValue(0);
2024     }
2025     InFlag = Chain.getValue(2);
2026     InVals.push_back(Val);
2027   }
2028
2029   return Chain;
2030 }
2031
2032 //===----------------------------------------------------------------------===//
2033 //                C & StdCall & Fast Calling Convention implementation
2034 //===----------------------------------------------------------------------===//
2035 //  StdCall calling convention seems to be standard for many Windows' API
2036 //  routines and around. It differs from C calling convention just a little:
2037 //  callee should clean up the stack, not caller. Symbols should be also
2038 //  decorated in some fancy way :) It doesn't support any vector arguments.
2039 //  For info on fast calling convention see Fast Calling Convention (tail call)
2040 //  implementation LowerX86_32FastCCCallTo.
2041
2042 /// CallIsStructReturn - Determines whether a call uses struct return
2043 /// semantics.
2044 enum StructReturnType {
2045   NotStructReturn,
2046   RegStructReturn,
2047   StackStructReturn
2048 };
2049 static StructReturnType
2050 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2051   if (Outs.empty())
2052     return NotStructReturn;
2053
2054   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2055   if (!Flags.isSRet())
2056     return NotStructReturn;
2057   if (Flags.isInReg())
2058     return RegStructReturn;
2059   return StackStructReturn;
2060 }
2061
2062 /// ArgsAreStructReturn - Determines whether a function uses struct
2063 /// return semantics.
2064 static StructReturnType
2065 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2066   if (Ins.empty())
2067     return NotStructReturn;
2068
2069   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2070   if (!Flags.isSRet())
2071     return NotStructReturn;
2072   if (Flags.isInReg())
2073     return RegStructReturn;
2074   return StackStructReturn;
2075 }
2076
2077 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2078 /// by "Src" to address "Dst" with size and alignment information specified by
2079 /// the specific parameter attribute. The copy will be passed as a byval
2080 /// function parameter.
2081 static SDValue
2082 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2083                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2084                           SDLoc dl) {
2085   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2086
2087   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2088                        /*isVolatile*/false, /*AlwaysInline=*/true,
2089                        MachinePointerInfo(), MachinePointerInfo());
2090 }
2091
2092 /// IsTailCallConvention - Return true if the calling convention is one that
2093 /// supports tail call optimization.
2094 static bool IsTailCallConvention(CallingConv::ID CC) {
2095   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2096           CC == CallingConv::HiPE);
2097 }
2098
2099 /// \brief Return true if the calling convention is a C calling convention.
2100 static bool IsCCallConvention(CallingConv::ID CC) {
2101   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2102           CC == CallingConv::X86_64_SysV);
2103 }
2104
2105 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2106   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2107     return false;
2108
2109   CallSite CS(CI);
2110   CallingConv::ID CalleeCC = CS.getCallingConv();
2111   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2112     return false;
2113
2114   return true;
2115 }
2116
2117 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2118 /// a tailcall target by changing its ABI.
2119 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2120                                    bool GuaranteedTailCallOpt) {
2121   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2122 }
2123
2124 SDValue
2125 X86TargetLowering::LowerMemArgument(SDValue Chain,
2126                                     CallingConv::ID CallConv,
2127                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2128                                     SDLoc dl, SelectionDAG &DAG,
2129                                     const CCValAssign &VA,
2130                                     MachineFrameInfo *MFI,
2131                                     unsigned i) const {
2132   // Create the nodes corresponding to a load from this parameter slot.
2133   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2134   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2135                               getTargetMachine().Options.GuaranteedTailCallOpt);
2136   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2137   EVT ValVT;
2138
2139   // If value is passed by pointer we have address passed instead of the value
2140   // itself.
2141   if (VA.getLocInfo() == CCValAssign::Indirect)
2142     ValVT = VA.getLocVT();
2143   else
2144     ValVT = VA.getValVT();
2145
2146   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2147   // changed with more analysis.
2148   // In case of tail call optimization mark all arguments mutable. Since they
2149   // could be overwritten by lowering of arguments in case of a tail call.
2150   if (Flags.isByVal()) {
2151     unsigned Bytes = Flags.getByValSize();
2152     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2153     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2154     return DAG.getFrameIndex(FI, getPointerTy());
2155   } else {
2156     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2157                                     VA.getLocMemOffset(), isImmutable);
2158     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2159     return DAG.getLoad(ValVT, dl, Chain, FIN,
2160                        MachinePointerInfo::getFixedStack(FI),
2161                        false, false, false, 0);
2162   }
2163 }
2164
2165 SDValue
2166 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2167                                         CallingConv::ID CallConv,
2168                                         bool isVarArg,
2169                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2170                                         SDLoc dl,
2171                                         SelectionDAG &DAG,
2172                                         SmallVectorImpl<SDValue> &InVals)
2173                                           const {
2174   MachineFunction &MF = DAG.getMachineFunction();
2175   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2176
2177   const Function* Fn = MF.getFunction();
2178   if (Fn->hasExternalLinkage() &&
2179       Subtarget->isTargetCygMing() &&
2180       Fn->getName() == "main")
2181     FuncInfo->setForceFramePointer(true);
2182
2183   MachineFrameInfo *MFI = MF.getFrameInfo();
2184   bool Is64Bit = Subtarget->is64Bit();
2185   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2186
2187   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2188          "Var args not supported with calling convention fastcc, ghc or hipe");
2189
2190   // Assign locations to all of the incoming arguments.
2191   SmallVector<CCValAssign, 16> ArgLocs;
2192   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2193                  ArgLocs, *DAG.getContext());
2194
2195   // Allocate shadow area for Win64
2196   if (IsWin64)
2197     CCInfo.AllocateStack(32, 8);
2198
2199   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2200
2201   unsigned LastVal = ~0U;
2202   SDValue ArgValue;
2203   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2204     CCValAssign &VA = ArgLocs[i];
2205     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2206     // places.
2207     assert(VA.getValNo() != LastVal &&
2208            "Don't support value assigned to multiple locs yet");
2209     (void)LastVal;
2210     LastVal = VA.getValNo();
2211
2212     if (VA.isRegLoc()) {
2213       EVT RegVT = VA.getLocVT();
2214       const TargetRegisterClass *RC;
2215       if (RegVT == MVT::i32)
2216         RC = &X86::GR32RegClass;
2217       else if (Is64Bit && RegVT == MVT::i64)
2218         RC = &X86::GR64RegClass;
2219       else if (RegVT == MVT::f32)
2220         RC = &X86::FR32RegClass;
2221       else if (RegVT == MVT::f64)
2222         RC = &X86::FR64RegClass;
2223       else if (RegVT.is512BitVector())
2224         RC = &X86::VR512RegClass;
2225       else if (RegVT.is256BitVector())
2226         RC = &X86::VR256RegClass;
2227       else if (RegVT.is128BitVector())
2228         RC = &X86::VR128RegClass;
2229       else if (RegVT == MVT::x86mmx)
2230         RC = &X86::VR64RegClass;
2231       else if (RegVT == MVT::i1)
2232         RC = &X86::VK1RegClass;
2233       else if (RegVT == MVT::v8i1)
2234         RC = &X86::VK8RegClass;
2235       else if (RegVT == MVT::v16i1)
2236         RC = &X86::VK16RegClass;
2237       else
2238         llvm_unreachable("Unknown argument type!");
2239
2240       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2241       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2242
2243       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2244       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2245       // right size.
2246       if (VA.getLocInfo() == CCValAssign::SExt)
2247         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2248                                DAG.getValueType(VA.getValVT()));
2249       else if (VA.getLocInfo() == CCValAssign::ZExt)
2250         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2251                                DAG.getValueType(VA.getValVT()));
2252       else if (VA.getLocInfo() == CCValAssign::BCvt)
2253         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2254
2255       if (VA.isExtInLoc()) {
2256         // Handle MMX values passed in XMM regs.
2257         if (RegVT.isVector())
2258           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2259         else
2260           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2261       }
2262     } else {
2263       assert(VA.isMemLoc());
2264       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2265     }
2266
2267     // If value is passed via pointer - do a load.
2268     if (VA.getLocInfo() == CCValAssign::Indirect)
2269       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2270                              MachinePointerInfo(), false, false, false, 0);
2271
2272     InVals.push_back(ArgValue);
2273   }
2274
2275   // The x86-64 ABIs require that for returning structs by value we copy
2276   // the sret argument into %rax/%eax (depending on ABI) for the return.
2277   // Win32 requires us to put the sret argument to %eax as well.
2278   // Save the argument into a virtual register so that we can access it
2279   // from the return points.
2280   if (MF.getFunction()->hasStructRetAttr() &&
2281       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2282     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2283     unsigned Reg = FuncInfo->getSRetReturnReg();
2284     if (!Reg) {
2285       MVT PtrTy = getPointerTy();
2286       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2287       FuncInfo->setSRetReturnReg(Reg);
2288     }
2289     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2290     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2291   }
2292
2293   unsigned StackSize = CCInfo.getNextStackOffset();
2294   // Align stack specially for tail calls.
2295   if (FuncIsMadeTailCallSafe(CallConv,
2296                              MF.getTarget().Options.GuaranteedTailCallOpt))
2297     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2298
2299   // If the function takes variable number of arguments, make a frame index for
2300   // the start of the first vararg value... for expansion of llvm.va_start.
2301   if (isVarArg) {
2302     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2303                     CallConv != CallingConv::X86_ThisCall)) {
2304       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2305     }
2306     if (Is64Bit) {
2307       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2308
2309       // FIXME: We should really autogenerate these arrays
2310       static const uint16_t GPR64ArgRegsWin64[] = {
2311         X86::RCX, X86::RDX, X86::R8,  X86::R9
2312       };
2313       static const uint16_t GPR64ArgRegs64Bit[] = {
2314         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2315       };
2316       static const uint16_t XMMArgRegs64Bit[] = {
2317         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2318         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2319       };
2320       const uint16_t *GPR64ArgRegs;
2321       unsigned NumXMMRegs = 0;
2322
2323       if (IsWin64) {
2324         // The XMM registers which might contain var arg parameters are shadowed
2325         // in their paired GPR.  So we only need to save the GPR to their home
2326         // slots.
2327         TotalNumIntRegs = 4;
2328         GPR64ArgRegs = GPR64ArgRegsWin64;
2329       } else {
2330         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2331         GPR64ArgRegs = GPR64ArgRegs64Bit;
2332
2333         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2334                                                 TotalNumXMMRegs);
2335       }
2336       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2337                                                        TotalNumIntRegs);
2338
2339       bool NoImplicitFloatOps = Fn->getAttributes().
2340         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2341       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2342              "SSE register cannot be used when SSE is disabled!");
2343       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2344                NoImplicitFloatOps) &&
2345              "SSE register cannot be used when SSE is disabled!");
2346       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2347           !Subtarget->hasSSE1())
2348         // Kernel mode asks for SSE to be disabled, so don't push them
2349         // on the stack.
2350         TotalNumXMMRegs = 0;
2351
2352       if (IsWin64) {
2353         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2354         // Get to the caller-allocated home save location.  Add 8 to account
2355         // for the return address.
2356         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2357         FuncInfo->setRegSaveFrameIndex(
2358           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2359         // Fixup to set vararg frame on shadow area (4 x i64).
2360         if (NumIntRegs < 4)
2361           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2362       } else {
2363         // For X86-64, if there are vararg parameters that are passed via
2364         // registers, then we must store them to their spots on the stack so
2365         // they may be loaded by deferencing the result of va_next.
2366         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2367         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2368         FuncInfo->setRegSaveFrameIndex(
2369           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2370                                false));
2371       }
2372
2373       // Store the integer parameter registers.
2374       SmallVector<SDValue, 8> MemOps;
2375       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2376                                         getPointerTy());
2377       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2378       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2379         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2380                                   DAG.getIntPtrConstant(Offset));
2381         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2382                                      &X86::GR64RegClass);
2383         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2384         SDValue Store =
2385           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2386                        MachinePointerInfo::getFixedStack(
2387                          FuncInfo->getRegSaveFrameIndex(), Offset),
2388                        false, false, 0);
2389         MemOps.push_back(Store);
2390         Offset += 8;
2391       }
2392
2393       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2394         // Now store the XMM (fp + vector) parameter registers.
2395         SmallVector<SDValue, 11> SaveXMMOps;
2396         SaveXMMOps.push_back(Chain);
2397
2398         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2399         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2400         SaveXMMOps.push_back(ALVal);
2401
2402         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2403                                FuncInfo->getRegSaveFrameIndex()));
2404         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2405                                FuncInfo->getVarArgsFPOffset()));
2406
2407         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2408           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2409                                        &X86::VR128RegClass);
2410           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2411           SaveXMMOps.push_back(Val);
2412         }
2413         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2414                                      MVT::Other,
2415                                      &SaveXMMOps[0], SaveXMMOps.size()));
2416       }
2417
2418       if (!MemOps.empty())
2419         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2420                             &MemOps[0], MemOps.size());
2421     }
2422   }
2423
2424   // Some CCs need callee pop.
2425   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2426                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2427     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2428   } else {
2429     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2430     // If this is an sret function, the return should pop the hidden pointer.
2431     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2432         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2433         argsAreStructReturn(Ins) == StackStructReturn)
2434       FuncInfo->setBytesToPopOnReturn(4);
2435   }
2436
2437   if (!Is64Bit) {
2438     // RegSaveFrameIndex is X86-64 only.
2439     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2440     if (CallConv == CallingConv::X86_FastCall ||
2441         CallConv == CallingConv::X86_ThisCall)
2442       // fastcc functions can't have varargs.
2443       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2444   }
2445
2446   FuncInfo->setArgumentStackSize(StackSize);
2447
2448   return Chain;
2449 }
2450
2451 SDValue
2452 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2453                                     SDValue StackPtr, SDValue Arg,
2454                                     SDLoc dl, SelectionDAG &DAG,
2455                                     const CCValAssign &VA,
2456                                     ISD::ArgFlagsTy Flags) const {
2457   unsigned LocMemOffset = VA.getLocMemOffset();
2458   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2459   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2460   if (Flags.isByVal())
2461     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2462
2463   return DAG.getStore(Chain, dl, Arg, PtrOff,
2464                       MachinePointerInfo::getStack(LocMemOffset),
2465                       false, false, 0);
2466 }
2467
2468 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2469 /// optimization is performed and it is required.
2470 SDValue
2471 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2472                                            SDValue &OutRetAddr, SDValue Chain,
2473                                            bool IsTailCall, bool Is64Bit,
2474                                            int FPDiff, SDLoc dl) const {
2475   // Adjust the Return address stack slot.
2476   EVT VT = getPointerTy();
2477   OutRetAddr = getReturnAddressFrameIndex(DAG);
2478
2479   // Load the "old" Return address.
2480   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2481                            false, false, false, 0);
2482   return SDValue(OutRetAddr.getNode(), 1);
2483 }
2484
2485 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2486 /// optimization is performed and it is required (FPDiff!=0).
2487 static SDValue
2488 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2489                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2490                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2491   // Store the return address to the appropriate stack slot.
2492   if (!FPDiff) return Chain;
2493   // Calculate the new stack slot for the return address.
2494   int NewReturnAddrFI =
2495     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2496                                          false);
2497   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2498   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2499                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2500                        false, false, 0);
2501   return Chain;
2502 }
2503
2504 SDValue
2505 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2506                              SmallVectorImpl<SDValue> &InVals) const {
2507   SelectionDAG &DAG                     = CLI.DAG;
2508   SDLoc &dl                             = CLI.DL;
2509   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2510   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2511   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2512   SDValue Chain                         = CLI.Chain;
2513   SDValue Callee                        = CLI.Callee;
2514   CallingConv::ID CallConv              = CLI.CallConv;
2515   bool &isTailCall                      = CLI.IsTailCall;
2516   bool isVarArg                         = CLI.IsVarArg;
2517
2518   MachineFunction &MF = DAG.getMachineFunction();
2519   bool Is64Bit        = Subtarget->is64Bit();
2520   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2521   StructReturnType SR = callIsStructReturn(Outs);
2522   bool IsSibcall      = false;
2523
2524   if (MF.getTarget().Options.DisableTailCalls)
2525     isTailCall = false;
2526
2527   if (isTailCall) {
2528     // Check if it's really possible to do a tail call.
2529     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2530                     isVarArg, SR != NotStructReturn,
2531                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2532                     Outs, OutVals, Ins, DAG);
2533
2534     // Sibcalls are automatically detected tailcalls which do not require
2535     // ABI changes.
2536     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2537       IsSibcall = true;
2538
2539     if (isTailCall)
2540       ++NumTailCalls;
2541   }
2542
2543   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2544          "Var args not supported with calling convention fastcc, ghc or hipe");
2545
2546   // Analyze operands of the call, assigning locations to each operand.
2547   SmallVector<CCValAssign, 16> ArgLocs;
2548   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2549                  ArgLocs, *DAG.getContext());
2550
2551   // Allocate shadow area for Win64
2552   if (IsWin64)
2553     CCInfo.AllocateStack(32, 8);
2554
2555   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2556
2557   // Get a count of how many bytes are to be pushed on the stack.
2558   unsigned NumBytes = CCInfo.getNextStackOffset();
2559   if (IsSibcall)
2560     // This is a sibcall. The memory operands are available in caller's
2561     // own caller's stack.
2562     NumBytes = 0;
2563   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2564            IsTailCallConvention(CallConv))
2565     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2566
2567   int FPDiff = 0;
2568   if (isTailCall && !IsSibcall) {
2569     // Lower arguments at fp - stackoffset + fpdiff.
2570     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2571     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2572
2573     FPDiff = NumBytesCallerPushed - NumBytes;
2574
2575     // Set the delta of movement of the returnaddr stackslot.
2576     // But only set if delta is greater than previous delta.
2577     if (FPDiff < X86Info->getTCReturnAddrDelta())
2578       X86Info->setTCReturnAddrDelta(FPDiff);
2579   }
2580
2581   if (!IsSibcall)
2582     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2583                                  dl);
2584
2585   SDValue RetAddrFrIdx;
2586   // Load return address for tail calls.
2587   if (isTailCall && FPDiff)
2588     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2589                                     Is64Bit, FPDiff, dl);
2590
2591   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2592   SmallVector<SDValue, 8> MemOpChains;
2593   SDValue StackPtr;
2594
2595   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2596   // of tail call optimization arguments are handle later.
2597   const X86RegisterInfo *RegInfo =
2598     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2599   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2600     CCValAssign &VA = ArgLocs[i];
2601     EVT RegVT = VA.getLocVT();
2602     SDValue Arg = OutVals[i];
2603     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2604     bool isByVal = Flags.isByVal();
2605
2606     // Promote the value if needed.
2607     switch (VA.getLocInfo()) {
2608     default: llvm_unreachable("Unknown loc info!");
2609     case CCValAssign::Full: break;
2610     case CCValAssign::SExt:
2611       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2612       break;
2613     case CCValAssign::ZExt:
2614       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2615       break;
2616     case CCValAssign::AExt:
2617       if (RegVT.is128BitVector()) {
2618         // Special case: passing MMX values in XMM registers.
2619         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2620         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2621         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2622       } else
2623         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2624       break;
2625     case CCValAssign::BCvt:
2626       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2627       break;
2628     case CCValAssign::Indirect: {
2629       // Store the argument.
2630       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2631       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2632       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2633                            MachinePointerInfo::getFixedStack(FI),
2634                            false, false, 0);
2635       Arg = SpillSlot;
2636       break;
2637     }
2638     }
2639
2640     if (VA.isRegLoc()) {
2641       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2642       if (isVarArg && IsWin64) {
2643         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2644         // shadow reg if callee is a varargs function.
2645         unsigned ShadowReg = 0;
2646         switch (VA.getLocReg()) {
2647         case X86::XMM0: ShadowReg = X86::RCX; break;
2648         case X86::XMM1: ShadowReg = X86::RDX; break;
2649         case X86::XMM2: ShadowReg = X86::R8; break;
2650         case X86::XMM3: ShadowReg = X86::R9; break;
2651         }
2652         if (ShadowReg)
2653           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2654       }
2655     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2656       assert(VA.isMemLoc());
2657       if (StackPtr.getNode() == 0)
2658         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2659                                       getPointerTy());
2660       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2661                                              dl, DAG, VA, Flags));
2662     }
2663   }
2664
2665   if (!MemOpChains.empty())
2666     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2667                         &MemOpChains[0], MemOpChains.size());
2668
2669   if (Subtarget->isPICStyleGOT()) {
2670     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2671     // GOT pointer.
2672     if (!isTailCall) {
2673       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2674                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2675     } else {
2676       // If we are tail calling and generating PIC/GOT style code load the
2677       // address of the callee into ECX. The value in ecx is used as target of
2678       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2679       // for tail calls on PIC/GOT architectures. Normally we would just put the
2680       // address of GOT into ebx and then call target@PLT. But for tail calls
2681       // ebx would be restored (since ebx is callee saved) before jumping to the
2682       // target@PLT.
2683
2684       // Note: The actual moving to ECX is done further down.
2685       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2686       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2687           !G->getGlobal()->hasProtectedVisibility())
2688         Callee = LowerGlobalAddress(Callee, DAG);
2689       else if (isa<ExternalSymbolSDNode>(Callee))
2690         Callee = LowerExternalSymbol(Callee, DAG);
2691     }
2692   }
2693
2694   if (Is64Bit && isVarArg && !IsWin64) {
2695     // From AMD64 ABI document:
2696     // For calls that may call functions that use varargs or stdargs
2697     // (prototype-less calls or calls to functions containing ellipsis (...) in
2698     // the declaration) %al is used as hidden argument to specify the number
2699     // of SSE registers used. The contents of %al do not need to match exactly
2700     // the number of registers, but must be an ubound on the number of SSE
2701     // registers used and is in the range 0 - 8 inclusive.
2702
2703     // Count the number of XMM registers allocated.
2704     static const uint16_t XMMArgRegs[] = {
2705       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2706       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2707     };
2708     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2709     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2710            && "SSE registers cannot be used when SSE is disabled");
2711
2712     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2713                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2714   }
2715
2716   // For tail calls lower the arguments to the 'real' stack slot.
2717   if (isTailCall) {
2718     // Force all the incoming stack arguments to be loaded from the stack
2719     // before any new outgoing arguments are stored to the stack, because the
2720     // outgoing stack slots may alias the incoming argument stack slots, and
2721     // the alias isn't otherwise explicit. This is slightly more conservative
2722     // than necessary, because it means that each store effectively depends
2723     // on every argument instead of just those arguments it would clobber.
2724     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2725
2726     SmallVector<SDValue, 8> MemOpChains2;
2727     SDValue FIN;
2728     int FI = 0;
2729     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2730       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2731         CCValAssign &VA = ArgLocs[i];
2732         if (VA.isRegLoc())
2733           continue;
2734         assert(VA.isMemLoc());
2735         SDValue Arg = OutVals[i];
2736         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2737         // Create frame index.
2738         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2739         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2740         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2741         FIN = DAG.getFrameIndex(FI, getPointerTy());
2742
2743         if (Flags.isByVal()) {
2744           // Copy relative to framepointer.
2745           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2746           if (StackPtr.getNode() == 0)
2747             StackPtr = DAG.getCopyFromReg(Chain, dl,
2748                                           RegInfo->getStackRegister(),
2749                                           getPointerTy());
2750           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2751
2752           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2753                                                            ArgChain,
2754                                                            Flags, DAG, dl));
2755         } else {
2756           // Store relative to framepointer.
2757           MemOpChains2.push_back(
2758             DAG.getStore(ArgChain, dl, Arg, FIN,
2759                          MachinePointerInfo::getFixedStack(FI),
2760                          false, false, 0));
2761         }
2762       }
2763     }
2764
2765     if (!MemOpChains2.empty())
2766       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2767                           &MemOpChains2[0], MemOpChains2.size());
2768
2769     // Store the return address to the appropriate stack slot.
2770     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2771                                      getPointerTy(), RegInfo->getSlotSize(),
2772                                      FPDiff, dl);
2773   }
2774
2775   // Build a sequence of copy-to-reg nodes chained together with token chain
2776   // and flag operands which copy the outgoing args into registers.
2777   SDValue InFlag;
2778   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2779     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2780                              RegsToPass[i].second, InFlag);
2781     InFlag = Chain.getValue(1);
2782   }
2783
2784   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2785     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2786     // In the 64-bit large code model, we have to make all calls
2787     // through a register, since the call instruction's 32-bit
2788     // pc-relative offset may not be large enough to hold the whole
2789     // address.
2790   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2791     // If the callee is a GlobalAddress node (quite common, every direct call
2792     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2793     // it.
2794
2795     // We should use extra load for direct calls to dllimported functions in
2796     // non-JIT mode.
2797     const GlobalValue *GV = G->getGlobal();
2798     if (!GV->hasDLLImportLinkage()) {
2799       unsigned char OpFlags = 0;
2800       bool ExtraLoad = false;
2801       unsigned WrapperKind = ISD::DELETED_NODE;
2802
2803       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2804       // external symbols most go through the PLT in PIC mode.  If the symbol
2805       // has hidden or protected visibility, or if it is static or local, then
2806       // we don't need to use the PLT - we can directly call it.
2807       if (Subtarget->isTargetELF() &&
2808           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2809           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2810         OpFlags = X86II::MO_PLT;
2811       } else if (Subtarget->isPICStyleStubAny() &&
2812                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2813                  (!Subtarget->getTargetTriple().isMacOSX() ||
2814                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2815         // PC-relative references to external symbols should go through $stub,
2816         // unless we're building with the leopard linker or later, which
2817         // automatically synthesizes these stubs.
2818         OpFlags = X86II::MO_DARWIN_STUB;
2819       } else if (Subtarget->isPICStyleRIPRel() &&
2820                  isa<Function>(GV) &&
2821                  cast<Function>(GV)->getAttributes().
2822                    hasAttribute(AttributeSet::FunctionIndex,
2823                                 Attribute::NonLazyBind)) {
2824         // If the function is marked as non-lazy, generate an indirect call
2825         // which loads from the GOT directly. This avoids runtime overhead
2826         // at the cost of eager binding (and one extra byte of encoding).
2827         OpFlags = X86II::MO_GOTPCREL;
2828         WrapperKind = X86ISD::WrapperRIP;
2829         ExtraLoad = true;
2830       }
2831
2832       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2833                                           G->getOffset(), OpFlags);
2834
2835       // Add a wrapper if needed.
2836       if (WrapperKind != ISD::DELETED_NODE)
2837         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2838       // Add extra indirection if needed.
2839       if (ExtraLoad)
2840         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2841                              MachinePointerInfo::getGOT(),
2842                              false, false, false, 0);
2843     }
2844   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2845     unsigned char OpFlags = 0;
2846
2847     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2848     // external symbols should go through the PLT.
2849     if (Subtarget->isTargetELF() &&
2850         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2851       OpFlags = X86II::MO_PLT;
2852     } else if (Subtarget->isPICStyleStubAny() &&
2853                (!Subtarget->getTargetTriple().isMacOSX() ||
2854                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2855       // PC-relative references to external symbols should go through $stub,
2856       // unless we're building with the leopard linker or later, which
2857       // automatically synthesizes these stubs.
2858       OpFlags = X86II::MO_DARWIN_STUB;
2859     }
2860
2861     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2862                                          OpFlags);
2863   }
2864
2865   // Returns a chain & a flag for retval copy to use.
2866   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2867   SmallVector<SDValue, 8> Ops;
2868
2869   if (!IsSibcall && isTailCall) {
2870     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2871                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2872     InFlag = Chain.getValue(1);
2873   }
2874
2875   Ops.push_back(Chain);
2876   Ops.push_back(Callee);
2877
2878   if (isTailCall)
2879     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2880
2881   // Add argument registers to the end of the list so that they are known live
2882   // into the call.
2883   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2884     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2885                                   RegsToPass[i].second.getValueType()));
2886
2887   // Add a register mask operand representing the call-preserved registers.
2888   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2889   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2890   assert(Mask && "Missing call preserved mask for calling convention");
2891   Ops.push_back(DAG.getRegisterMask(Mask));
2892
2893   if (InFlag.getNode())
2894     Ops.push_back(InFlag);
2895
2896   if (isTailCall) {
2897     // We used to do:
2898     //// If this is the first return lowered for this function, add the regs
2899     //// to the liveout set for the function.
2900     // This isn't right, although it's probably harmless on x86; liveouts
2901     // should be computed from returns not tail calls.  Consider a void
2902     // function making a tail call to a function returning int.
2903     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2904   }
2905
2906   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2907   InFlag = Chain.getValue(1);
2908
2909   // Create the CALLSEQ_END node.
2910   unsigned NumBytesForCalleeToPush;
2911   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2912                        getTargetMachine().Options.GuaranteedTailCallOpt))
2913     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2914   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2915            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2916            SR == StackStructReturn)
2917     // If this is a call to a struct-return function, the callee
2918     // pops the hidden struct pointer, so we have to push it back.
2919     // This is common for Darwin/X86, Linux & Mingw32 targets.
2920     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2921     NumBytesForCalleeToPush = 4;
2922   else
2923     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2924
2925   // Returns a flag for retval copy to use.
2926   if (!IsSibcall) {
2927     Chain = DAG.getCALLSEQ_END(Chain,
2928                                DAG.getIntPtrConstant(NumBytes, true),
2929                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2930                                                      true),
2931                                InFlag, dl);
2932     InFlag = Chain.getValue(1);
2933   }
2934
2935   // Handle result values, copying them out of physregs into vregs that we
2936   // return.
2937   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2938                          Ins, dl, DAG, InVals);
2939 }
2940
2941 //===----------------------------------------------------------------------===//
2942 //                Fast Calling Convention (tail call) implementation
2943 //===----------------------------------------------------------------------===//
2944
2945 //  Like std call, callee cleans arguments, convention except that ECX is
2946 //  reserved for storing the tail called function address. Only 2 registers are
2947 //  free for argument passing (inreg). Tail call optimization is performed
2948 //  provided:
2949 //                * tailcallopt is enabled
2950 //                * caller/callee are fastcc
2951 //  On X86_64 architecture with GOT-style position independent code only local
2952 //  (within module) calls are supported at the moment.
2953 //  To keep the stack aligned according to platform abi the function
2954 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2955 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2956 //  If a tail called function callee has more arguments than the caller the
2957 //  caller needs to make sure that there is room to move the RETADDR to. This is
2958 //  achieved by reserving an area the size of the argument delta right after the
2959 //  original REtADDR, but before the saved framepointer or the spilled registers
2960 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2961 //  stack layout:
2962 //    arg1
2963 //    arg2
2964 //    RETADDR
2965 //    [ new RETADDR
2966 //      move area ]
2967 //    (possible EBP)
2968 //    ESI
2969 //    EDI
2970 //    local1 ..
2971
2972 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2973 /// for a 16 byte align requirement.
2974 unsigned
2975 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2976                                                SelectionDAG& DAG) const {
2977   MachineFunction &MF = DAG.getMachineFunction();
2978   const TargetMachine &TM = MF.getTarget();
2979   const X86RegisterInfo *RegInfo =
2980     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2981   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2982   unsigned StackAlignment = TFI.getStackAlignment();
2983   uint64_t AlignMask = StackAlignment - 1;
2984   int64_t Offset = StackSize;
2985   unsigned SlotSize = RegInfo->getSlotSize();
2986   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2987     // Number smaller than 12 so just add the difference.
2988     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2989   } else {
2990     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2991     Offset = ((~AlignMask) & Offset) + StackAlignment +
2992       (StackAlignment-SlotSize);
2993   }
2994   return Offset;
2995 }
2996
2997 /// MatchingStackOffset - Return true if the given stack call argument is
2998 /// already available in the same position (relatively) of the caller's
2999 /// incoming argument stack.
3000 static
3001 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3002                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3003                          const X86InstrInfo *TII) {
3004   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3005   int FI = INT_MAX;
3006   if (Arg.getOpcode() == ISD::CopyFromReg) {
3007     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3008     if (!TargetRegisterInfo::isVirtualRegister(VR))
3009       return false;
3010     MachineInstr *Def = MRI->getVRegDef(VR);
3011     if (!Def)
3012       return false;
3013     if (!Flags.isByVal()) {
3014       if (!TII->isLoadFromStackSlot(Def, FI))
3015         return false;
3016     } else {
3017       unsigned Opcode = Def->getOpcode();
3018       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3019           Def->getOperand(1).isFI()) {
3020         FI = Def->getOperand(1).getIndex();
3021         Bytes = Flags.getByValSize();
3022       } else
3023         return false;
3024     }
3025   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3026     if (Flags.isByVal())
3027       // ByVal argument is passed in as a pointer but it's now being
3028       // dereferenced. e.g.
3029       // define @foo(%struct.X* %A) {
3030       //   tail call @bar(%struct.X* byval %A)
3031       // }
3032       return false;
3033     SDValue Ptr = Ld->getBasePtr();
3034     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3035     if (!FINode)
3036       return false;
3037     FI = FINode->getIndex();
3038   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3039     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3040     FI = FINode->getIndex();
3041     Bytes = Flags.getByValSize();
3042   } else
3043     return false;
3044
3045   assert(FI != INT_MAX);
3046   if (!MFI->isFixedObjectIndex(FI))
3047     return false;
3048   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3049 }
3050
3051 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3052 /// for tail call optimization. Targets which want to do tail call
3053 /// optimization should implement this function.
3054 bool
3055 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3056                                                      CallingConv::ID CalleeCC,
3057                                                      bool isVarArg,
3058                                                      bool isCalleeStructRet,
3059                                                      bool isCallerStructRet,
3060                                                      Type *RetTy,
3061                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3062                                     const SmallVectorImpl<SDValue> &OutVals,
3063                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3064                                                      SelectionDAG &DAG) const {
3065   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3066     return false;
3067
3068   // If -tailcallopt is specified, make fastcc functions tail-callable.
3069   const MachineFunction &MF = DAG.getMachineFunction();
3070   const Function *CallerF = MF.getFunction();
3071
3072   // If the function return type is x86_fp80 and the callee return type is not,
3073   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3074   // perform a tailcall optimization here.
3075   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3076     return false;
3077
3078   CallingConv::ID CallerCC = CallerF->getCallingConv();
3079   bool CCMatch = CallerCC == CalleeCC;
3080   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3081   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3082
3083   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3084     if (IsTailCallConvention(CalleeCC) && CCMatch)
3085       return true;
3086     return false;
3087   }
3088
3089   // Look for obvious safe cases to perform tail call optimization that do not
3090   // require ABI changes. This is what gcc calls sibcall.
3091
3092   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3093   // emit a special epilogue.
3094   const X86RegisterInfo *RegInfo =
3095     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3096   if (RegInfo->needsStackRealignment(MF))
3097     return false;
3098
3099   // Also avoid sibcall optimization if either caller or callee uses struct
3100   // return semantics.
3101   if (isCalleeStructRet || isCallerStructRet)
3102     return false;
3103
3104   // An stdcall/thiscall caller is expected to clean up its arguments; the
3105   // callee isn't going to do that.
3106   // FIXME: this is more restrictive than needed. We could produce a tailcall
3107   // when the stack adjustment matches. For example, with a thiscall that takes
3108   // only one argument.
3109   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3110                    CallerCC == CallingConv::X86_ThisCall))
3111     return false;
3112
3113   // Do not sibcall optimize vararg calls unless all arguments are passed via
3114   // registers.
3115   if (isVarArg && !Outs.empty()) {
3116
3117     // Optimizing for varargs on Win64 is unlikely to be safe without
3118     // additional testing.
3119     if (IsCalleeWin64 || IsCallerWin64)
3120       return false;
3121
3122     SmallVector<CCValAssign, 16> ArgLocs;
3123     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3124                    getTargetMachine(), ArgLocs, *DAG.getContext());
3125
3126     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3127     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3128       if (!ArgLocs[i].isRegLoc())
3129         return false;
3130   }
3131
3132   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3133   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3134   // this into a sibcall.
3135   bool Unused = false;
3136   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3137     if (!Ins[i].Used) {
3138       Unused = true;
3139       break;
3140     }
3141   }
3142   if (Unused) {
3143     SmallVector<CCValAssign, 16> RVLocs;
3144     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3145                    getTargetMachine(), RVLocs, *DAG.getContext());
3146     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3147     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3148       CCValAssign &VA = RVLocs[i];
3149       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3150         return false;
3151     }
3152   }
3153
3154   // If the calling conventions do not match, then we'd better make sure the
3155   // results are returned in the same way as what the caller expects.
3156   if (!CCMatch) {
3157     SmallVector<CCValAssign, 16> RVLocs1;
3158     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3159                     getTargetMachine(), RVLocs1, *DAG.getContext());
3160     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3161
3162     SmallVector<CCValAssign, 16> RVLocs2;
3163     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3164                     getTargetMachine(), RVLocs2, *DAG.getContext());
3165     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3166
3167     if (RVLocs1.size() != RVLocs2.size())
3168       return false;
3169     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3170       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3171         return false;
3172       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3173         return false;
3174       if (RVLocs1[i].isRegLoc()) {
3175         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3176           return false;
3177       } else {
3178         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3179           return false;
3180       }
3181     }
3182   }
3183
3184   // If the callee takes no arguments then go on to check the results of the
3185   // call.
3186   if (!Outs.empty()) {
3187     // Check if stack adjustment is needed. For now, do not do this if any
3188     // argument is passed on the stack.
3189     SmallVector<CCValAssign, 16> ArgLocs;
3190     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3191                    getTargetMachine(), ArgLocs, *DAG.getContext());
3192
3193     // Allocate shadow area for Win64
3194     if (IsCalleeWin64)
3195       CCInfo.AllocateStack(32, 8);
3196
3197     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3198     if (CCInfo.getNextStackOffset()) {
3199       MachineFunction &MF = DAG.getMachineFunction();
3200       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3201         return false;
3202
3203       // Check if the arguments are already laid out in the right way as
3204       // the caller's fixed stack objects.
3205       MachineFrameInfo *MFI = MF.getFrameInfo();
3206       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3207       const X86InstrInfo *TII =
3208         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3209       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3210         CCValAssign &VA = ArgLocs[i];
3211         SDValue Arg = OutVals[i];
3212         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3213         if (VA.getLocInfo() == CCValAssign::Indirect)
3214           return false;
3215         if (!VA.isRegLoc()) {
3216           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3217                                    MFI, MRI, TII))
3218             return false;
3219         }
3220       }
3221     }
3222
3223     // If the tailcall address may be in a register, then make sure it's
3224     // possible to register allocate for it. In 32-bit, the call address can
3225     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3226     // callee-saved registers are restored. These happen to be the same
3227     // registers used to pass 'inreg' arguments so watch out for those.
3228     if (!Subtarget->is64Bit() &&
3229         ((!isa<GlobalAddressSDNode>(Callee) &&
3230           !isa<ExternalSymbolSDNode>(Callee)) ||
3231          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3232       unsigned NumInRegs = 0;
3233       // In PIC we need an extra register to formulate the address computation
3234       // for the callee.
3235       unsigned MaxInRegs =
3236           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3237
3238       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3239         CCValAssign &VA = ArgLocs[i];
3240         if (!VA.isRegLoc())
3241           continue;
3242         unsigned Reg = VA.getLocReg();
3243         switch (Reg) {
3244         default: break;
3245         case X86::EAX: case X86::EDX: case X86::ECX:
3246           if (++NumInRegs == MaxInRegs)
3247             return false;
3248           break;
3249         }
3250       }
3251     }
3252   }
3253
3254   return true;
3255 }
3256
3257 FastISel *
3258 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3259                                   const TargetLibraryInfo *libInfo) const {
3260   return X86::createFastISel(funcInfo, libInfo);
3261 }
3262
3263 //===----------------------------------------------------------------------===//
3264 //                           Other Lowering Hooks
3265 //===----------------------------------------------------------------------===//
3266
3267 static bool MayFoldLoad(SDValue Op) {
3268   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3269 }
3270
3271 static bool MayFoldIntoStore(SDValue Op) {
3272   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3273 }
3274
3275 static bool isTargetShuffle(unsigned Opcode) {
3276   switch(Opcode) {
3277   default: return false;
3278   case X86ISD::PSHUFD:
3279   case X86ISD::PSHUFHW:
3280   case X86ISD::PSHUFLW:
3281   case X86ISD::SHUFP:
3282   case X86ISD::PALIGNR:
3283   case X86ISD::MOVLHPS:
3284   case X86ISD::MOVLHPD:
3285   case X86ISD::MOVHLPS:
3286   case X86ISD::MOVLPS:
3287   case X86ISD::MOVLPD:
3288   case X86ISD::MOVSHDUP:
3289   case X86ISD::MOVSLDUP:
3290   case X86ISD::MOVDDUP:
3291   case X86ISD::MOVSS:
3292   case X86ISD::MOVSD:
3293   case X86ISD::UNPCKL:
3294   case X86ISD::UNPCKH:
3295   case X86ISD::VPERMILP:
3296   case X86ISD::VPERM2X128:
3297   case X86ISD::VPERMI:
3298     return true;
3299   }
3300 }
3301
3302 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3303                                     SDValue V1, SelectionDAG &DAG) {
3304   switch(Opc) {
3305   default: llvm_unreachable("Unknown x86 shuffle node");
3306   case X86ISD::MOVSHDUP:
3307   case X86ISD::MOVSLDUP:
3308   case X86ISD::MOVDDUP:
3309     return DAG.getNode(Opc, dl, VT, V1);
3310   }
3311 }
3312
3313 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3314                                     SDValue V1, unsigned TargetMask,
3315                                     SelectionDAG &DAG) {
3316   switch(Opc) {
3317   default: llvm_unreachable("Unknown x86 shuffle node");
3318   case X86ISD::PSHUFD:
3319   case X86ISD::PSHUFHW:
3320   case X86ISD::PSHUFLW:
3321   case X86ISD::VPERMILP:
3322   case X86ISD::VPERMI:
3323     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3324   }
3325 }
3326
3327 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3328                                     SDValue V1, SDValue V2, unsigned TargetMask,
3329                                     SelectionDAG &DAG) {
3330   switch(Opc) {
3331   default: llvm_unreachable("Unknown x86 shuffle node");
3332   case X86ISD::PALIGNR:
3333   case X86ISD::SHUFP:
3334   case X86ISD::VPERM2X128:
3335     return DAG.getNode(Opc, dl, VT, V1, V2,
3336                        DAG.getConstant(TargetMask, MVT::i8));
3337   }
3338 }
3339
3340 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3341                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3342   switch(Opc) {
3343   default: llvm_unreachable("Unknown x86 shuffle node");
3344   case X86ISD::MOVLHPS:
3345   case X86ISD::MOVLHPD:
3346   case X86ISD::MOVHLPS:
3347   case X86ISD::MOVLPS:
3348   case X86ISD::MOVLPD:
3349   case X86ISD::MOVSS:
3350   case X86ISD::MOVSD:
3351   case X86ISD::UNPCKL:
3352   case X86ISD::UNPCKH:
3353     return DAG.getNode(Opc, dl, VT, V1, V2);
3354   }
3355 }
3356
3357 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3358   MachineFunction &MF = DAG.getMachineFunction();
3359   const X86RegisterInfo *RegInfo =
3360     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3361   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3362   int ReturnAddrIndex = FuncInfo->getRAIndex();
3363
3364   if (ReturnAddrIndex == 0) {
3365     // Set up a frame object for the return address.
3366     unsigned SlotSize = RegInfo->getSlotSize();
3367     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3368                                                            -(int64_t)SlotSize,
3369                                                            false);
3370     FuncInfo->setRAIndex(ReturnAddrIndex);
3371   }
3372
3373   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3374 }
3375
3376 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3377                                        bool hasSymbolicDisplacement) {
3378   // Offset should fit into 32 bit immediate field.
3379   if (!isInt<32>(Offset))
3380     return false;
3381
3382   // If we don't have a symbolic displacement - we don't have any extra
3383   // restrictions.
3384   if (!hasSymbolicDisplacement)
3385     return true;
3386
3387   // FIXME: Some tweaks might be needed for medium code model.
3388   if (M != CodeModel::Small && M != CodeModel::Kernel)
3389     return false;
3390
3391   // For small code model we assume that latest object is 16MB before end of 31
3392   // bits boundary. We may also accept pretty large negative constants knowing
3393   // that all objects are in the positive half of address space.
3394   if (M == CodeModel::Small && Offset < 16*1024*1024)
3395     return true;
3396
3397   // For kernel code model we know that all object resist in the negative half
3398   // of 32bits address space. We may not accept negative offsets, since they may
3399   // be just off and we may accept pretty large positive ones.
3400   if (M == CodeModel::Kernel && Offset > 0)
3401     return true;
3402
3403   return false;
3404 }
3405
3406 /// isCalleePop - Determines whether the callee is required to pop its
3407 /// own arguments. Callee pop is necessary to support tail calls.
3408 bool X86::isCalleePop(CallingConv::ID CallingConv,
3409                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3410   if (IsVarArg)
3411     return false;
3412
3413   switch (CallingConv) {
3414   default:
3415     return false;
3416   case CallingConv::X86_StdCall:
3417     return !is64Bit;
3418   case CallingConv::X86_FastCall:
3419     return !is64Bit;
3420   case CallingConv::X86_ThisCall:
3421     return !is64Bit;
3422   case CallingConv::Fast:
3423     return TailCallOpt;
3424   case CallingConv::GHC:
3425     return TailCallOpt;
3426   case CallingConv::HiPE:
3427     return TailCallOpt;
3428   }
3429 }
3430
3431 /// \brief Return true if the condition is an unsigned comparison operation.
3432 static bool isX86CCUnsigned(unsigned X86CC) {
3433   switch (X86CC) {
3434   default: llvm_unreachable("Invalid integer condition!");
3435   case X86::COND_E:     return true;
3436   case X86::COND_G:     return false;
3437   case X86::COND_GE:    return false;
3438   case X86::COND_L:     return false;
3439   case X86::COND_LE:    return false;
3440   case X86::COND_NE:    return true;
3441   case X86::COND_B:     return true;
3442   case X86::COND_A:     return true;
3443   case X86::COND_BE:    return true;
3444   case X86::COND_AE:    return true;
3445   }
3446   llvm_unreachable("covered switch fell through?!");
3447 }
3448
3449 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3450 /// specific condition code, returning the condition code and the LHS/RHS of the
3451 /// comparison to make.
3452 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3453                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3454   if (!isFP) {
3455     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3456       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3457         // X > -1   -> X == 0, jump !sign.
3458         RHS = DAG.getConstant(0, RHS.getValueType());
3459         return X86::COND_NS;
3460       }
3461       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3462         // X < 0   -> X == 0, jump on sign.
3463         return X86::COND_S;
3464       }
3465       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3466         // X < 1   -> X <= 0
3467         RHS = DAG.getConstant(0, RHS.getValueType());
3468         return X86::COND_LE;
3469       }
3470     }
3471
3472     switch (SetCCOpcode) {
3473     default: llvm_unreachable("Invalid integer condition!");
3474     case ISD::SETEQ:  return X86::COND_E;
3475     case ISD::SETGT:  return X86::COND_G;
3476     case ISD::SETGE:  return X86::COND_GE;
3477     case ISD::SETLT:  return X86::COND_L;
3478     case ISD::SETLE:  return X86::COND_LE;
3479     case ISD::SETNE:  return X86::COND_NE;
3480     case ISD::SETULT: return X86::COND_B;
3481     case ISD::SETUGT: return X86::COND_A;
3482     case ISD::SETULE: return X86::COND_BE;
3483     case ISD::SETUGE: return X86::COND_AE;
3484     }
3485   }
3486
3487   // First determine if it is required or is profitable to flip the operands.
3488
3489   // If LHS is a foldable load, but RHS is not, flip the condition.
3490   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3491       !ISD::isNON_EXTLoad(RHS.getNode())) {
3492     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3493     std::swap(LHS, RHS);
3494   }
3495
3496   switch (SetCCOpcode) {
3497   default: break;
3498   case ISD::SETOLT:
3499   case ISD::SETOLE:
3500   case ISD::SETUGT:
3501   case ISD::SETUGE:
3502     std::swap(LHS, RHS);
3503     break;
3504   }
3505
3506   // On a floating point condition, the flags are set as follows:
3507   // ZF  PF  CF   op
3508   //  0 | 0 | 0 | X > Y
3509   //  0 | 0 | 1 | X < Y
3510   //  1 | 0 | 0 | X == Y
3511   //  1 | 1 | 1 | unordered
3512   switch (SetCCOpcode) {
3513   default: llvm_unreachable("Condcode should be pre-legalized away");
3514   case ISD::SETUEQ:
3515   case ISD::SETEQ:   return X86::COND_E;
3516   case ISD::SETOLT:              // flipped
3517   case ISD::SETOGT:
3518   case ISD::SETGT:   return X86::COND_A;
3519   case ISD::SETOLE:              // flipped
3520   case ISD::SETOGE:
3521   case ISD::SETGE:   return X86::COND_AE;
3522   case ISD::SETUGT:              // flipped
3523   case ISD::SETULT:
3524   case ISD::SETLT:   return X86::COND_B;
3525   case ISD::SETUGE:              // flipped
3526   case ISD::SETULE:
3527   case ISD::SETLE:   return X86::COND_BE;
3528   case ISD::SETONE:
3529   case ISD::SETNE:   return X86::COND_NE;
3530   case ISD::SETUO:   return X86::COND_P;
3531   case ISD::SETO:    return X86::COND_NP;
3532   case ISD::SETOEQ:
3533   case ISD::SETUNE:  return X86::COND_INVALID;
3534   }
3535 }
3536
3537 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3538 /// code. Current x86 isa includes the following FP cmov instructions:
3539 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3540 static bool hasFPCMov(unsigned X86CC) {
3541   switch (X86CC) {
3542   default:
3543     return false;
3544   case X86::COND_B:
3545   case X86::COND_BE:
3546   case X86::COND_E:
3547   case X86::COND_P:
3548   case X86::COND_A:
3549   case X86::COND_AE:
3550   case X86::COND_NE:
3551   case X86::COND_NP:
3552     return true;
3553   }
3554 }
3555
3556 /// isFPImmLegal - Returns true if the target can instruction select the
3557 /// specified FP immediate natively. If false, the legalizer will
3558 /// materialize the FP immediate as a load from a constant pool.
3559 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3560   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3561     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3562       return true;
3563   }
3564   return false;
3565 }
3566
3567 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3568 /// the specified range (L, H].
3569 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3570   return (Val < 0) || (Val >= Low && Val < Hi);
3571 }
3572
3573 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3574 /// specified value.
3575 static bool isUndefOrEqual(int Val, int CmpVal) {
3576   return (Val < 0 || Val == CmpVal);
3577 }
3578
3579 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3580 /// from position Pos and ending in Pos+Size, falls within the specified
3581 /// sequential range (L, L+Pos]. or is undef.
3582 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3583                                        unsigned Pos, unsigned Size, int Low) {
3584   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3585     if (!isUndefOrEqual(Mask[i], Low))
3586       return false;
3587   return true;
3588 }
3589
3590 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3591 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3592 /// the second operand.
3593 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3594   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3595     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3596   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3597     return (Mask[0] < 2 && Mask[1] < 2);
3598   return false;
3599 }
3600
3601 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3602 /// is suitable for input to PSHUFHW.
3603 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3604   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3605     return false;
3606
3607   // Lower quadword copied in order or undef.
3608   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3609     return false;
3610
3611   // Upper quadword shuffled.
3612   for (unsigned i = 4; i != 8; ++i)
3613     if (!isUndefOrInRange(Mask[i], 4, 8))
3614       return false;
3615
3616   if (VT == MVT::v16i16) {
3617     // Lower quadword copied in order or undef.
3618     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3619       return false;
3620
3621     // Upper quadword shuffled.
3622     for (unsigned i = 12; i != 16; ++i)
3623       if (!isUndefOrInRange(Mask[i], 12, 16))
3624         return false;
3625   }
3626
3627   return true;
3628 }
3629
3630 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3631 /// is suitable for input to PSHUFLW.
3632 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3633   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3634     return false;
3635
3636   // Upper quadword copied in order.
3637   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3638     return false;
3639
3640   // Lower quadword shuffled.
3641   for (unsigned i = 0; i != 4; ++i)
3642     if (!isUndefOrInRange(Mask[i], 0, 4))
3643       return false;
3644
3645   if (VT == MVT::v16i16) {
3646     // Upper quadword copied in order.
3647     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3648       return false;
3649
3650     // Lower quadword shuffled.
3651     for (unsigned i = 8; i != 12; ++i)
3652       if (!isUndefOrInRange(Mask[i], 8, 12))
3653         return false;
3654   }
3655
3656   return true;
3657 }
3658
3659 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3660 /// is suitable for input to PALIGNR.
3661 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3662                           const X86Subtarget *Subtarget) {
3663   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3664       (VT.is256BitVector() && !Subtarget->hasInt256()))
3665     return false;
3666
3667   unsigned NumElts = VT.getVectorNumElements();
3668   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3669   unsigned NumLaneElts = NumElts/NumLanes;
3670
3671   // Do not handle 64-bit element shuffles with palignr.
3672   if (NumLaneElts == 2)
3673     return false;
3674
3675   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3676     unsigned i;
3677     for (i = 0; i != NumLaneElts; ++i) {
3678       if (Mask[i+l] >= 0)
3679         break;
3680     }
3681
3682     // Lane is all undef, go to next lane
3683     if (i == NumLaneElts)
3684       continue;
3685
3686     int Start = Mask[i+l];
3687
3688     // Make sure its in this lane in one of the sources
3689     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3690         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3691       return false;
3692
3693     // If not lane 0, then we must match lane 0
3694     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3695       return false;
3696
3697     // Correct second source to be contiguous with first source
3698     if (Start >= (int)NumElts)
3699       Start -= NumElts - NumLaneElts;
3700
3701     // Make sure we're shifting in the right direction.
3702     if (Start <= (int)(i+l))
3703       return false;
3704
3705     Start -= i;
3706
3707     // Check the rest of the elements to see if they are consecutive.
3708     for (++i; i != NumLaneElts; ++i) {
3709       int Idx = Mask[i+l];
3710
3711       // Make sure its in this lane
3712       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3713           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3714         return false;
3715
3716       // If not lane 0, then we must match lane 0
3717       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3718         return false;
3719
3720       if (Idx >= (int)NumElts)
3721         Idx -= NumElts - NumLaneElts;
3722
3723       if (!isUndefOrEqual(Idx, Start+i))
3724         return false;
3725
3726     }
3727   }
3728
3729   return true;
3730 }
3731
3732 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3733 /// the two vector operands have swapped position.
3734 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3735                                      unsigned NumElems) {
3736   for (unsigned i = 0; i != NumElems; ++i) {
3737     int idx = Mask[i];
3738     if (idx < 0)
3739       continue;
3740     else if (idx < (int)NumElems)
3741       Mask[i] = idx + NumElems;
3742     else
3743       Mask[i] = idx - NumElems;
3744   }
3745 }
3746
3747 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3748 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3749 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3750 /// reverse of what x86 shuffles want.
3751 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3752
3753   unsigned NumElems = VT.getVectorNumElements();
3754   unsigned NumLanes = VT.getSizeInBits()/128;
3755   unsigned NumLaneElems = NumElems/NumLanes;
3756
3757   if (NumLaneElems != 2 && NumLaneElems != 4)
3758     return false;
3759
3760   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3761   bool symetricMaskRequired =
3762     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3763
3764   // VSHUFPSY divides the resulting vector into 4 chunks.
3765   // The sources are also splitted into 4 chunks, and each destination
3766   // chunk must come from a different source chunk.
3767   //
3768   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3769   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3770   //
3771   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3772   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3773   //
3774   // VSHUFPDY divides the resulting vector into 4 chunks.
3775   // The sources are also splitted into 4 chunks, and each destination
3776   // chunk must come from a different source chunk.
3777   //
3778   //  SRC1 =>      X3       X2       X1       X0
3779   //  SRC2 =>      Y3       Y2       Y1       Y0
3780   //
3781   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3782   //
3783   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3784   unsigned HalfLaneElems = NumLaneElems/2;
3785   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3786     for (unsigned i = 0; i != NumLaneElems; ++i) {
3787       int Idx = Mask[i+l];
3788       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3789       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3790         return false;
3791       // For VSHUFPSY, the mask of the second half must be the same as the
3792       // first but with the appropriate offsets. This works in the same way as
3793       // VPERMILPS works with masks.
3794       if (!symetricMaskRequired || Idx < 0)
3795         continue;
3796       if (MaskVal[i] < 0) {
3797         MaskVal[i] = Idx - l;
3798         continue;
3799       }
3800       if ((signed)(Idx - l) != MaskVal[i])
3801         return false;
3802     }
3803   }
3804
3805   return true;
3806 }
3807
3808 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3809 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3810 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3811   if (!VT.is128BitVector())
3812     return false;
3813
3814   unsigned NumElems = VT.getVectorNumElements();
3815
3816   if (NumElems != 4)
3817     return false;
3818
3819   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3820   return isUndefOrEqual(Mask[0], 6) &&
3821          isUndefOrEqual(Mask[1], 7) &&
3822          isUndefOrEqual(Mask[2], 2) &&
3823          isUndefOrEqual(Mask[3], 3);
3824 }
3825
3826 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3827 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3828 /// <2, 3, 2, 3>
3829 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3830   if (!VT.is128BitVector())
3831     return false;
3832
3833   unsigned NumElems = VT.getVectorNumElements();
3834
3835   if (NumElems != 4)
3836     return false;
3837
3838   return isUndefOrEqual(Mask[0], 2) &&
3839          isUndefOrEqual(Mask[1], 3) &&
3840          isUndefOrEqual(Mask[2], 2) &&
3841          isUndefOrEqual(Mask[3], 3);
3842 }
3843
3844 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3845 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3846 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3847   if (!VT.is128BitVector())
3848     return false;
3849
3850   unsigned NumElems = VT.getVectorNumElements();
3851
3852   if (NumElems != 2 && NumElems != 4)
3853     return false;
3854
3855   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3856     if (!isUndefOrEqual(Mask[i], i + NumElems))
3857       return false;
3858
3859   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3860     if (!isUndefOrEqual(Mask[i], i))
3861       return false;
3862
3863   return true;
3864 }
3865
3866 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3867 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3868 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3869   if (!VT.is128BitVector())
3870     return false;
3871
3872   unsigned NumElems = VT.getVectorNumElements();
3873
3874   if (NumElems != 2 && NumElems != 4)
3875     return false;
3876
3877   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3878     if (!isUndefOrEqual(Mask[i], i))
3879       return false;
3880
3881   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3882     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3883       return false;
3884
3885   return true;
3886 }
3887
3888 //
3889 // Some special combinations that can be optimized.
3890 //
3891 static
3892 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3893                                SelectionDAG &DAG) {
3894   MVT VT = SVOp->getSimpleValueType(0);
3895   SDLoc dl(SVOp);
3896
3897   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3898     return SDValue();
3899
3900   ArrayRef<int> Mask = SVOp->getMask();
3901
3902   // These are the special masks that may be optimized.
3903   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3904   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3905   bool MatchEvenMask = true;
3906   bool MatchOddMask  = true;
3907   for (int i=0; i<8; ++i) {
3908     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3909       MatchEvenMask = false;
3910     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3911       MatchOddMask = false;
3912   }
3913
3914   if (!MatchEvenMask && !MatchOddMask)
3915     return SDValue();
3916
3917   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3918
3919   SDValue Op0 = SVOp->getOperand(0);
3920   SDValue Op1 = SVOp->getOperand(1);
3921
3922   if (MatchEvenMask) {
3923     // Shift the second operand right to 32 bits.
3924     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3925     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3926   } else {
3927     // Shift the first operand left to 32 bits.
3928     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3929     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3930   }
3931   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3932   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3933 }
3934
3935 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3937 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3938                          bool HasInt256, bool V2IsSplat = false) {
3939
3940   assert(VT.getSizeInBits() >= 128 &&
3941          "Unsupported vector type for unpckl");
3942
3943   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3944   unsigned NumLanes;
3945   unsigned NumOf256BitLanes;
3946   unsigned NumElts = VT.getVectorNumElements();
3947   if (VT.is256BitVector()) {
3948     if (NumElts != 4 && NumElts != 8 &&
3949         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3950     return false;
3951     NumLanes = 2;
3952     NumOf256BitLanes = 1;
3953   } else if (VT.is512BitVector()) {
3954     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3955            "Unsupported vector type for unpckh");
3956     NumLanes = 2;
3957     NumOf256BitLanes = 2;
3958   } else {
3959     NumLanes = 1;
3960     NumOf256BitLanes = 1;
3961   }
3962
3963   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
3964   unsigned NumLaneElts = NumEltsInStride/NumLanes;
3965
3966   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
3967     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
3968       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3969         int BitI  = Mask[l256*NumEltsInStride+l+i];
3970         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
3971         if (!isUndefOrEqual(BitI, j+l256*NumElts))
3972           return false;
3973         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
3974           return false;
3975         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
3976           return false;
3977       }
3978     }
3979   }
3980   return true;
3981 }
3982
3983 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3984 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3985 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
3986                          bool HasInt256, bool V2IsSplat = false) {
3987   assert(VT.getSizeInBits() >= 128 &&
3988          "Unsupported vector type for unpckh");
3989
3990   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3991   unsigned NumLanes;
3992   unsigned NumOf256BitLanes;
3993   unsigned NumElts = VT.getVectorNumElements();
3994   if (VT.is256BitVector()) {
3995     if (NumElts != 4 && NumElts != 8 &&
3996         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3997     return false;
3998     NumLanes = 2;
3999     NumOf256BitLanes = 1;
4000   } else if (VT.is512BitVector()) {
4001     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4002            "Unsupported vector type for unpckh");
4003     NumLanes = 2;
4004     NumOf256BitLanes = 2;
4005   } else {
4006     NumLanes = 1;
4007     NumOf256BitLanes = 1;
4008   }
4009
4010   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4011   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4012
4013   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4014     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4015       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4016         int BitI  = Mask[l256*NumEltsInStride+l+i];
4017         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4018         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4019           return false;
4020         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4021           return false;
4022         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4023           return false;
4024       }
4025     }
4026   }
4027   return true;
4028 }
4029
4030 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4031 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4032 /// <0, 0, 1, 1>
4033 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4034   unsigned NumElts = VT.getVectorNumElements();
4035   bool Is256BitVec = VT.is256BitVector();
4036
4037   if (VT.is512BitVector())
4038     return false;
4039   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4040          "Unsupported vector type for unpckh");
4041
4042   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4043       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4044     return false;
4045
4046   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4047   // FIXME: Need a better way to get rid of this, there's no latency difference
4048   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4049   // the former later. We should also remove the "_undef" special mask.
4050   if (NumElts == 4 && Is256BitVec)
4051     return false;
4052
4053   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4054   // independently on 128-bit lanes.
4055   unsigned NumLanes = VT.getSizeInBits()/128;
4056   unsigned NumLaneElts = NumElts/NumLanes;
4057
4058   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4059     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4060       int BitI  = Mask[l+i];
4061       int BitI1 = Mask[l+i+1];
4062
4063       if (!isUndefOrEqual(BitI, j))
4064         return false;
4065       if (!isUndefOrEqual(BitI1, j))
4066         return false;
4067     }
4068   }
4069
4070   return true;
4071 }
4072
4073 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4074 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4075 /// <2, 2, 3, 3>
4076 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4077   unsigned NumElts = VT.getVectorNumElements();
4078
4079   if (VT.is512BitVector())
4080     return false;
4081
4082   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4083          "Unsupported vector type for unpckh");
4084
4085   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4086       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4087     return false;
4088
4089   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4090   // independently on 128-bit lanes.
4091   unsigned NumLanes = VT.getSizeInBits()/128;
4092   unsigned NumLaneElts = NumElts/NumLanes;
4093
4094   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4095     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4096       int BitI  = Mask[l+i];
4097       int BitI1 = Mask[l+i+1];
4098       if (!isUndefOrEqual(BitI, j))
4099         return false;
4100       if (!isUndefOrEqual(BitI1, j))
4101         return false;
4102     }
4103   }
4104   return true;
4105 }
4106
4107 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4108 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4109 /// MOVSD, and MOVD, i.e. setting the lowest element.
4110 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4111   if (VT.getVectorElementType().getSizeInBits() < 32)
4112     return false;
4113   if (!VT.is128BitVector())
4114     return false;
4115
4116   unsigned NumElts = VT.getVectorNumElements();
4117
4118   if (!isUndefOrEqual(Mask[0], NumElts))
4119     return false;
4120
4121   for (unsigned i = 1; i != NumElts; ++i)
4122     if (!isUndefOrEqual(Mask[i], i))
4123       return false;
4124
4125   return true;
4126 }
4127
4128 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4129 /// as permutations between 128-bit chunks or halves. As an example: this
4130 /// shuffle bellow:
4131 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4132 /// The first half comes from the second half of V1 and the second half from the
4133 /// the second half of V2.
4134 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4135   if (!HasFp256 || !VT.is256BitVector())
4136     return false;
4137
4138   // The shuffle result is divided into half A and half B. In total the two
4139   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4140   // B must come from C, D, E or F.
4141   unsigned HalfSize = VT.getVectorNumElements()/2;
4142   bool MatchA = false, MatchB = false;
4143
4144   // Check if A comes from one of C, D, E, F.
4145   for (unsigned Half = 0; Half != 4; ++Half) {
4146     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4147       MatchA = true;
4148       break;
4149     }
4150   }
4151
4152   // Check if B comes from one of C, D, E, F.
4153   for (unsigned Half = 0; Half != 4; ++Half) {
4154     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4155       MatchB = true;
4156       break;
4157     }
4158   }
4159
4160   return MatchA && MatchB;
4161 }
4162
4163 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4164 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4165 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4166   MVT VT = SVOp->getSimpleValueType(0);
4167
4168   unsigned HalfSize = VT.getVectorNumElements()/2;
4169
4170   unsigned FstHalf = 0, SndHalf = 0;
4171   for (unsigned i = 0; i < HalfSize; ++i) {
4172     if (SVOp->getMaskElt(i) > 0) {
4173       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4174       break;
4175     }
4176   }
4177   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4178     if (SVOp->getMaskElt(i) > 0) {
4179       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4180       break;
4181     }
4182   }
4183
4184   return (FstHalf | (SndHalf << 4));
4185 }
4186
4187 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4188 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4189   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4190   if (EltSize < 32)
4191     return false;
4192
4193   unsigned NumElts = VT.getVectorNumElements();
4194   Imm8 = 0;
4195   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4196     for (unsigned i = 0; i != NumElts; ++i) {
4197       if (Mask[i] < 0)
4198         continue;
4199       Imm8 |= Mask[i] << (i*2);
4200     }
4201     return true;
4202   }
4203
4204   unsigned LaneSize = 4;
4205   SmallVector<int, 4> MaskVal(LaneSize, -1);
4206
4207   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4208     for (unsigned i = 0; i != LaneSize; ++i) {
4209       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4210         return false;
4211       if (Mask[i+l] < 0)
4212         continue;
4213       if (MaskVal[i] < 0) {
4214         MaskVal[i] = Mask[i+l] - l;
4215         Imm8 |= MaskVal[i] << (i*2);
4216         continue;
4217       }
4218       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4219         return false;
4220     }
4221   }
4222   return true;
4223 }
4224
4225 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4226 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4227 /// Note that VPERMIL mask matching is different depending whether theunderlying
4228 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4229 /// to the same elements of the low, but to the higher half of the source.
4230 /// In VPERMILPD the two lanes could be shuffled independently of each other
4231 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4232 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4233   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4234   if (VT.getSizeInBits() < 256 || EltSize < 32)
4235     return false;
4236   bool symetricMaskRequired = (EltSize == 32);
4237   unsigned NumElts = VT.getVectorNumElements();
4238
4239   unsigned NumLanes = VT.getSizeInBits()/128;
4240   unsigned LaneSize = NumElts/NumLanes;
4241   // 2 or 4 elements in one lane
4242
4243   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4244   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4245     for (unsigned i = 0; i != LaneSize; ++i) {
4246       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4247         return false;
4248       if (symetricMaskRequired) {
4249         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4250           ExpectedMaskVal[i] = Mask[i+l] - l;
4251           continue;
4252         }
4253         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4254           return false;
4255       }
4256     }
4257   }
4258   return true;
4259 }
4260
4261 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4262 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4263 /// element of vector 2 and the other elements to come from vector 1 in order.
4264 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4265                                bool V2IsSplat = false, bool V2IsUndef = false) {
4266   if (!VT.is128BitVector())
4267     return false;
4268
4269   unsigned NumOps = VT.getVectorNumElements();
4270   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4271     return false;
4272
4273   if (!isUndefOrEqual(Mask[0], 0))
4274     return false;
4275
4276   for (unsigned i = 1; i != NumOps; ++i)
4277     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4278           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4279           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4280       return false;
4281
4282   return true;
4283 }
4284
4285 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4286 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4287 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4288 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4289                            const X86Subtarget *Subtarget) {
4290   if (!Subtarget->hasSSE3())
4291     return false;
4292
4293   unsigned NumElems = VT.getVectorNumElements();
4294
4295   if ((VT.is128BitVector() && NumElems != 4) ||
4296       (VT.is256BitVector() && NumElems != 8) ||
4297       (VT.is512BitVector() && NumElems != 16))
4298     return false;
4299
4300   // "i+1" is the value the indexed mask element must have
4301   for (unsigned i = 0; i != NumElems; i += 2)
4302     if (!isUndefOrEqual(Mask[i], i+1) ||
4303         !isUndefOrEqual(Mask[i+1], i+1))
4304       return false;
4305
4306   return true;
4307 }
4308
4309 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4310 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4311 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4312 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4313                            const X86Subtarget *Subtarget) {
4314   if (!Subtarget->hasSSE3())
4315     return false;
4316
4317   unsigned NumElems = VT.getVectorNumElements();
4318
4319   if ((VT.is128BitVector() && NumElems != 4) ||
4320       (VT.is256BitVector() && NumElems != 8) ||
4321       (VT.is512BitVector() && NumElems != 16))
4322     return false;
4323
4324   // "i" is the value the indexed mask element must have
4325   for (unsigned i = 0; i != NumElems; i += 2)
4326     if (!isUndefOrEqual(Mask[i], i) ||
4327         !isUndefOrEqual(Mask[i+1], i))
4328       return false;
4329
4330   return true;
4331 }
4332
4333 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4334 /// specifies a shuffle of elements that is suitable for input to 256-bit
4335 /// version of MOVDDUP.
4336 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4337   if (!HasFp256 || !VT.is256BitVector())
4338     return false;
4339
4340   unsigned NumElts = VT.getVectorNumElements();
4341   if (NumElts != 4)
4342     return false;
4343
4344   for (unsigned i = 0; i != NumElts/2; ++i)
4345     if (!isUndefOrEqual(Mask[i], 0))
4346       return false;
4347   for (unsigned i = NumElts/2; i != NumElts; ++i)
4348     if (!isUndefOrEqual(Mask[i], NumElts/2))
4349       return false;
4350   return true;
4351 }
4352
4353 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4354 /// specifies a shuffle of elements that is suitable for input to 128-bit
4355 /// version of MOVDDUP.
4356 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4357   if (!VT.is128BitVector())
4358     return false;
4359
4360   unsigned e = VT.getVectorNumElements() / 2;
4361   for (unsigned i = 0; i != e; ++i)
4362     if (!isUndefOrEqual(Mask[i], i))
4363       return false;
4364   for (unsigned i = 0; i != e; ++i)
4365     if (!isUndefOrEqual(Mask[e+i], i))
4366       return false;
4367   return true;
4368 }
4369
4370 /// isVEXTRACTIndex - Return true if the specified
4371 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4372 /// suitable for instruction that extract 128 or 256 bit vectors
4373 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4374   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4375   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4376     return false;
4377
4378   // The index should be aligned on a vecWidth-bit boundary.
4379   uint64_t Index =
4380     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4381
4382   MVT VT = N->getSimpleValueType(0);
4383   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4384   bool Result = (Index * ElSize) % vecWidth == 0;
4385
4386   return Result;
4387 }
4388
4389 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4390 /// operand specifies a subvector insert that is suitable for input to
4391 /// insertion of 128 or 256-bit subvectors
4392 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4393   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4394   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4395     return false;
4396   // The index should be aligned on a vecWidth-bit boundary.
4397   uint64_t Index =
4398     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4399
4400   MVT VT = N->getSimpleValueType(0);
4401   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4402   bool Result = (Index * ElSize) % vecWidth == 0;
4403
4404   return Result;
4405 }
4406
4407 bool X86::isVINSERT128Index(SDNode *N) {
4408   return isVINSERTIndex(N, 128);
4409 }
4410
4411 bool X86::isVINSERT256Index(SDNode *N) {
4412   return isVINSERTIndex(N, 256);
4413 }
4414
4415 bool X86::isVEXTRACT128Index(SDNode *N) {
4416   return isVEXTRACTIndex(N, 128);
4417 }
4418
4419 bool X86::isVEXTRACT256Index(SDNode *N) {
4420   return isVEXTRACTIndex(N, 256);
4421 }
4422
4423 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4424 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4425 /// Handles 128-bit and 256-bit.
4426 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4427   MVT VT = N->getSimpleValueType(0);
4428
4429   assert((VT.getSizeInBits() >= 128) &&
4430          "Unsupported vector type for PSHUF/SHUFP");
4431
4432   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4433   // independently on 128-bit lanes.
4434   unsigned NumElts = VT.getVectorNumElements();
4435   unsigned NumLanes = VT.getSizeInBits()/128;
4436   unsigned NumLaneElts = NumElts/NumLanes;
4437
4438   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4439          "Only supports 2, 4 or 8 elements per lane");
4440
4441   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4442   unsigned Mask = 0;
4443   for (unsigned i = 0; i != NumElts; ++i) {
4444     int Elt = N->getMaskElt(i);
4445     if (Elt < 0) continue;
4446     Elt &= NumLaneElts - 1;
4447     unsigned ShAmt = (i << Shift) % 8;
4448     Mask |= Elt << ShAmt;
4449   }
4450
4451   return Mask;
4452 }
4453
4454 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4455 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4456 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4457   MVT VT = N->getSimpleValueType(0);
4458
4459   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4460          "Unsupported vector type for PSHUFHW");
4461
4462   unsigned NumElts = VT.getVectorNumElements();
4463
4464   unsigned Mask = 0;
4465   for (unsigned l = 0; l != NumElts; l += 8) {
4466     // 8 nodes per lane, but we only care about the last 4.
4467     for (unsigned i = 0; i < 4; ++i) {
4468       int Elt = N->getMaskElt(l+i+4);
4469       if (Elt < 0) continue;
4470       Elt &= 0x3; // only 2-bits.
4471       Mask |= Elt << (i * 2);
4472     }
4473   }
4474
4475   return Mask;
4476 }
4477
4478 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4479 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4480 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4481   MVT VT = N->getSimpleValueType(0);
4482
4483   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4484          "Unsupported vector type for PSHUFHW");
4485
4486   unsigned NumElts = VT.getVectorNumElements();
4487
4488   unsigned Mask = 0;
4489   for (unsigned l = 0; l != NumElts; l += 8) {
4490     // 8 nodes per lane, but we only care about the first 4.
4491     for (unsigned i = 0; i < 4; ++i) {
4492       int Elt = N->getMaskElt(l+i);
4493       if (Elt < 0) continue;
4494       Elt &= 0x3; // only 2-bits
4495       Mask |= Elt << (i * 2);
4496     }
4497   }
4498
4499   return Mask;
4500 }
4501
4502 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4503 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4504 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4505   MVT VT = SVOp->getSimpleValueType(0);
4506   unsigned EltSize = VT.is512BitVector() ? 1 :
4507     VT.getVectorElementType().getSizeInBits() >> 3;
4508
4509   unsigned NumElts = VT.getVectorNumElements();
4510   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4511   unsigned NumLaneElts = NumElts/NumLanes;
4512
4513   int Val = 0;
4514   unsigned i;
4515   for (i = 0; i != NumElts; ++i) {
4516     Val = SVOp->getMaskElt(i);
4517     if (Val >= 0)
4518       break;
4519   }
4520   if (Val >= (int)NumElts)
4521     Val -= NumElts - NumLaneElts;
4522
4523   assert(Val - i > 0 && "PALIGNR imm should be positive");
4524   return (Val - i) * EltSize;
4525 }
4526
4527 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4528   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4529   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4530     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4531
4532   uint64_t Index =
4533     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4534
4535   MVT VecVT = N->getOperand(0).getSimpleValueType();
4536   MVT ElVT = VecVT.getVectorElementType();
4537
4538   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4539   return Index / NumElemsPerChunk;
4540 }
4541
4542 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4543   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4544   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4545     llvm_unreachable("Illegal insert subvector for VINSERT");
4546
4547   uint64_t Index =
4548     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4549
4550   MVT VecVT = N->getSimpleValueType(0);
4551   MVT ElVT = VecVT.getVectorElementType();
4552
4553   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4554   return Index / NumElemsPerChunk;
4555 }
4556
4557 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4558 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4559 /// and VINSERTI128 instructions.
4560 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4561   return getExtractVEXTRACTImmediate(N, 128);
4562 }
4563
4564 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4565 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4566 /// and VINSERTI64x4 instructions.
4567 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4568   return getExtractVEXTRACTImmediate(N, 256);
4569 }
4570
4571 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4572 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4573 /// and VINSERTI128 instructions.
4574 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4575   return getInsertVINSERTImmediate(N, 128);
4576 }
4577
4578 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4579 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4580 /// and VINSERTI64x4 instructions.
4581 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4582   return getInsertVINSERTImmediate(N, 256);
4583 }
4584
4585 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4586 /// constant +0.0.
4587 bool X86::isZeroNode(SDValue Elt) {
4588   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4589     return CN->isNullValue();
4590   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4591     return CFP->getValueAPF().isPosZero();
4592   return false;
4593 }
4594
4595 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4596 /// their permute mask.
4597 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4598                                     SelectionDAG &DAG) {
4599   MVT VT = SVOp->getSimpleValueType(0);
4600   unsigned NumElems = VT.getVectorNumElements();
4601   SmallVector<int, 8> MaskVec;
4602
4603   for (unsigned i = 0; i != NumElems; ++i) {
4604     int Idx = SVOp->getMaskElt(i);
4605     if (Idx >= 0) {
4606       if (Idx < (int)NumElems)
4607         Idx += NumElems;
4608       else
4609         Idx -= NumElems;
4610     }
4611     MaskVec.push_back(Idx);
4612   }
4613   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4614                               SVOp->getOperand(0), &MaskVec[0]);
4615 }
4616
4617 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4618 /// match movhlps. The lower half elements should come from upper half of
4619 /// V1 (and in order), and the upper half elements should come from the upper
4620 /// half of V2 (and in order).
4621 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4622   if (!VT.is128BitVector())
4623     return false;
4624   if (VT.getVectorNumElements() != 4)
4625     return false;
4626   for (unsigned i = 0, e = 2; i != e; ++i)
4627     if (!isUndefOrEqual(Mask[i], i+2))
4628       return false;
4629   for (unsigned i = 2; i != 4; ++i)
4630     if (!isUndefOrEqual(Mask[i], i+4))
4631       return false;
4632   return true;
4633 }
4634
4635 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4636 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4637 /// required.
4638 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4639   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4640     return false;
4641   N = N->getOperand(0).getNode();
4642   if (!ISD::isNON_EXTLoad(N))
4643     return false;
4644   if (LD)
4645     *LD = cast<LoadSDNode>(N);
4646   return true;
4647 }
4648
4649 // Test whether the given value is a vector value which will be legalized
4650 // into a load.
4651 static bool WillBeConstantPoolLoad(SDNode *N) {
4652   if (N->getOpcode() != ISD::BUILD_VECTOR)
4653     return false;
4654
4655   // Check for any non-constant elements.
4656   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4657     switch (N->getOperand(i).getNode()->getOpcode()) {
4658     case ISD::UNDEF:
4659     case ISD::ConstantFP:
4660     case ISD::Constant:
4661       break;
4662     default:
4663       return false;
4664     }
4665
4666   // Vectors of all-zeros and all-ones are materialized with special
4667   // instructions rather than being loaded.
4668   return !ISD::isBuildVectorAllZeros(N) &&
4669          !ISD::isBuildVectorAllOnes(N);
4670 }
4671
4672 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4673 /// match movlp{s|d}. The lower half elements should come from lower half of
4674 /// V1 (and in order), and the upper half elements should come from the upper
4675 /// half of V2 (and in order). And since V1 will become the source of the
4676 /// MOVLP, it must be either a vector load or a scalar load to vector.
4677 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4678                                ArrayRef<int> Mask, MVT VT) {
4679   if (!VT.is128BitVector())
4680     return false;
4681
4682   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4683     return false;
4684   // Is V2 is a vector load, don't do this transformation. We will try to use
4685   // load folding shufps op.
4686   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4687     return false;
4688
4689   unsigned NumElems = VT.getVectorNumElements();
4690
4691   if (NumElems != 2 && NumElems != 4)
4692     return false;
4693   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4694     if (!isUndefOrEqual(Mask[i], i))
4695       return false;
4696   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4697     if (!isUndefOrEqual(Mask[i], i+NumElems))
4698       return false;
4699   return true;
4700 }
4701
4702 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4703 /// all the same.
4704 static bool isSplatVector(SDNode *N) {
4705   if (N->getOpcode() != ISD::BUILD_VECTOR)
4706     return false;
4707
4708   SDValue SplatValue = N->getOperand(0);
4709   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4710     if (N->getOperand(i) != SplatValue)
4711       return false;
4712   return true;
4713 }
4714
4715 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4716 /// to an zero vector.
4717 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4718 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4719   SDValue V1 = N->getOperand(0);
4720   SDValue V2 = N->getOperand(1);
4721   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4722   for (unsigned i = 0; i != NumElems; ++i) {
4723     int Idx = N->getMaskElt(i);
4724     if (Idx >= (int)NumElems) {
4725       unsigned Opc = V2.getOpcode();
4726       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4727         continue;
4728       if (Opc != ISD::BUILD_VECTOR ||
4729           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4730         return false;
4731     } else if (Idx >= 0) {
4732       unsigned Opc = V1.getOpcode();
4733       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4734         continue;
4735       if (Opc != ISD::BUILD_VECTOR ||
4736           !X86::isZeroNode(V1.getOperand(Idx)))
4737         return false;
4738     }
4739   }
4740   return true;
4741 }
4742
4743 /// getZeroVector - Returns a vector of specified type with all zero elements.
4744 ///
4745 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4746                              SelectionDAG &DAG, SDLoc dl) {
4747   assert(VT.isVector() && "Expected a vector type");
4748
4749   // Always build SSE zero vectors as <4 x i32> bitcasted
4750   // to their dest type. This ensures they get CSE'd.
4751   SDValue Vec;
4752   if (VT.is128BitVector()) {  // SSE
4753     if (Subtarget->hasSSE2()) {  // SSE2
4754       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4755       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4756     } else { // SSE1
4757       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4758       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4759     }
4760   } else if (VT.is256BitVector()) { // AVX
4761     if (Subtarget->hasInt256()) { // AVX2
4762       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4763       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4764       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4765                         array_lengthof(Ops));
4766     } else {
4767       // 256-bit logic and arithmetic instructions in AVX are all
4768       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4769       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4770       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4771       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4772                         array_lengthof(Ops));
4773     }
4774   } else if (VT.is512BitVector()) { // AVX-512
4775       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4776       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4777                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4778       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4779   } else
4780     llvm_unreachable("Unexpected vector type");
4781
4782   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4783 }
4784
4785 /// getOnesVector - Returns a vector of specified type with all bits set.
4786 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4787 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4788 /// Then bitcast to their original type, ensuring they get CSE'd.
4789 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4790                              SDLoc dl) {
4791   assert(VT.isVector() && "Expected a vector type");
4792
4793   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4794   SDValue Vec;
4795   if (VT.is256BitVector()) {
4796     if (HasInt256) { // AVX2
4797       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4798       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4799                         array_lengthof(Ops));
4800     } else { // AVX
4801       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4802       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4803     }
4804   } else if (VT.is128BitVector()) {
4805     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4806   } else
4807     llvm_unreachable("Unexpected vector type");
4808
4809   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4810 }
4811
4812 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4813 /// that point to V2 points to its first element.
4814 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4815   for (unsigned i = 0; i != NumElems; ++i) {
4816     if (Mask[i] > (int)NumElems) {
4817       Mask[i] = NumElems;
4818     }
4819   }
4820 }
4821
4822 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4823 /// operation of specified width.
4824 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4825                        SDValue V2) {
4826   unsigned NumElems = VT.getVectorNumElements();
4827   SmallVector<int, 8> Mask;
4828   Mask.push_back(NumElems);
4829   for (unsigned i = 1; i != NumElems; ++i)
4830     Mask.push_back(i);
4831   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4832 }
4833
4834 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4835 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4836                           SDValue V2) {
4837   unsigned NumElems = VT.getVectorNumElements();
4838   SmallVector<int, 8> Mask;
4839   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4840     Mask.push_back(i);
4841     Mask.push_back(i + NumElems);
4842   }
4843   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4844 }
4845
4846 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4847 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4848                           SDValue V2) {
4849   unsigned NumElems = VT.getVectorNumElements();
4850   SmallVector<int, 8> Mask;
4851   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4852     Mask.push_back(i + Half);
4853     Mask.push_back(i + NumElems + Half);
4854   }
4855   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4856 }
4857
4858 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4859 // a generic shuffle instruction because the target has no such instructions.
4860 // Generate shuffles which repeat i16 and i8 several times until they can be
4861 // represented by v4f32 and then be manipulated by target suported shuffles.
4862 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4863   MVT VT = V.getSimpleValueType();
4864   int NumElems = VT.getVectorNumElements();
4865   SDLoc dl(V);
4866
4867   while (NumElems > 4) {
4868     if (EltNo < NumElems/2) {
4869       V = getUnpackl(DAG, dl, VT, V, V);
4870     } else {
4871       V = getUnpackh(DAG, dl, VT, V, V);
4872       EltNo -= NumElems/2;
4873     }
4874     NumElems >>= 1;
4875   }
4876   return V;
4877 }
4878
4879 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4880 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4881   MVT VT = V.getSimpleValueType();
4882   SDLoc dl(V);
4883
4884   if (VT.is128BitVector()) {
4885     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4886     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4887     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4888                              &SplatMask[0]);
4889   } else if (VT.is256BitVector()) {
4890     // To use VPERMILPS to splat scalars, the second half of indicies must
4891     // refer to the higher part, which is a duplication of the lower one,
4892     // because VPERMILPS can only handle in-lane permutations.
4893     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4894                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4895
4896     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4897     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4898                              &SplatMask[0]);
4899   } else
4900     llvm_unreachable("Vector size not supported");
4901
4902   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4903 }
4904
4905 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4906 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4907   MVT SrcVT = SV->getSimpleValueType(0);
4908   SDValue V1 = SV->getOperand(0);
4909   SDLoc dl(SV);
4910
4911   int EltNo = SV->getSplatIndex();
4912   int NumElems = SrcVT.getVectorNumElements();
4913   bool Is256BitVec = SrcVT.is256BitVector();
4914
4915   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4916          "Unknown how to promote splat for type");
4917
4918   // Extract the 128-bit part containing the splat element and update
4919   // the splat element index when it refers to the higher register.
4920   if (Is256BitVec) {
4921     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4922     if (EltNo >= NumElems/2)
4923       EltNo -= NumElems/2;
4924   }
4925
4926   // All i16 and i8 vector types can't be used directly by a generic shuffle
4927   // instruction because the target has no such instruction. Generate shuffles
4928   // which repeat i16 and i8 several times until they fit in i32, and then can
4929   // be manipulated by target suported shuffles.
4930   MVT EltVT = SrcVT.getVectorElementType();
4931   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4932     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4933
4934   // Recreate the 256-bit vector and place the same 128-bit vector
4935   // into the low and high part. This is necessary because we want
4936   // to use VPERM* to shuffle the vectors
4937   if (Is256BitVec) {
4938     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4939   }
4940
4941   return getLegalSplat(DAG, V1, EltNo);
4942 }
4943
4944 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4945 /// vector of zero or undef vector.  This produces a shuffle where the low
4946 /// element of V2 is swizzled into the zero/undef vector, landing at element
4947 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4948 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4949                                            bool IsZero,
4950                                            const X86Subtarget *Subtarget,
4951                                            SelectionDAG &DAG) {
4952   MVT VT = V2.getSimpleValueType();
4953   SDValue V1 = IsZero
4954     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4955   unsigned NumElems = VT.getVectorNumElements();
4956   SmallVector<int, 16> MaskVec;
4957   for (unsigned i = 0; i != NumElems; ++i)
4958     // If this is the insertion idx, put the low elt of V2 here.
4959     MaskVec.push_back(i == Idx ? NumElems : i);
4960   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4961 }
4962
4963 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4964 /// target specific opcode. Returns true if the Mask could be calculated.
4965 /// Sets IsUnary to true if only uses one source.
4966 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4967                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4968   unsigned NumElems = VT.getVectorNumElements();
4969   SDValue ImmN;
4970
4971   IsUnary = false;
4972   switch(N->getOpcode()) {
4973   case X86ISD::SHUFP:
4974     ImmN = N->getOperand(N->getNumOperands()-1);
4975     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4976     break;
4977   case X86ISD::UNPCKH:
4978     DecodeUNPCKHMask(VT, Mask);
4979     break;
4980   case X86ISD::UNPCKL:
4981     DecodeUNPCKLMask(VT, Mask);
4982     break;
4983   case X86ISD::MOVHLPS:
4984     DecodeMOVHLPSMask(NumElems, Mask);
4985     break;
4986   case X86ISD::MOVLHPS:
4987     DecodeMOVLHPSMask(NumElems, Mask);
4988     break;
4989   case X86ISD::PALIGNR:
4990     ImmN = N->getOperand(N->getNumOperands()-1);
4991     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4992     break;
4993   case X86ISD::PSHUFD:
4994   case X86ISD::VPERMILP:
4995     ImmN = N->getOperand(N->getNumOperands()-1);
4996     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4997     IsUnary = true;
4998     break;
4999   case X86ISD::PSHUFHW:
5000     ImmN = N->getOperand(N->getNumOperands()-1);
5001     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5002     IsUnary = true;
5003     break;
5004   case X86ISD::PSHUFLW:
5005     ImmN = N->getOperand(N->getNumOperands()-1);
5006     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5007     IsUnary = true;
5008     break;
5009   case X86ISD::VPERMI:
5010     ImmN = N->getOperand(N->getNumOperands()-1);
5011     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5012     IsUnary = true;
5013     break;
5014   case X86ISD::MOVSS:
5015   case X86ISD::MOVSD: {
5016     // The index 0 always comes from the first element of the second source,
5017     // this is why MOVSS and MOVSD are used in the first place. The other
5018     // elements come from the other positions of the first source vector
5019     Mask.push_back(NumElems);
5020     for (unsigned i = 1; i != NumElems; ++i) {
5021       Mask.push_back(i);
5022     }
5023     break;
5024   }
5025   case X86ISD::VPERM2X128:
5026     ImmN = N->getOperand(N->getNumOperands()-1);
5027     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5028     if (Mask.empty()) return false;
5029     break;
5030   case X86ISD::MOVDDUP:
5031   case X86ISD::MOVLHPD:
5032   case X86ISD::MOVLPD:
5033   case X86ISD::MOVLPS:
5034   case X86ISD::MOVSHDUP:
5035   case X86ISD::MOVSLDUP:
5036     // Not yet implemented
5037     return false;
5038   default: llvm_unreachable("unknown target shuffle node");
5039   }
5040
5041   return true;
5042 }
5043
5044 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5045 /// element of the result of the vector shuffle.
5046 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5047                                    unsigned Depth) {
5048   if (Depth == 6)
5049     return SDValue();  // Limit search depth.
5050
5051   SDValue V = SDValue(N, 0);
5052   EVT VT = V.getValueType();
5053   unsigned Opcode = V.getOpcode();
5054
5055   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5056   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5057     int Elt = SV->getMaskElt(Index);
5058
5059     if (Elt < 0)
5060       return DAG.getUNDEF(VT.getVectorElementType());
5061
5062     unsigned NumElems = VT.getVectorNumElements();
5063     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5064                                          : SV->getOperand(1);
5065     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5066   }
5067
5068   // Recurse into target specific vector shuffles to find scalars.
5069   if (isTargetShuffle(Opcode)) {
5070     MVT ShufVT = V.getSimpleValueType();
5071     unsigned NumElems = ShufVT.getVectorNumElements();
5072     SmallVector<int, 16> ShuffleMask;
5073     bool IsUnary;
5074
5075     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5076       return SDValue();
5077
5078     int Elt = ShuffleMask[Index];
5079     if (Elt < 0)
5080       return DAG.getUNDEF(ShufVT.getVectorElementType());
5081
5082     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5083                                          : N->getOperand(1);
5084     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5085                                Depth+1);
5086   }
5087
5088   // Actual nodes that may contain scalar elements
5089   if (Opcode == ISD::BITCAST) {
5090     V = V.getOperand(0);
5091     EVT SrcVT = V.getValueType();
5092     unsigned NumElems = VT.getVectorNumElements();
5093
5094     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5095       return SDValue();
5096   }
5097
5098   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5099     return (Index == 0) ? V.getOperand(0)
5100                         : DAG.getUNDEF(VT.getVectorElementType());
5101
5102   if (V.getOpcode() == ISD::BUILD_VECTOR)
5103     return V.getOperand(Index);
5104
5105   return SDValue();
5106 }
5107
5108 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5109 /// shuffle operation which come from a consecutively from a zero. The
5110 /// search can start in two different directions, from left or right.
5111 /// We count undefs as zeros until PreferredNum is reached.
5112 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5113                                          unsigned NumElems, bool ZerosFromLeft,
5114                                          SelectionDAG &DAG,
5115                                          unsigned PreferredNum = -1U) {
5116   unsigned NumZeros = 0;
5117   for (unsigned i = 0; i != NumElems; ++i) {
5118     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5119     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5120     if (!Elt.getNode())
5121       break;
5122
5123     if (X86::isZeroNode(Elt))
5124       ++NumZeros;
5125     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5126       NumZeros = std::min(NumZeros + 1, PreferredNum);
5127     else
5128       break;
5129   }
5130
5131   return NumZeros;
5132 }
5133
5134 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5135 /// correspond consecutively to elements from one of the vector operands,
5136 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5137 static
5138 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5139                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5140                               unsigned NumElems, unsigned &OpNum) {
5141   bool SeenV1 = false;
5142   bool SeenV2 = false;
5143
5144   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5145     int Idx = SVOp->getMaskElt(i);
5146     // Ignore undef indicies
5147     if (Idx < 0)
5148       continue;
5149
5150     if (Idx < (int)NumElems)
5151       SeenV1 = true;
5152     else
5153       SeenV2 = true;
5154
5155     // Only accept consecutive elements from the same vector
5156     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5157       return false;
5158   }
5159
5160   OpNum = SeenV1 ? 0 : 1;
5161   return true;
5162 }
5163
5164 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5165 /// logical left shift of a vector.
5166 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5167                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5168   unsigned NumElems =
5169     SVOp->getSimpleValueType(0).getVectorNumElements();
5170   unsigned NumZeros = getNumOfConsecutiveZeros(
5171       SVOp, NumElems, false /* check zeros from right */, DAG,
5172       SVOp->getMaskElt(0));
5173   unsigned OpSrc;
5174
5175   if (!NumZeros)
5176     return false;
5177
5178   // Considering the elements in the mask that are not consecutive zeros,
5179   // check if they consecutively come from only one of the source vectors.
5180   //
5181   //               V1 = {X, A, B, C}     0
5182   //                         \  \  \    /
5183   //   vector_shuffle V1, V2 <1, 2, 3, X>
5184   //
5185   if (!isShuffleMaskConsecutive(SVOp,
5186             0,                   // Mask Start Index
5187             NumElems-NumZeros,   // Mask End Index(exclusive)
5188             NumZeros,            // Where to start looking in the src vector
5189             NumElems,            // Number of elements in vector
5190             OpSrc))              // Which source operand ?
5191     return false;
5192
5193   isLeft = false;
5194   ShAmt = NumZeros;
5195   ShVal = SVOp->getOperand(OpSrc);
5196   return true;
5197 }
5198
5199 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5200 /// logical left shift of a vector.
5201 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5202                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5203   unsigned NumElems =
5204     SVOp->getSimpleValueType(0).getVectorNumElements();
5205   unsigned NumZeros = getNumOfConsecutiveZeros(
5206       SVOp, NumElems, true /* check zeros from left */, DAG,
5207       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5208   unsigned OpSrc;
5209
5210   if (!NumZeros)
5211     return false;
5212
5213   // Considering the elements in the mask that are not consecutive zeros,
5214   // check if they consecutively come from only one of the source vectors.
5215   //
5216   //                           0    { A, B, X, X } = V2
5217   //                          / \    /  /
5218   //   vector_shuffle V1, V2 <X, X, 4, 5>
5219   //
5220   if (!isShuffleMaskConsecutive(SVOp,
5221             NumZeros,     // Mask Start Index
5222             NumElems,     // Mask End Index(exclusive)
5223             0,            // Where to start looking in the src vector
5224             NumElems,     // Number of elements in vector
5225             OpSrc))       // Which source operand ?
5226     return false;
5227
5228   isLeft = true;
5229   ShAmt = NumZeros;
5230   ShVal = SVOp->getOperand(OpSrc);
5231   return true;
5232 }
5233
5234 /// isVectorShift - Returns true if the shuffle can be implemented as a
5235 /// logical left or right shift of a vector.
5236 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5237                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5238   // Although the logic below support any bitwidth size, there are no
5239   // shift instructions which handle more than 128-bit vectors.
5240   if (!SVOp->getSimpleValueType(0).is128BitVector())
5241     return false;
5242
5243   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5244       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5245     return true;
5246
5247   return false;
5248 }
5249
5250 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5251 ///
5252 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5253                                        unsigned NumNonZero, unsigned NumZero,
5254                                        SelectionDAG &DAG,
5255                                        const X86Subtarget* Subtarget,
5256                                        const TargetLowering &TLI) {
5257   if (NumNonZero > 8)
5258     return SDValue();
5259
5260   SDLoc dl(Op);
5261   SDValue V(0, 0);
5262   bool First = true;
5263   for (unsigned i = 0; i < 16; ++i) {
5264     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5265     if (ThisIsNonZero && First) {
5266       if (NumZero)
5267         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5268       else
5269         V = DAG.getUNDEF(MVT::v8i16);
5270       First = false;
5271     }
5272
5273     if ((i & 1) != 0) {
5274       SDValue ThisElt(0, 0), LastElt(0, 0);
5275       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5276       if (LastIsNonZero) {
5277         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5278                               MVT::i16, Op.getOperand(i-1));
5279       }
5280       if (ThisIsNonZero) {
5281         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5282         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5283                               ThisElt, DAG.getConstant(8, MVT::i8));
5284         if (LastIsNonZero)
5285           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5286       } else
5287         ThisElt = LastElt;
5288
5289       if (ThisElt.getNode())
5290         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5291                         DAG.getIntPtrConstant(i/2));
5292     }
5293   }
5294
5295   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5296 }
5297
5298 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5299 ///
5300 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5301                                      unsigned NumNonZero, unsigned NumZero,
5302                                      SelectionDAG &DAG,
5303                                      const X86Subtarget* Subtarget,
5304                                      const TargetLowering &TLI) {
5305   if (NumNonZero > 4)
5306     return SDValue();
5307
5308   SDLoc dl(Op);
5309   SDValue V(0, 0);
5310   bool First = true;
5311   for (unsigned i = 0; i < 8; ++i) {
5312     bool isNonZero = (NonZeros & (1 << i)) != 0;
5313     if (isNonZero) {
5314       if (First) {
5315         if (NumZero)
5316           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5317         else
5318           V = DAG.getUNDEF(MVT::v8i16);
5319         First = false;
5320       }
5321       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5322                       MVT::v8i16, V, Op.getOperand(i),
5323                       DAG.getIntPtrConstant(i));
5324     }
5325   }
5326
5327   return V;
5328 }
5329
5330 /// getVShift - Return a vector logical shift node.
5331 ///
5332 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5333                          unsigned NumBits, SelectionDAG &DAG,
5334                          const TargetLowering &TLI, SDLoc dl) {
5335   assert(VT.is128BitVector() && "Unknown type for VShift");
5336   EVT ShVT = MVT::v2i64;
5337   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5338   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5339   return DAG.getNode(ISD::BITCAST, dl, VT,
5340                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5341                              DAG.getConstant(NumBits,
5342                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5343 }
5344
5345 static SDValue
5346 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5347
5348   // Check if the scalar load can be widened into a vector load. And if
5349   // the address is "base + cst" see if the cst can be "absorbed" into
5350   // the shuffle mask.
5351   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5352     SDValue Ptr = LD->getBasePtr();
5353     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5354       return SDValue();
5355     EVT PVT = LD->getValueType(0);
5356     if (PVT != MVT::i32 && PVT != MVT::f32)
5357       return SDValue();
5358
5359     int FI = -1;
5360     int64_t Offset = 0;
5361     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5362       FI = FINode->getIndex();
5363       Offset = 0;
5364     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5365                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5366       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5367       Offset = Ptr.getConstantOperandVal(1);
5368       Ptr = Ptr.getOperand(0);
5369     } else {
5370       return SDValue();
5371     }
5372
5373     // FIXME: 256-bit vector instructions don't require a strict alignment,
5374     // improve this code to support it better.
5375     unsigned RequiredAlign = VT.getSizeInBits()/8;
5376     SDValue Chain = LD->getChain();
5377     // Make sure the stack object alignment is at least 16 or 32.
5378     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5379     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5380       if (MFI->isFixedObjectIndex(FI)) {
5381         // Can't change the alignment. FIXME: It's possible to compute
5382         // the exact stack offset and reference FI + adjust offset instead.
5383         // If someone *really* cares about this. That's the way to implement it.
5384         return SDValue();
5385       } else {
5386         MFI->setObjectAlignment(FI, RequiredAlign);
5387       }
5388     }
5389
5390     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5391     // Ptr + (Offset & ~15).
5392     if (Offset < 0)
5393       return SDValue();
5394     if ((Offset % RequiredAlign) & 3)
5395       return SDValue();
5396     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5397     if (StartOffset)
5398       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5399                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5400
5401     int EltNo = (Offset - StartOffset) >> 2;
5402     unsigned NumElems = VT.getVectorNumElements();
5403
5404     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5405     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5406                              LD->getPointerInfo().getWithOffset(StartOffset),
5407                              false, false, false, 0);
5408
5409     SmallVector<int, 8> Mask;
5410     for (unsigned i = 0; i != NumElems; ++i)
5411       Mask.push_back(EltNo);
5412
5413     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5414   }
5415
5416   return SDValue();
5417 }
5418
5419 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5420 /// vector of type 'VT', see if the elements can be replaced by a single large
5421 /// load which has the same value as a build_vector whose operands are 'elts'.
5422 ///
5423 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5424 ///
5425 /// FIXME: we'd also like to handle the case where the last elements are zero
5426 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5427 /// There's even a handy isZeroNode for that purpose.
5428 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5429                                         SDLoc &DL, SelectionDAG &DAG,
5430                                         bool isAfterLegalize) {
5431   EVT EltVT = VT.getVectorElementType();
5432   unsigned NumElems = Elts.size();
5433
5434   LoadSDNode *LDBase = NULL;
5435   unsigned LastLoadedElt = -1U;
5436
5437   // For each element in the initializer, see if we've found a load or an undef.
5438   // If we don't find an initial load element, or later load elements are
5439   // non-consecutive, bail out.
5440   for (unsigned i = 0; i < NumElems; ++i) {
5441     SDValue Elt = Elts[i];
5442
5443     if (!Elt.getNode() ||
5444         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5445       return SDValue();
5446     if (!LDBase) {
5447       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5448         return SDValue();
5449       LDBase = cast<LoadSDNode>(Elt.getNode());
5450       LastLoadedElt = i;
5451       continue;
5452     }
5453     if (Elt.getOpcode() == ISD::UNDEF)
5454       continue;
5455
5456     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5457     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5458       return SDValue();
5459     LastLoadedElt = i;
5460   }
5461
5462   // If we have found an entire vector of loads and undefs, then return a large
5463   // load of the entire vector width starting at the base pointer.  If we found
5464   // consecutive loads for the low half, generate a vzext_load node.
5465   if (LastLoadedElt == NumElems - 1) {
5466
5467     if (isAfterLegalize &&
5468         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5469       return SDValue();
5470
5471     SDValue NewLd = SDValue();
5472
5473     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5474       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5475                           LDBase->getPointerInfo(),
5476                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5477                           LDBase->isInvariant(), 0);
5478     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5479                         LDBase->getPointerInfo(),
5480                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5481                         LDBase->isInvariant(), LDBase->getAlignment());
5482
5483     if (LDBase->hasAnyUseOfValue(1)) {
5484       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5485                                      SDValue(LDBase, 1),
5486                                      SDValue(NewLd.getNode(), 1));
5487       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5488       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5489                              SDValue(NewLd.getNode(), 1));
5490     }
5491
5492     return NewLd;
5493   }
5494   if (NumElems == 4 && LastLoadedElt == 1 &&
5495       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5496     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5497     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5498     SDValue ResNode =
5499         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5500                                 array_lengthof(Ops), MVT::i64,
5501                                 LDBase->getPointerInfo(),
5502                                 LDBase->getAlignment(),
5503                                 false/*isVolatile*/, true/*ReadMem*/,
5504                                 false/*WriteMem*/);
5505
5506     // Make sure the newly-created LOAD is in the same position as LDBase in
5507     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5508     // update uses of LDBase's output chain to use the TokenFactor.
5509     if (LDBase->hasAnyUseOfValue(1)) {
5510       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5511                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5512       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5513       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5514                              SDValue(ResNode.getNode(), 1));
5515     }
5516
5517     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5518   }
5519   return SDValue();
5520 }
5521
5522 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5523 /// to generate a splat value for the following cases:
5524 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5525 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5526 /// a scalar load, or a constant.
5527 /// The VBROADCAST node is returned when a pattern is found,
5528 /// or SDValue() otherwise.
5529 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5530                                     SelectionDAG &DAG) {
5531   if (!Subtarget->hasFp256())
5532     return SDValue();
5533
5534   MVT VT = Op.getSimpleValueType();
5535   SDLoc dl(Op);
5536
5537   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5538          "Unsupported vector type for broadcast.");
5539
5540   SDValue Ld;
5541   bool ConstSplatVal;
5542
5543   switch (Op.getOpcode()) {
5544     default:
5545       // Unknown pattern found.
5546       return SDValue();
5547
5548     case ISD::BUILD_VECTOR: {
5549       // The BUILD_VECTOR node must be a splat.
5550       if (!isSplatVector(Op.getNode()))
5551         return SDValue();
5552
5553       Ld = Op.getOperand(0);
5554       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5555                      Ld.getOpcode() == ISD::ConstantFP);
5556
5557       // The suspected load node has several users. Make sure that all
5558       // of its users are from the BUILD_VECTOR node.
5559       // Constants may have multiple users.
5560       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5561         return SDValue();
5562       break;
5563     }
5564
5565     case ISD::VECTOR_SHUFFLE: {
5566       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5567
5568       // Shuffles must have a splat mask where the first element is
5569       // broadcasted.
5570       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5571         return SDValue();
5572
5573       SDValue Sc = Op.getOperand(0);
5574       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5575           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5576
5577         if (!Subtarget->hasInt256())
5578           return SDValue();
5579
5580         // Use the register form of the broadcast instruction available on AVX2.
5581         if (VT.getSizeInBits() >= 256)
5582           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5583         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5584       }
5585
5586       Ld = Sc.getOperand(0);
5587       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5588                        Ld.getOpcode() == ISD::ConstantFP);
5589
5590       // The scalar_to_vector node and the suspected
5591       // load node must have exactly one user.
5592       // Constants may have multiple users.
5593
5594       // AVX-512 has register version of the broadcast
5595       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5596         Ld.getValueType().getSizeInBits() >= 32;
5597       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5598           !hasRegVer))
5599         return SDValue();
5600       break;
5601     }
5602   }
5603
5604   bool IsGE256 = (VT.getSizeInBits() >= 256);
5605
5606   // Handle the broadcasting a single constant scalar from the constant pool
5607   // into a vector. On Sandybridge it is still better to load a constant vector
5608   // from the constant pool and not to broadcast it from a scalar.
5609   if (ConstSplatVal && Subtarget->hasInt256()) {
5610     EVT CVT = Ld.getValueType();
5611     assert(!CVT.isVector() && "Must not broadcast a vector type");
5612     unsigned ScalarSize = CVT.getSizeInBits();
5613
5614     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5615       const Constant *C = 0;
5616       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5617         C = CI->getConstantIntValue();
5618       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5619         C = CF->getConstantFPValue();
5620
5621       assert(C && "Invalid constant type");
5622
5623       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5624       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5625       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5626       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5627                        MachinePointerInfo::getConstantPool(),
5628                        false, false, false, Alignment);
5629
5630       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5631     }
5632   }
5633
5634   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5635   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5636
5637   // Handle AVX2 in-register broadcasts.
5638   if (!IsLoad && Subtarget->hasInt256() &&
5639       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5640     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5641
5642   // The scalar source must be a normal load.
5643   if (!IsLoad)
5644     return SDValue();
5645
5646   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5647     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5648
5649   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5650   // double since there is no vbroadcastsd xmm
5651   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5652     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5653       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5654   }
5655
5656   // Unsupported broadcast.
5657   return SDValue();
5658 }
5659
5660 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5661   MVT VT = Op.getSimpleValueType();
5662
5663   // Skip if insert_vec_elt is not supported.
5664   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5665   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5666     return SDValue();
5667
5668   SDLoc DL(Op);
5669   unsigned NumElems = Op.getNumOperands();
5670
5671   SDValue VecIn1;
5672   SDValue VecIn2;
5673   SmallVector<unsigned, 4> InsertIndices;
5674   SmallVector<int, 8> Mask(NumElems, -1);
5675
5676   for (unsigned i = 0; i != NumElems; ++i) {
5677     unsigned Opc = Op.getOperand(i).getOpcode();
5678
5679     if (Opc == ISD::UNDEF)
5680       continue;
5681
5682     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5683       // Quit if more than 1 elements need inserting.
5684       if (InsertIndices.size() > 1)
5685         return SDValue();
5686
5687       InsertIndices.push_back(i);
5688       continue;
5689     }
5690
5691     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5692     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5693
5694     // Quit if extracted from vector of different type.
5695     if (ExtractedFromVec.getValueType() != VT)
5696       return SDValue();
5697
5698     // Quit if non-constant index.
5699     if (!isa<ConstantSDNode>(ExtIdx))
5700       return SDValue();
5701
5702     if (VecIn1.getNode() == 0)
5703       VecIn1 = ExtractedFromVec;
5704     else if (VecIn1 != ExtractedFromVec) {
5705       if (VecIn2.getNode() == 0)
5706         VecIn2 = ExtractedFromVec;
5707       else if (VecIn2 != ExtractedFromVec)
5708         // Quit if more than 2 vectors to shuffle
5709         return SDValue();
5710     }
5711
5712     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5713
5714     if (ExtractedFromVec == VecIn1)
5715       Mask[i] = Idx;
5716     else if (ExtractedFromVec == VecIn2)
5717       Mask[i] = Idx + NumElems;
5718   }
5719
5720   if (VecIn1.getNode() == 0)
5721     return SDValue();
5722
5723   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5724   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5725   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5726     unsigned Idx = InsertIndices[i];
5727     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5728                      DAG.getIntPtrConstant(Idx));
5729   }
5730
5731   return NV;
5732 }
5733
5734 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5735 SDValue
5736 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5737
5738   MVT VT = Op.getSimpleValueType();
5739   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5740          "Unexpected type in LowerBUILD_VECTORvXi1!");
5741
5742   SDLoc dl(Op);
5743   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5744     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5745     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5746                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5747     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5748                        Ops, VT.getVectorNumElements());
5749   }
5750
5751   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5752     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5753     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5754                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5755     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5756                        Ops, VT.getVectorNumElements());
5757   }
5758
5759   bool AllContants = true;
5760   uint64_t Immediate = 0;
5761   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5762     SDValue In = Op.getOperand(idx);
5763     if (In.getOpcode() == ISD::UNDEF)
5764       continue;
5765     if (!isa<ConstantSDNode>(In)) {
5766       AllContants = false;
5767       break;
5768     }
5769     if (cast<ConstantSDNode>(In)->getZExtValue())
5770       Immediate |= (1ULL << idx);
5771   }
5772
5773   if (AllContants) {
5774     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5775       DAG.getConstant(Immediate, MVT::i16));
5776     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5777                        DAG.getIntPtrConstant(0));
5778   }
5779
5780   // Splat vector (with undefs)
5781   SDValue In = Op.getOperand(0);
5782   for (unsigned i = 1, e = Op.getNumOperands(); i != e; ++i) {
5783     if (Op.getOperand(i) != In && Op.getOperand(i).getOpcode() != ISD::UNDEF)
5784       llvm_unreachable("Unsupported predicate operation");
5785   }
5786
5787   SDValue EFLAGS, X86CC;
5788   if (In.getOpcode() == ISD::SETCC) {
5789     SDValue Op0 = In.getOperand(0);
5790     SDValue Op1 = In.getOperand(1);
5791     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5792     bool isFP = Op1.getValueType().isFloatingPoint();
5793     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5794
5795     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5796
5797     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5798     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5799     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5800   } else if (In.getOpcode() == X86ISD::SETCC) {
5801     X86CC = In.getOperand(0);
5802     EFLAGS = In.getOperand(1);
5803   } else {
5804     // The algorithm:
5805     //   Bit1 = In & 0x1
5806     //   if (Bit1 != 0)
5807     //     ZF = 0
5808     //   else
5809     //     ZF = 1
5810     //   if (ZF == 0)
5811     //     res = allOnes ### CMOVNE -1, %res
5812     //   else
5813     //     res = allZero
5814     MVT InVT = In.getSimpleValueType();
5815     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5816     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5817     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5818   }
5819
5820   if (VT == MVT::v16i1) {
5821     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5822     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5823     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5824           Cst0, Cst1, X86CC, EFLAGS);
5825     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5826   }
5827
5828   if (VT == MVT::v8i1) {
5829     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5830     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5831     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5832           Cst0, Cst1, X86CC, EFLAGS);
5833     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5834     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5835   }
5836   llvm_unreachable("Unsupported predicate operation");
5837 }
5838
5839 SDValue
5840 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5841   SDLoc dl(Op);
5842
5843   MVT VT = Op.getSimpleValueType();
5844   MVT ExtVT = VT.getVectorElementType();
5845   unsigned NumElems = Op.getNumOperands();
5846
5847   // Generate vectors for predicate vectors.
5848   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5849     return LowerBUILD_VECTORvXi1(Op, DAG);
5850
5851   // Vectors containing all zeros can be matched by pxor and xorps later
5852   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5853     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5854     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5855     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5856       return Op;
5857
5858     return getZeroVector(VT, Subtarget, DAG, dl);
5859   }
5860
5861   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5862   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5863   // vpcmpeqd on 256-bit vectors.
5864   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5865     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5866       return Op;
5867
5868     if (!VT.is512BitVector())
5869       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5870   }
5871
5872   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5873   if (Broadcast.getNode())
5874     return Broadcast;
5875
5876   unsigned EVTBits = ExtVT.getSizeInBits();
5877
5878   unsigned NumZero  = 0;
5879   unsigned NumNonZero = 0;
5880   unsigned NonZeros = 0;
5881   bool IsAllConstants = true;
5882   SmallSet<SDValue, 8> Values;
5883   for (unsigned i = 0; i < NumElems; ++i) {
5884     SDValue Elt = Op.getOperand(i);
5885     if (Elt.getOpcode() == ISD::UNDEF)
5886       continue;
5887     Values.insert(Elt);
5888     if (Elt.getOpcode() != ISD::Constant &&
5889         Elt.getOpcode() != ISD::ConstantFP)
5890       IsAllConstants = false;
5891     if (X86::isZeroNode(Elt))
5892       NumZero++;
5893     else {
5894       NonZeros |= (1 << i);
5895       NumNonZero++;
5896     }
5897   }
5898
5899   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5900   if (NumNonZero == 0)
5901     return DAG.getUNDEF(VT);
5902
5903   // Special case for single non-zero, non-undef, element.
5904   if (NumNonZero == 1) {
5905     unsigned Idx = countTrailingZeros(NonZeros);
5906     SDValue Item = Op.getOperand(Idx);
5907
5908     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5909     // the value are obviously zero, truncate the value to i32 and do the
5910     // insertion that way.  Only do this if the value is non-constant or if the
5911     // value is a constant being inserted into element 0.  It is cheaper to do
5912     // a constant pool load than it is to do a movd + shuffle.
5913     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5914         (!IsAllConstants || Idx == 0)) {
5915       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5916         // Handle SSE only.
5917         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5918         EVT VecVT = MVT::v4i32;
5919         unsigned VecElts = 4;
5920
5921         // Truncate the value (which may itself be a constant) to i32, and
5922         // convert it to a vector with movd (S2V+shuffle to zero extend).
5923         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5924         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5925         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5926
5927         // Now we have our 32-bit value zero extended in the low element of
5928         // a vector.  If Idx != 0, swizzle it into place.
5929         if (Idx != 0) {
5930           SmallVector<int, 4> Mask;
5931           Mask.push_back(Idx);
5932           for (unsigned i = 1; i != VecElts; ++i)
5933             Mask.push_back(i);
5934           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5935                                       &Mask[0]);
5936         }
5937         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5938       }
5939     }
5940
5941     // If we have a constant or non-constant insertion into the low element of
5942     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5943     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5944     // depending on what the source datatype is.
5945     if (Idx == 0) {
5946       if (NumZero == 0)
5947         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5948
5949       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5950           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5951         if (VT.is256BitVector() || VT.is512BitVector()) {
5952           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5953           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5954                              Item, DAG.getIntPtrConstant(0));
5955         }
5956         assert(VT.is128BitVector() && "Expected an SSE value type!");
5957         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5958         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5959         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5960       }
5961
5962       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5963         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5964         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5965         if (VT.is256BitVector()) {
5966           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5967           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5968         } else {
5969           assert(VT.is128BitVector() && "Expected an SSE value type!");
5970           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5971         }
5972         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5973       }
5974     }
5975
5976     // Is it a vector logical left shift?
5977     if (NumElems == 2 && Idx == 1 &&
5978         X86::isZeroNode(Op.getOperand(0)) &&
5979         !X86::isZeroNode(Op.getOperand(1))) {
5980       unsigned NumBits = VT.getSizeInBits();
5981       return getVShift(true, VT,
5982                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5983                                    VT, Op.getOperand(1)),
5984                        NumBits/2, DAG, *this, dl);
5985     }
5986
5987     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5988       return SDValue();
5989
5990     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5991     // is a non-constant being inserted into an element other than the low one,
5992     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5993     // movd/movss) to move this into the low element, then shuffle it into
5994     // place.
5995     if (EVTBits == 32) {
5996       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5997
5998       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5999       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6000       SmallVector<int, 8> MaskVec;
6001       for (unsigned i = 0; i != NumElems; ++i)
6002         MaskVec.push_back(i == Idx ? 0 : 1);
6003       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6004     }
6005   }
6006
6007   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6008   if (Values.size() == 1) {
6009     if (EVTBits == 32) {
6010       // Instead of a shuffle like this:
6011       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6012       // Check if it's possible to issue this instead.
6013       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6014       unsigned Idx = countTrailingZeros(NonZeros);
6015       SDValue Item = Op.getOperand(Idx);
6016       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6017         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6018     }
6019     return SDValue();
6020   }
6021
6022   // A vector full of immediates; various special cases are already
6023   // handled, so this is best done with a single constant-pool load.
6024   if (IsAllConstants)
6025     return SDValue();
6026
6027   // For AVX-length vectors, build the individual 128-bit pieces and use
6028   // shuffles to put them in place.
6029   if (VT.is256BitVector()) {
6030     SmallVector<SDValue, 32> V;
6031     for (unsigned i = 0; i != NumElems; ++i)
6032       V.push_back(Op.getOperand(i));
6033
6034     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6035
6036     // Build both the lower and upper subvector.
6037     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6038     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6039                                 NumElems/2);
6040
6041     // Recreate the wider vector with the lower and upper part.
6042     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6043   }
6044
6045   // Let legalizer expand 2-wide build_vectors.
6046   if (EVTBits == 64) {
6047     if (NumNonZero == 1) {
6048       // One half is zero or undef.
6049       unsigned Idx = countTrailingZeros(NonZeros);
6050       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6051                                  Op.getOperand(Idx));
6052       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6053     }
6054     return SDValue();
6055   }
6056
6057   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6058   if (EVTBits == 8 && NumElems == 16) {
6059     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6060                                         Subtarget, *this);
6061     if (V.getNode()) return V;
6062   }
6063
6064   if (EVTBits == 16 && NumElems == 8) {
6065     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6066                                       Subtarget, *this);
6067     if (V.getNode()) return V;
6068   }
6069
6070   // If element VT is == 32 bits, turn it into a number of shuffles.
6071   SmallVector<SDValue, 8> V(NumElems);
6072   if (NumElems == 4 && NumZero > 0) {
6073     for (unsigned i = 0; i < 4; ++i) {
6074       bool isZero = !(NonZeros & (1 << i));
6075       if (isZero)
6076         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6077       else
6078         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6079     }
6080
6081     for (unsigned i = 0; i < 2; ++i) {
6082       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6083         default: break;
6084         case 0:
6085           V[i] = V[i*2];  // Must be a zero vector.
6086           break;
6087         case 1:
6088           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6089           break;
6090         case 2:
6091           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6092           break;
6093         case 3:
6094           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6095           break;
6096       }
6097     }
6098
6099     bool Reverse1 = (NonZeros & 0x3) == 2;
6100     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6101     int MaskVec[] = {
6102       Reverse1 ? 1 : 0,
6103       Reverse1 ? 0 : 1,
6104       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6105       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6106     };
6107     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6108   }
6109
6110   if (Values.size() > 1 && VT.is128BitVector()) {
6111     // Check for a build vector of consecutive loads.
6112     for (unsigned i = 0; i < NumElems; ++i)
6113       V[i] = Op.getOperand(i);
6114
6115     // Check for elements which are consecutive loads.
6116     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6117     if (LD.getNode())
6118       return LD;
6119
6120     // Check for a build vector from mostly shuffle plus few inserting.
6121     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6122     if (Sh.getNode())
6123       return Sh;
6124
6125     // For SSE 4.1, use insertps to put the high elements into the low element.
6126     if (getSubtarget()->hasSSE41()) {
6127       SDValue Result;
6128       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6129         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6130       else
6131         Result = DAG.getUNDEF(VT);
6132
6133       for (unsigned i = 1; i < NumElems; ++i) {
6134         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6135         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6136                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6137       }
6138       return Result;
6139     }
6140
6141     // Otherwise, expand into a number of unpckl*, start by extending each of
6142     // our (non-undef) elements to the full vector width with the element in the
6143     // bottom slot of the vector (which generates no code for SSE).
6144     for (unsigned i = 0; i < NumElems; ++i) {
6145       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6146         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6147       else
6148         V[i] = DAG.getUNDEF(VT);
6149     }
6150
6151     // Next, we iteratively mix elements, e.g. for v4f32:
6152     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6153     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6154     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6155     unsigned EltStride = NumElems >> 1;
6156     while (EltStride != 0) {
6157       for (unsigned i = 0; i < EltStride; ++i) {
6158         // If V[i+EltStride] is undef and this is the first round of mixing,
6159         // then it is safe to just drop this shuffle: V[i] is already in the
6160         // right place, the one element (since it's the first round) being
6161         // inserted as undef can be dropped.  This isn't safe for successive
6162         // rounds because they will permute elements within both vectors.
6163         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6164             EltStride == NumElems/2)
6165           continue;
6166
6167         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6168       }
6169       EltStride >>= 1;
6170     }
6171     return V[0];
6172   }
6173   return SDValue();
6174 }
6175
6176 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6177 // to create 256-bit vectors from two other 128-bit ones.
6178 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6179   SDLoc dl(Op);
6180   MVT ResVT = Op.getSimpleValueType();
6181
6182   assert((ResVT.is256BitVector() ||
6183           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6184
6185   SDValue V1 = Op.getOperand(0);
6186   SDValue V2 = Op.getOperand(1);
6187   unsigned NumElems = ResVT.getVectorNumElements();
6188   if(ResVT.is256BitVector())
6189     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6190
6191   if (Op.getNumOperands() == 4) {
6192     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6193                                 ResVT.getVectorNumElements()/2);
6194     SDValue V3 = Op.getOperand(2);
6195     SDValue V4 = Op.getOperand(3);
6196     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6197       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6198   }
6199   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6200 }
6201
6202 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6203   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6204   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6205          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6206           Op.getNumOperands() == 4)));
6207
6208   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6209   // from two other 128-bit ones.
6210
6211   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6212   return LowerAVXCONCAT_VECTORS(Op, DAG);
6213 }
6214
6215 // Try to lower a shuffle node into a simple blend instruction.
6216 static SDValue
6217 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6218                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6219   SDValue V1 = SVOp->getOperand(0);
6220   SDValue V2 = SVOp->getOperand(1);
6221   SDLoc dl(SVOp);
6222   MVT VT = SVOp->getSimpleValueType(0);
6223   MVT EltVT = VT.getVectorElementType();
6224   unsigned NumElems = VT.getVectorNumElements();
6225
6226   // There is no blend with immediate in AVX-512.
6227   if (VT.is512BitVector())
6228     return SDValue();
6229
6230   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6231     return SDValue();
6232   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6233     return SDValue();
6234
6235   // Check the mask for BLEND and build the value.
6236   unsigned MaskValue = 0;
6237   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6238   unsigned NumLanes = (NumElems-1)/8 + 1;
6239   unsigned NumElemsInLane = NumElems / NumLanes;
6240
6241   // Blend for v16i16 should be symetric for the both lanes.
6242   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6243
6244     int SndLaneEltIdx = (NumLanes == 2) ?
6245       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6246     int EltIdx = SVOp->getMaskElt(i);
6247
6248     if ((EltIdx < 0 || EltIdx == (int)i) &&
6249         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6250       continue;
6251
6252     if (((unsigned)EltIdx == (i + NumElems)) &&
6253         (SndLaneEltIdx < 0 ||
6254          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6255       MaskValue |= (1<<i);
6256     else
6257       return SDValue();
6258   }
6259
6260   // Convert i32 vectors to floating point if it is not AVX2.
6261   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6262   MVT BlendVT = VT;
6263   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6264     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6265                                NumElems);
6266     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6267     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6268   }
6269
6270   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6271                             DAG.getConstant(MaskValue, MVT::i32));
6272   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6273 }
6274
6275 // v8i16 shuffles - Prefer shuffles in the following order:
6276 // 1. [all]   pshuflw, pshufhw, optional move
6277 // 2. [ssse3] 1 x pshufb
6278 // 3. [ssse3] 2 x pshufb + 1 x por
6279 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6280 static SDValue
6281 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6282                          SelectionDAG &DAG) {
6283   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6284   SDValue V1 = SVOp->getOperand(0);
6285   SDValue V2 = SVOp->getOperand(1);
6286   SDLoc dl(SVOp);
6287   SmallVector<int, 8> MaskVals;
6288
6289   // Determine if more than 1 of the words in each of the low and high quadwords
6290   // of the result come from the same quadword of one of the two inputs.  Undef
6291   // mask values count as coming from any quadword, for better codegen.
6292   unsigned LoQuad[] = { 0, 0, 0, 0 };
6293   unsigned HiQuad[] = { 0, 0, 0, 0 };
6294   std::bitset<4> InputQuads;
6295   for (unsigned i = 0; i < 8; ++i) {
6296     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6297     int EltIdx = SVOp->getMaskElt(i);
6298     MaskVals.push_back(EltIdx);
6299     if (EltIdx < 0) {
6300       ++Quad[0];
6301       ++Quad[1];
6302       ++Quad[2];
6303       ++Quad[3];
6304       continue;
6305     }
6306     ++Quad[EltIdx / 4];
6307     InputQuads.set(EltIdx / 4);
6308   }
6309
6310   int BestLoQuad = -1;
6311   unsigned MaxQuad = 1;
6312   for (unsigned i = 0; i < 4; ++i) {
6313     if (LoQuad[i] > MaxQuad) {
6314       BestLoQuad = i;
6315       MaxQuad = LoQuad[i];
6316     }
6317   }
6318
6319   int BestHiQuad = -1;
6320   MaxQuad = 1;
6321   for (unsigned i = 0; i < 4; ++i) {
6322     if (HiQuad[i] > MaxQuad) {
6323       BestHiQuad = i;
6324       MaxQuad = HiQuad[i];
6325     }
6326   }
6327
6328   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6329   // of the two input vectors, shuffle them into one input vector so only a
6330   // single pshufb instruction is necessary. If There are more than 2 input
6331   // quads, disable the next transformation since it does not help SSSE3.
6332   bool V1Used = InputQuads[0] || InputQuads[1];
6333   bool V2Used = InputQuads[2] || InputQuads[3];
6334   if (Subtarget->hasSSSE3()) {
6335     if (InputQuads.count() == 2 && V1Used && V2Used) {
6336       BestLoQuad = InputQuads[0] ? 0 : 1;
6337       BestHiQuad = InputQuads[2] ? 2 : 3;
6338     }
6339     if (InputQuads.count() > 2) {
6340       BestLoQuad = -1;
6341       BestHiQuad = -1;
6342     }
6343   }
6344
6345   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6346   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6347   // words from all 4 input quadwords.
6348   SDValue NewV;
6349   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6350     int MaskV[] = {
6351       BestLoQuad < 0 ? 0 : BestLoQuad,
6352       BestHiQuad < 0 ? 1 : BestHiQuad
6353     };
6354     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6355                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6356                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6357     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6358
6359     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6360     // source words for the shuffle, to aid later transformations.
6361     bool AllWordsInNewV = true;
6362     bool InOrder[2] = { true, true };
6363     for (unsigned i = 0; i != 8; ++i) {
6364       int idx = MaskVals[i];
6365       if (idx != (int)i)
6366         InOrder[i/4] = false;
6367       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6368         continue;
6369       AllWordsInNewV = false;
6370       break;
6371     }
6372
6373     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6374     if (AllWordsInNewV) {
6375       for (int i = 0; i != 8; ++i) {
6376         int idx = MaskVals[i];
6377         if (idx < 0)
6378           continue;
6379         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6380         if ((idx != i) && idx < 4)
6381           pshufhw = false;
6382         if ((idx != i) && idx > 3)
6383           pshuflw = false;
6384       }
6385       V1 = NewV;
6386       V2Used = false;
6387       BestLoQuad = 0;
6388       BestHiQuad = 1;
6389     }
6390
6391     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6392     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6393     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6394       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6395       unsigned TargetMask = 0;
6396       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6397                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6398       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6399       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6400                              getShufflePSHUFLWImmediate(SVOp);
6401       V1 = NewV.getOperand(0);
6402       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6403     }
6404   }
6405
6406   // Promote splats to a larger type which usually leads to more efficient code.
6407   // FIXME: Is this true if pshufb is available?
6408   if (SVOp->isSplat())
6409     return PromoteSplat(SVOp, DAG);
6410
6411   // If we have SSSE3, and all words of the result are from 1 input vector,
6412   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6413   // is present, fall back to case 4.
6414   if (Subtarget->hasSSSE3()) {
6415     SmallVector<SDValue,16> pshufbMask;
6416
6417     // If we have elements from both input vectors, set the high bit of the
6418     // shuffle mask element to zero out elements that come from V2 in the V1
6419     // mask, and elements that come from V1 in the V2 mask, so that the two
6420     // results can be OR'd together.
6421     bool TwoInputs = V1Used && V2Used;
6422     for (unsigned i = 0; i != 8; ++i) {
6423       int EltIdx = MaskVals[i] * 2;
6424       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6425       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6426       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6427       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6428     }
6429     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6430     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6431                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6432                                  MVT::v16i8, &pshufbMask[0], 16));
6433     if (!TwoInputs)
6434       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6435
6436     // Calculate the shuffle mask for the second input, shuffle it, and
6437     // OR it with the first shuffled input.
6438     pshufbMask.clear();
6439     for (unsigned i = 0; i != 8; ++i) {
6440       int EltIdx = MaskVals[i] * 2;
6441       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6442       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6443       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6444       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6445     }
6446     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6447     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6448                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6449                                  MVT::v16i8, &pshufbMask[0], 16));
6450     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6451     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6452   }
6453
6454   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6455   // and update MaskVals with new element order.
6456   std::bitset<8> InOrder;
6457   if (BestLoQuad >= 0) {
6458     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6459     for (int i = 0; i != 4; ++i) {
6460       int idx = MaskVals[i];
6461       if (idx < 0) {
6462         InOrder.set(i);
6463       } else if ((idx / 4) == BestLoQuad) {
6464         MaskV[i] = idx & 3;
6465         InOrder.set(i);
6466       }
6467     }
6468     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6469                                 &MaskV[0]);
6470
6471     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6472       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6473       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6474                                   NewV.getOperand(0),
6475                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6476     }
6477   }
6478
6479   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6480   // and update MaskVals with the new element order.
6481   if (BestHiQuad >= 0) {
6482     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6483     for (unsigned i = 4; i != 8; ++i) {
6484       int idx = MaskVals[i];
6485       if (idx < 0) {
6486         InOrder.set(i);
6487       } else if ((idx / 4) == BestHiQuad) {
6488         MaskV[i] = (idx & 3) + 4;
6489         InOrder.set(i);
6490       }
6491     }
6492     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6493                                 &MaskV[0]);
6494
6495     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6496       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6497       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6498                                   NewV.getOperand(0),
6499                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6500     }
6501   }
6502
6503   // In case BestHi & BestLo were both -1, which means each quadword has a word
6504   // from each of the four input quadwords, calculate the InOrder bitvector now
6505   // before falling through to the insert/extract cleanup.
6506   if (BestLoQuad == -1 && BestHiQuad == -1) {
6507     NewV = V1;
6508     for (int i = 0; i != 8; ++i)
6509       if (MaskVals[i] < 0 || MaskVals[i] == i)
6510         InOrder.set(i);
6511   }
6512
6513   // The other elements are put in the right place using pextrw and pinsrw.
6514   for (unsigned i = 0; i != 8; ++i) {
6515     if (InOrder[i])
6516       continue;
6517     int EltIdx = MaskVals[i];
6518     if (EltIdx < 0)
6519       continue;
6520     SDValue ExtOp = (EltIdx < 8) ?
6521       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6522                   DAG.getIntPtrConstant(EltIdx)) :
6523       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6524                   DAG.getIntPtrConstant(EltIdx - 8));
6525     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6526                        DAG.getIntPtrConstant(i));
6527   }
6528   return NewV;
6529 }
6530
6531 // v16i8 shuffles - Prefer shuffles in the following order:
6532 // 1. [ssse3] 1 x pshufb
6533 // 2. [ssse3] 2 x pshufb + 1 x por
6534 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6535 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6536                                         const X86Subtarget* Subtarget,
6537                                         SelectionDAG &DAG) {
6538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6539   SDValue V1 = SVOp->getOperand(0);
6540   SDValue V2 = SVOp->getOperand(1);
6541   SDLoc dl(SVOp);
6542   ArrayRef<int> MaskVals = SVOp->getMask();
6543
6544   // Promote splats to a larger type which usually leads to more efficient code.
6545   // FIXME: Is this true if pshufb is available?
6546   if (SVOp->isSplat())
6547     return PromoteSplat(SVOp, DAG);
6548
6549   // If we have SSSE3, case 1 is generated when all result bytes come from
6550   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6551   // present, fall back to case 3.
6552
6553   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6554   if (Subtarget->hasSSSE3()) {
6555     SmallVector<SDValue,16> pshufbMask;
6556
6557     // If all result elements are from one input vector, then only translate
6558     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6559     //
6560     // Otherwise, we have elements from both input vectors, and must zero out
6561     // elements that come from V2 in the first mask, and V1 in the second mask
6562     // so that we can OR them together.
6563     for (unsigned i = 0; i != 16; ++i) {
6564       int EltIdx = MaskVals[i];
6565       if (EltIdx < 0 || EltIdx >= 16)
6566         EltIdx = 0x80;
6567       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6568     }
6569     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6570                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6571                                  MVT::v16i8, &pshufbMask[0], 16));
6572
6573     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6574     // the 2nd operand if it's undefined or zero.
6575     if (V2.getOpcode() == ISD::UNDEF ||
6576         ISD::isBuildVectorAllZeros(V2.getNode()))
6577       return V1;
6578
6579     // Calculate the shuffle mask for the second input, shuffle it, and
6580     // OR it with the first shuffled input.
6581     pshufbMask.clear();
6582     for (unsigned i = 0; i != 16; ++i) {
6583       int EltIdx = MaskVals[i];
6584       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6585       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6586     }
6587     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6588                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6589                                  MVT::v16i8, &pshufbMask[0], 16));
6590     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6591   }
6592
6593   // No SSSE3 - Calculate in place words and then fix all out of place words
6594   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6595   // the 16 different words that comprise the two doublequadword input vectors.
6596   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6597   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6598   SDValue NewV = V1;
6599   for (int i = 0; i != 8; ++i) {
6600     int Elt0 = MaskVals[i*2];
6601     int Elt1 = MaskVals[i*2+1];
6602
6603     // This word of the result is all undef, skip it.
6604     if (Elt0 < 0 && Elt1 < 0)
6605       continue;
6606
6607     // This word of the result is already in the correct place, skip it.
6608     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6609       continue;
6610
6611     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6612     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6613     SDValue InsElt;
6614
6615     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6616     // using a single extract together, load it and store it.
6617     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6618       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6619                            DAG.getIntPtrConstant(Elt1 / 2));
6620       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6621                         DAG.getIntPtrConstant(i));
6622       continue;
6623     }
6624
6625     // If Elt1 is defined, extract it from the appropriate source.  If the
6626     // source byte is not also odd, shift the extracted word left 8 bits
6627     // otherwise clear the bottom 8 bits if we need to do an or.
6628     if (Elt1 >= 0) {
6629       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6630                            DAG.getIntPtrConstant(Elt1 / 2));
6631       if ((Elt1 & 1) == 0)
6632         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6633                              DAG.getConstant(8,
6634                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6635       else if (Elt0 >= 0)
6636         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6637                              DAG.getConstant(0xFF00, MVT::i16));
6638     }
6639     // If Elt0 is defined, extract it from the appropriate source.  If the
6640     // source byte is not also even, shift the extracted word right 8 bits. If
6641     // Elt1 was also defined, OR the extracted values together before
6642     // inserting them in the result.
6643     if (Elt0 >= 0) {
6644       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6645                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6646       if ((Elt0 & 1) != 0)
6647         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6648                               DAG.getConstant(8,
6649                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6650       else if (Elt1 >= 0)
6651         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6652                              DAG.getConstant(0x00FF, MVT::i16));
6653       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6654                          : InsElt0;
6655     }
6656     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6657                        DAG.getIntPtrConstant(i));
6658   }
6659   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6660 }
6661
6662 // v32i8 shuffles - Translate to VPSHUFB if possible.
6663 static
6664 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6665                                  const X86Subtarget *Subtarget,
6666                                  SelectionDAG &DAG) {
6667   MVT VT = SVOp->getSimpleValueType(0);
6668   SDValue V1 = SVOp->getOperand(0);
6669   SDValue V2 = SVOp->getOperand(1);
6670   SDLoc dl(SVOp);
6671   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6672
6673   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6674   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6675   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6676
6677   // VPSHUFB may be generated if
6678   // (1) one of input vector is undefined or zeroinitializer.
6679   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6680   // And (2) the mask indexes don't cross the 128-bit lane.
6681   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6682       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6683     return SDValue();
6684
6685   if (V1IsAllZero && !V2IsAllZero) {
6686     CommuteVectorShuffleMask(MaskVals, 32);
6687     V1 = V2;
6688   }
6689   SmallVector<SDValue, 32> pshufbMask;
6690   for (unsigned i = 0; i != 32; i++) {
6691     int EltIdx = MaskVals[i];
6692     if (EltIdx < 0 || EltIdx >= 32)
6693       EltIdx = 0x80;
6694     else {
6695       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6696         // Cross lane is not allowed.
6697         return SDValue();
6698       EltIdx &= 0xf;
6699     }
6700     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6701   }
6702   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6703                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6704                                   MVT::v32i8, &pshufbMask[0], 32));
6705 }
6706
6707 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6708 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6709 /// done when every pair / quad of shuffle mask elements point to elements in
6710 /// the right sequence. e.g.
6711 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6712 static
6713 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6714                                  SelectionDAG &DAG) {
6715   MVT VT = SVOp->getSimpleValueType(0);
6716   SDLoc dl(SVOp);
6717   unsigned NumElems = VT.getVectorNumElements();
6718   MVT NewVT;
6719   unsigned Scale;
6720   switch (VT.SimpleTy) {
6721   default: llvm_unreachable("Unexpected!");
6722   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6723   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6724   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6725   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6726   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6727   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6728   }
6729
6730   SmallVector<int, 8> MaskVec;
6731   for (unsigned i = 0; i != NumElems; i += Scale) {
6732     int StartIdx = -1;
6733     for (unsigned j = 0; j != Scale; ++j) {
6734       int EltIdx = SVOp->getMaskElt(i+j);
6735       if (EltIdx < 0)
6736         continue;
6737       if (StartIdx < 0)
6738         StartIdx = (EltIdx / Scale);
6739       if (EltIdx != (int)(StartIdx*Scale + j))
6740         return SDValue();
6741     }
6742     MaskVec.push_back(StartIdx);
6743   }
6744
6745   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6746   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6747   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6748 }
6749
6750 /// getVZextMovL - Return a zero-extending vector move low node.
6751 ///
6752 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6753                             SDValue SrcOp, SelectionDAG &DAG,
6754                             const X86Subtarget *Subtarget, SDLoc dl) {
6755   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6756     LoadSDNode *LD = NULL;
6757     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6758       LD = dyn_cast<LoadSDNode>(SrcOp);
6759     if (!LD) {
6760       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6761       // instead.
6762       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6763       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6764           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6765           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6766           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6767         // PR2108
6768         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6769         return DAG.getNode(ISD::BITCAST, dl, VT,
6770                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6771                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6772                                                    OpVT,
6773                                                    SrcOp.getOperand(0)
6774                                                           .getOperand(0))));
6775       }
6776     }
6777   }
6778
6779   return DAG.getNode(ISD::BITCAST, dl, VT,
6780                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6781                                  DAG.getNode(ISD::BITCAST, dl,
6782                                              OpVT, SrcOp)));
6783 }
6784
6785 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6786 /// which could not be matched by any known target speficic shuffle
6787 static SDValue
6788 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6789
6790   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6791   if (NewOp.getNode())
6792     return NewOp;
6793
6794   MVT VT = SVOp->getSimpleValueType(0);
6795
6796   unsigned NumElems = VT.getVectorNumElements();
6797   unsigned NumLaneElems = NumElems / 2;
6798
6799   SDLoc dl(SVOp);
6800   MVT EltVT = VT.getVectorElementType();
6801   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6802   SDValue Output[2];
6803
6804   SmallVector<int, 16> Mask;
6805   for (unsigned l = 0; l < 2; ++l) {
6806     // Build a shuffle mask for the output, discovering on the fly which
6807     // input vectors to use as shuffle operands (recorded in InputUsed).
6808     // If building a suitable shuffle vector proves too hard, then bail
6809     // out with UseBuildVector set.
6810     bool UseBuildVector = false;
6811     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6812     unsigned LaneStart = l * NumLaneElems;
6813     for (unsigned i = 0; i != NumLaneElems; ++i) {
6814       // The mask element.  This indexes into the input.
6815       int Idx = SVOp->getMaskElt(i+LaneStart);
6816       if (Idx < 0) {
6817         // the mask element does not index into any input vector.
6818         Mask.push_back(-1);
6819         continue;
6820       }
6821
6822       // The input vector this mask element indexes into.
6823       int Input = Idx / NumLaneElems;
6824
6825       // Turn the index into an offset from the start of the input vector.
6826       Idx -= Input * NumLaneElems;
6827
6828       // Find or create a shuffle vector operand to hold this input.
6829       unsigned OpNo;
6830       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6831         if (InputUsed[OpNo] == Input)
6832           // This input vector is already an operand.
6833           break;
6834         if (InputUsed[OpNo] < 0) {
6835           // Create a new operand for this input vector.
6836           InputUsed[OpNo] = Input;
6837           break;
6838         }
6839       }
6840
6841       if (OpNo >= array_lengthof(InputUsed)) {
6842         // More than two input vectors used!  Give up on trying to create a
6843         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6844         UseBuildVector = true;
6845         break;
6846       }
6847
6848       // Add the mask index for the new shuffle vector.
6849       Mask.push_back(Idx + OpNo * NumLaneElems);
6850     }
6851
6852     if (UseBuildVector) {
6853       SmallVector<SDValue, 16> SVOps;
6854       for (unsigned i = 0; i != NumLaneElems; ++i) {
6855         // The mask element.  This indexes into the input.
6856         int Idx = SVOp->getMaskElt(i+LaneStart);
6857         if (Idx < 0) {
6858           SVOps.push_back(DAG.getUNDEF(EltVT));
6859           continue;
6860         }
6861
6862         // The input vector this mask element indexes into.
6863         int Input = Idx / NumElems;
6864
6865         // Turn the index into an offset from the start of the input vector.
6866         Idx -= Input * NumElems;
6867
6868         // Extract the vector element by hand.
6869         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6870                                     SVOp->getOperand(Input),
6871                                     DAG.getIntPtrConstant(Idx)));
6872       }
6873
6874       // Construct the output using a BUILD_VECTOR.
6875       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6876                               SVOps.size());
6877     } else if (InputUsed[0] < 0) {
6878       // No input vectors were used! The result is undefined.
6879       Output[l] = DAG.getUNDEF(NVT);
6880     } else {
6881       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6882                                         (InputUsed[0] % 2) * NumLaneElems,
6883                                         DAG, dl);
6884       // If only one input was used, use an undefined vector for the other.
6885       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6886         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6887                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6888       // At least one input vector was used. Create a new shuffle vector.
6889       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6890     }
6891
6892     Mask.clear();
6893   }
6894
6895   // Concatenate the result back
6896   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6897 }
6898
6899 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6900 /// 4 elements, and match them with several different shuffle types.
6901 static SDValue
6902 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6903   SDValue V1 = SVOp->getOperand(0);
6904   SDValue V2 = SVOp->getOperand(1);
6905   SDLoc dl(SVOp);
6906   MVT VT = SVOp->getSimpleValueType(0);
6907
6908   assert(VT.is128BitVector() && "Unsupported vector size");
6909
6910   std::pair<int, int> Locs[4];
6911   int Mask1[] = { -1, -1, -1, -1 };
6912   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6913
6914   unsigned NumHi = 0;
6915   unsigned NumLo = 0;
6916   for (unsigned i = 0; i != 4; ++i) {
6917     int Idx = PermMask[i];
6918     if (Idx < 0) {
6919       Locs[i] = std::make_pair(-1, -1);
6920     } else {
6921       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6922       if (Idx < 4) {
6923         Locs[i] = std::make_pair(0, NumLo);
6924         Mask1[NumLo] = Idx;
6925         NumLo++;
6926       } else {
6927         Locs[i] = std::make_pair(1, NumHi);
6928         if (2+NumHi < 4)
6929           Mask1[2+NumHi] = Idx;
6930         NumHi++;
6931       }
6932     }
6933   }
6934
6935   if (NumLo <= 2 && NumHi <= 2) {
6936     // If no more than two elements come from either vector. This can be
6937     // implemented with two shuffles. First shuffle gather the elements.
6938     // The second shuffle, which takes the first shuffle as both of its
6939     // vector operands, put the elements into the right order.
6940     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6941
6942     int Mask2[] = { -1, -1, -1, -1 };
6943
6944     for (unsigned i = 0; i != 4; ++i)
6945       if (Locs[i].first != -1) {
6946         unsigned Idx = (i < 2) ? 0 : 4;
6947         Idx += Locs[i].first * 2 + Locs[i].second;
6948         Mask2[i] = Idx;
6949       }
6950
6951     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6952   }
6953
6954   if (NumLo == 3 || NumHi == 3) {
6955     // Otherwise, we must have three elements from one vector, call it X, and
6956     // one element from the other, call it Y.  First, use a shufps to build an
6957     // intermediate vector with the one element from Y and the element from X
6958     // that will be in the same half in the final destination (the indexes don't
6959     // matter). Then, use a shufps to build the final vector, taking the half
6960     // containing the element from Y from the intermediate, and the other half
6961     // from X.
6962     if (NumHi == 3) {
6963       // Normalize it so the 3 elements come from V1.
6964       CommuteVectorShuffleMask(PermMask, 4);
6965       std::swap(V1, V2);
6966     }
6967
6968     // Find the element from V2.
6969     unsigned HiIndex;
6970     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6971       int Val = PermMask[HiIndex];
6972       if (Val < 0)
6973         continue;
6974       if (Val >= 4)
6975         break;
6976     }
6977
6978     Mask1[0] = PermMask[HiIndex];
6979     Mask1[1] = -1;
6980     Mask1[2] = PermMask[HiIndex^1];
6981     Mask1[3] = -1;
6982     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6983
6984     if (HiIndex >= 2) {
6985       Mask1[0] = PermMask[0];
6986       Mask1[1] = PermMask[1];
6987       Mask1[2] = HiIndex & 1 ? 6 : 4;
6988       Mask1[3] = HiIndex & 1 ? 4 : 6;
6989       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6990     }
6991
6992     Mask1[0] = HiIndex & 1 ? 2 : 0;
6993     Mask1[1] = HiIndex & 1 ? 0 : 2;
6994     Mask1[2] = PermMask[2];
6995     Mask1[3] = PermMask[3];
6996     if (Mask1[2] >= 0)
6997       Mask1[2] += 4;
6998     if (Mask1[3] >= 0)
6999       Mask1[3] += 4;
7000     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7001   }
7002
7003   // Break it into (shuffle shuffle_hi, shuffle_lo).
7004   int LoMask[] = { -1, -1, -1, -1 };
7005   int HiMask[] = { -1, -1, -1, -1 };
7006
7007   int *MaskPtr = LoMask;
7008   unsigned MaskIdx = 0;
7009   unsigned LoIdx = 0;
7010   unsigned HiIdx = 2;
7011   for (unsigned i = 0; i != 4; ++i) {
7012     if (i == 2) {
7013       MaskPtr = HiMask;
7014       MaskIdx = 1;
7015       LoIdx = 0;
7016       HiIdx = 2;
7017     }
7018     int Idx = PermMask[i];
7019     if (Idx < 0) {
7020       Locs[i] = std::make_pair(-1, -1);
7021     } else if (Idx < 4) {
7022       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7023       MaskPtr[LoIdx] = Idx;
7024       LoIdx++;
7025     } else {
7026       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7027       MaskPtr[HiIdx] = Idx;
7028       HiIdx++;
7029     }
7030   }
7031
7032   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7033   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7034   int MaskOps[] = { -1, -1, -1, -1 };
7035   for (unsigned i = 0; i != 4; ++i)
7036     if (Locs[i].first != -1)
7037       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7038   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7039 }
7040
7041 static bool MayFoldVectorLoad(SDValue V) {
7042   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7043     V = V.getOperand(0);
7044
7045   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7046     V = V.getOperand(0);
7047   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7048       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7049     // BUILD_VECTOR (load), undef
7050     V = V.getOperand(0);
7051
7052   return MayFoldLoad(V);
7053 }
7054
7055 static
7056 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7057   MVT VT = Op.getSimpleValueType();
7058
7059   // Canonizalize to v2f64.
7060   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7061   return DAG.getNode(ISD::BITCAST, dl, VT,
7062                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7063                                           V1, DAG));
7064 }
7065
7066 static
7067 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7068                         bool HasSSE2) {
7069   SDValue V1 = Op.getOperand(0);
7070   SDValue V2 = Op.getOperand(1);
7071   MVT VT = Op.getSimpleValueType();
7072
7073   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7074
7075   if (HasSSE2 && VT == MVT::v2f64)
7076     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7077
7078   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7079   return DAG.getNode(ISD::BITCAST, dl, VT,
7080                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7081                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7082                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7083 }
7084
7085 static
7086 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7087   SDValue V1 = Op.getOperand(0);
7088   SDValue V2 = Op.getOperand(1);
7089   MVT VT = Op.getSimpleValueType();
7090
7091   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7092          "unsupported shuffle type");
7093
7094   if (V2.getOpcode() == ISD::UNDEF)
7095     V2 = V1;
7096
7097   // v4i32 or v4f32
7098   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7099 }
7100
7101 static
7102 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7103   SDValue V1 = Op.getOperand(0);
7104   SDValue V2 = Op.getOperand(1);
7105   MVT VT = Op.getSimpleValueType();
7106   unsigned NumElems = VT.getVectorNumElements();
7107
7108   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7109   // operand of these instructions is only memory, so check if there's a
7110   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7111   // same masks.
7112   bool CanFoldLoad = false;
7113
7114   // Trivial case, when V2 comes from a load.
7115   if (MayFoldVectorLoad(V2))
7116     CanFoldLoad = true;
7117
7118   // When V1 is a load, it can be folded later into a store in isel, example:
7119   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7120   //    turns into:
7121   //  (MOVLPSmr addr:$src1, VR128:$src2)
7122   // So, recognize this potential and also use MOVLPS or MOVLPD
7123   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7124     CanFoldLoad = true;
7125
7126   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7127   if (CanFoldLoad) {
7128     if (HasSSE2 && NumElems == 2)
7129       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7130
7131     if (NumElems == 4)
7132       // If we don't care about the second element, proceed to use movss.
7133       if (SVOp->getMaskElt(1) != -1)
7134         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7135   }
7136
7137   // movl and movlp will both match v2i64, but v2i64 is never matched by
7138   // movl earlier because we make it strict to avoid messing with the movlp load
7139   // folding logic (see the code above getMOVLP call). Match it here then,
7140   // this is horrible, but will stay like this until we move all shuffle
7141   // matching to x86 specific nodes. Note that for the 1st condition all
7142   // types are matched with movsd.
7143   if (HasSSE2) {
7144     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7145     // as to remove this logic from here, as much as possible
7146     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7147       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7148     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7149   }
7150
7151   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7152
7153   // Invert the operand order and use SHUFPS to match it.
7154   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7155                               getShuffleSHUFImmediate(SVOp), DAG);
7156 }
7157
7158 // Reduce a vector shuffle to zext.
7159 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7160                                     SelectionDAG &DAG) {
7161   // PMOVZX is only available from SSE41.
7162   if (!Subtarget->hasSSE41())
7163     return SDValue();
7164
7165   MVT VT = Op.getSimpleValueType();
7166
7167   // Only AVX2 support 256-bit vector integer extending.
7168   if (!Subtarget->hasInt256() && VT.is256BitVector())
7169     return SDValue();
7170
7171   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7172   SDLoc DL(Op);
7173   SDValue V1 = Op.getOperand(0);
7174   SDValue V2 = Op.getOperand(1);
7175   unsigned NumElems = VT.getVectorNumElements();
7176
7177   // Extending is an unary operation and the element type of the source vector
7178   // won't be equal to or larger than i64.
7179   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7180       VT.getVectorElementType() == MVT::i64)
7181     return SDValue();
7182
7183   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7184   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7185   while ((1U << Shift) < NumElems) {
7186     if (SVOp->getMaskElt(1U << Shift) == 1)
7187       break;
7188     Shift += 1;
7189     // The maximal ratio is 8, i.e. from i8 to i64.
7190     if (Shift > 3)
7191       return SDValue();
7192   }
7193
7194   // Check the shuffle mask.
7195   unsigned Mask = (1U << Shift) - 1;
7196   for (unsigned i = 0; i != NumElems; ++i) {
7197     int EltIdx = SVOp->getMaskElt(i);
7198     if ((i & Mask) != 0 && EltIdx != -1)
7199       return SDValue();
7200     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7201       return SDValue();
7202   }
7203
7204   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7205   MVT NeVT = MVT::getIntegerVT(NBits);
7206   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7207
7208   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7209     return SDValue();
7210
7211   // Simplify the operand as it's prepared to be fed into shuffle.
7212   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7213   if (V1.getOpcode() == ISD::BITCAST &&
7214       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7215       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7216       V1.getOperand(0).getOperand(0)
7217         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7218     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7219     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7220     ConstantSDNode *CIdx =
7221       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7222     // If it's foldable, i.e. normal load with single use, we will let code
7223     // selection to fold it. Otherwise, we will short the conversion sequence.
7224     if (CIdx && CIdx->getZExtValue() == 0 &&
7225         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7226       MVT FullVT = V.getSimpleValueType();
7227       MVT V1VT = V1.getSimpleValueType();
7228       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7229         // The "ext_vec_elt" node is wider than the result node.
7230         // In this case we should extract subvector from V.
7231         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7232         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7233         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7234                                         FullVT.getVectorNumElements()/Ratio);
7235         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7236                         DAG.getIntPtrConstant(0));
7237       }
7238       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7239     }
7240   }
7241
7242   return DAG.getNode(ISD::BITCAST, DL, VT,
7243                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7244 }
7245
7246 static SDValue
7247 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7248                        SelectionDAG &DAG) {
7249   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7250   MVT VT = Op.getSimpleValueType();
7251   SDLoc dl(Op);
7252   SDValue V1 = Op.getOperand(0);
7253   SDValue V2 = Op.getOperand(1);
7254
7255   if (isZeroShuffle(SVOp))
7256     return getZeroVector(VT, Subtarget, DAG, dl);
7257
7258   // Handle splat operations
7259   if (SVOp->isSplat()) {
7260     // Use vbroadcast whenever the splat comes from a foldable load
7261     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7262     if (Broadcast.getNode())
7263       return Broadcast;
7264   }
7265
7266   // Check integer expanding shuffles.
7267   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7268   if (NewOp.getNode())
7269     return NewOp;
7270
7271   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7272   // do it!
7273   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7274       VT == MVT::v16i16 || VT == MVT::v32i8) {
7275     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7276     if (NewOp.getNode())
7277       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7278   } else if ((VT == MVT::v4i32 ||
7279              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7280     // FIXME: Figure out a cleaner way to do this.
7281     // Try to make use of movq to zero out the top part.
7282     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7283       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7284       if (NewOp.getNode()) {
7285         MVT NewVT = NewOp.getSimpleValueType();
7286         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7287                                NewVT, true, false))
7288           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7289                               DAG, Subtarget, dl);
7290       }
7291     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7292       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7293       if (NewOp.getNode()) {
7294         MVT NewVT = NewOp.getSimpleValueType();
7295         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7296           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7297                               DAG, Subtarget, dl);
7298       }
7299     }
7300   }
7301   return SDValue();
7302 }
7303
7304 SDValue
7305 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7306   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7307   SDValue V1 = Op.getOperand(0);
7308   SDValue V2 = Op.getOperand(1);
7309   MVT VT = Op.getSimpleValueType();
7310   SDLoc dl(Op);
7311   unsigned NumElems = VT.getVectorNumElements();
7312   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7313   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7314   bool V1IsSplat = false;
7315   bool V2IsSplat = false;
7316   bool HasSSE2 = Subtarget->hasSSE2();
7317   bool HasFp256    = Subtarget->hasFp256();
7318   bool HasInt256   = Subtarget->hasInt256();
7319   MachineFunction &MF = DAG.getMachineFunction();
7320   bool OptForSize = MF.getFunction()->getAttributes().
7321     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7322
7323   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7324
7325   if (V1IsUndef && V2IsUndef)
7326     return DAG.getUNDEF(VT);
7327
7328   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7329
7330   // Vector shuffle lowering takes 3 steps:
7331   //
7332   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7333   //    narrowing and commutation of operands should be handled.
7334   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7335   //    shuffle nodes.
7336   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7337   //    so the shuffle can be broken into other shuffles and the legalizer can
7338   //    try the lowering again.
7339   //
7340   // The general idea is that no vector_shuffle operation should be left to
7341   // be matched during isel, all of them must be converted to a target specific
7342   // node here.
7343
7344   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7345   // narrowing and commutation of operands should be handled. The actual code
7346   // doesn't include all of those, work in progress...
7347   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7348   if (NewOp.getNode())
7349     return NewOp;
7350
7351   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7352
7353   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7354   // unpckh_undef). Only use pshufd if speed is more important than size.
7355   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7356     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7357   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7358     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7359
7360   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7361       V2IsUndef && MayFoldVectorLoad(V1))
7362     return getMOVDDup(Op, dl, V1, DAG);
7363
7364   if (isMOVHLPS_v_undef_Mask(M, VT))
7365     return getMOVHighToLow(Op, dl, DAG);
7366
7367   // Use to match splats
7368   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7369       (VT == MVT::v2f64 || VT == MVT::v2i64))
7370     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7371
7372   if (isPSHUFDMask(M, VT)) {
7373     // The actual implementation will match the mask in the if above and then
7374     // during isel it can match several different instructions, not only pshufd
7375     // as its name says, sad but true, emulate the behavior for now...
7376     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7377       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7378
7379     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7380
7381     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7382       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7383
7384     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7385       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7386                                   DAG);
7387
7388     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7389                                 TargetMask, DAG);
7390   }
7391
7392   if (isPALIGNRMask(M, VT, Subtarget))
7393     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7394                                 getShufflePALIGNRImmediate(SVOp),
7395                                 DAG);
7396
7397   // Check if this can be converted into a logical shift.
7398   bool isLeft = false;
7399   unsigned ShAmt = 0;
7400   SDValue ShVal;
7401   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7402   if (isShift && ShVal.hasOneUse()) {
7403     // If the shifted value has multiple uses, it may be cheaper to use
7404     // v_set0 + movlhps or movhlps, etc.
7405     MVT EltVT = VT.getVectorElementType();
7406     ShAmt *= EltVT.getSizeInBits();
7407     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7408   }
7409
7410   if (isMOVLMask(M, VT)) {
7411     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7412       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7413     if (!isMOVLPMask(M, VT)) {
7414       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7415         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7416
7417       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7418         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7419     }
7420   }
7421
7422   // FIXME: fold these into legal mask.
7423   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7424     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7425
7426   if (isMOVHLPSMask(M, VT))
7427     return getMOVHighToLow(Op, dl, DAG);
7428
7429   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7430     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7431
7432   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7433     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7434
7435   if (isMOVLPMask(M, VT))
7436     return getMOVLP(Op, dl, DAG, HasSSE2);
7437
7438   if (ShouldXformToMOVHLPS(M, VT) ||
7439       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7440     return CommuteVectorShuffle(SVOp, DAG);
7441
7442   if (isShift) {
7443     // No better options. Use a vshldq / vsrldq.
7444     MVT EltVT = VT.getVectorElementType();
7445     ShAmt *= EltVT.getSizeInBits();
7446     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7447   }
7448
7449   bool Commuted = false;
7450   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7451   // 1,1,1,1 -> v8i16 though.
7452   V1IsSplat = isSplatVector(V1.getNode());
7453   V2IsSplat = isSplatVector(V2.getNode());
7454
7455   // Canonicalize the splat or undef, if present, to be on the RHS.
7456   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7457     CommuteVectorShuffleMask(M, NumElems);
7458     std::swap(V1, V2);
7459     std::swap(V1IsSplat, V2IsSplat);
7460     Commuted = true;
7461   }
7462
7463   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7464     // Shuffling low element of v1 into undef, just return v1.
7465     if (V2IsUndef)
7466       return V1;
7467     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7468     // the instruction selector will not match, so get a canonical MOVL with
7469     // swapped operands to undo the commute.
7470     return getMOVL(DAG, dl, VT, V2, V1);
7471   }
7472
7473   if (isUNPCKLMask(M, VT, HasInt256))
7474     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7475
7476   if (isUNPCKHMask(M, VT, HasInt256))
7477     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7478
7479   if (V2IsSplat) {
7480     // Normalize mask so all entries that point to V2 points to its first
7481     // element then try to match unpck{h|l} again. If match, return a
7482     // new vector_shuffle with the corrected mask.p
7483     SmallVector<int, 8> NewMask(M.begin(), M.end());
7484     NormalizeMask(NewMask, NumElems);
7485     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7486       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7487     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7488       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7489   }
7490
7491   if (Commuted) {
7492     // Commute is back and try unpck* again.
7493     // FIXME: this seems wrong.
7494     CommuteVectorShuffleMask(M, NumElems);
7495     std::swap(V1, V2);
7496     std::swap(V1IsSplat, V2IsSplat);
7497     Commuted = false;
7498
7499     if (isUNPCKLMask(M, VT, HasInt256))
7500       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7501
7502     if (isUNPCKHMask(M, VT, HasInt256))
7503       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7504   }
7505
7506   // Normalize the node to match x86 shuffle ops if needed
7507   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7508     return CommuteVectorShuffle(SVOp, DAG);
7509
7510   // The checks below are all present in isShuffleMaskLegal, but they are
7511   // inlined here right now to enable us to directly emit target specific
7512   // nodes, and remove one by one until they don't return Op anymore.
7513
7514   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7515       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7516     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7517       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7518   }
7519
7520   if (isPSHUFHWMask(M, VT, HasInt256))
7521     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7522                                 getShufflePSHUFHWImmediate(SVOp),
7523                                 DAG);
7524
7525   if (isPSHUFLWMask(M, VT, HasInt256))
7526     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7527                                 getShufflePSHUFLWImmediate(SVOp),
7528                                 DAG);
7529
7530   if (isSHUFPMask(M, VT))
7531     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7532                                 getShuffleSHUFImmediate(SVOp), DAG);
7533
7534   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7535     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7536   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7537     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7538
7539   //===--------------------------------------------------------------------===//
7540   // Generate target specific nodes for 128 or 256-bit shuffles only
7541   // supported in the AVX instruction set.
7542   //
7543
7544   // Handle VMOVDDUPY permutations
7545   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7546     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7547
7548   // Handle VPERMILPS/D* permutations
7549   if (isVPERMILPMask(M, VT)) {
7550     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7551       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7552                                   getShuffleSHUFImmediate(SVOp), DAG);
7553     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7554                                 getShuffleSHUFImmediate(SVOp), DAG);
7555   }
7556
7557   // Handle VPERM2F128/VPERM2I128 permutations
7558   if (isVPERM2X128Mask(M, VT, HasFp256))
7559     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7560                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7561
7562   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7563   if (BlendOp.getNode())
7564     return BlendOp;
7565
7566   unsigned Imm8;
7567   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7568     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7569
7570   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7571       VT.is512BitVector()) {
7572     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7573     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7574     SmallVector<SDValue, 16> permclMask;
7575     for (unsigned i = 0; i != NumElems; ++i) {
7576       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7577     }
7578
7579     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7580                                 &permclMask[0], NumElems);
7581     if (V2IsUndef)
7582       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7583       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7584                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7585     return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7586                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7587   }
7588
7589   //===--------------------------------------------------------------------===//
7590   // Since no target specific shuffle was selected for this generic one,
7591   // lower it into other known shuffles. FIXME: this isn't true yet, but
7592   // this is the plan.
7593   //
7594
7595   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7596   if (VT == MVT::v8i16) {
7597     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7598     if (NewOp.getNode())
7599       return NewOp;
7600   }
7601
7602   if (VT == MVT::v16i8) {
7603     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7604     if (NewOp.getNode())
7605       return NewOp;
7606   }
7607
7608   if (VT == MVT::v32i8) {
7609     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7610     if (NewOp.getNode())
7611       return NewOp;
7612   }
7613
7614   // Handle all 128-bit wide vectors with 4 elements, and match them with
7615   // several different shuffle types.
7616   if (NumElems == 4 && VT.is128BitVector())
7617     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7618
7619   // Handle general 256-bit shuffles
7620   if (VT.is256BitVector())
7621     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7622
7623   return SDValue();
7624 }
7625
7626 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7627   MVT VT = Op.getSimpleValueType();
7628   SDLoc dl(Op);
7629
7630   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7631     return SDValue();
7632
7633   if (VT.getSizeInBits() == 8) {
7634     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7635                                   Op.getOperand(0), Op.getOperand(1));
7636     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7637                                   DAG.getValueType(VT));
7638     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7639   }
7640
7641   if (VT.getSizeInBits() == 16) {
7642     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7643     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7644     if (Idx == 0)
7645       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7646                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7647                                      DAG.getNode(ISD::BITCAST, dl,
7648                                                  MVT::v4i32,
7649                                                  Op.getOperand(0)),
7650                                      Op.getOperand(1)));
7651     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7652                                   Op.getOperand(0), Op.getOperand(1));
7653     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7654                                   DAG.getValueType(VT));
7655     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7656   }
7657
7658   if (VT == MVT::f32) {
7659     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7660     // the result back to FR32 register. It's only worth matching if the
7661     // result has a single use which is a store or a bitcast to i32.  And in
7662     // the case of a store, it's not worth it if the index is a constant 0,
7663     // because a MOVSSmr can be used instead, which is smaller and faster.
7664     if (!Op.hasOneUse())
7665       return SDValue();
7666     SDNode *User = *Op.getNode()->use_begin();
7667     if ((User->getOpcode() != ISD::STORE ||
7668          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7669           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7670         (User->getOpcode() != ISD::BITCAST ||
7671          User->getValueType(0) != MVT::i32))
7672       return SDValue();
7673     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7674                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7675                                               Op.getOperand(0)),
7676                                               Op.getOperand(1));
7677     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7678   }
7679
7680   if (VT == MVT::i32 || VT == MVT::i64) {
7681     // ExtractPS/pextrq works with constant index.
7682     if (isa<ConstantSDNode>(Op.getOperand(1)))
7683       return Op;
7684   }
7685   return SDValue();
7686 }
7687
7688 /// Extract one bit from mask vector, like v16i1 or v8i1.
7689 /// AVX-512 feature.
7690 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) {
7691   SDValue Vec = Op.getOperand(0);
7692   SDLoc dl(Vec);
7693   MVT VecVT = Vec.getSimpleValueType();
7694   SDValue Idx = Op.getOperand(1);
7695   MVT EltVT = Op.getSimpleValueType();
7696
7697   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7698
7699   // variable index can't be handled in mask registers,
7700   // extend vector to VR512
7701   if (!isa<ConstantSDNode>(Idx)) {
7702     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7703     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7704     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7705                               ExtVT.getVectorElementType(), Ext, Idx);
7706     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7707   }
7708
7709   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7710   if (IdxVal) {
7711     unsigned MaxSift = VecVT.getSizeInBits() - 1;
7712     Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7713                       DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7714     Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7715                       DAG.getConstant(MaxSift, MVT::i8));
7716   }
7717   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i1, Vec,
7718                        DAG.getIntPtrConstant(0));
7719 }
7720
7721 SDValue
7722 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7723                                            SelectionDAG &DAG) const {
7724   SDLoc dl(Op);
7725   SDValue Vec = Op.getOperand(0);
7726   MVT VecVT = Vec.getSimpleValueType();
7727   SDValue Idx = Op.getOperand(1);
7728
7729   if (Op.getSimpleValueType() == MVT::i1)
7730     return ExtractBitFromMaskVector(Op, DAG);
7731
7732   if (!isa<ConstantSDNode>(Idx)) {
7733     if (VecVT.is512BitVector() ||
7734         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7735          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7736
7737       MVT MaskEltVT =
7738         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7739       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7740                                     MaskEltVT.getSizeInBits());
7741
7742       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7743       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7744                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7745                                 Idx, DAG.getConstant(0, getPointerTy()));
7746       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7747       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7748                         Perm, DAG.getConstant(0, getPointerTy()));
7749     }
7750     return SDValue();
7751   }
7752
7753   // If this is a 256-bit vector result, first extract the 128-bit vector and
7754   // then extract the element from the 128-bit vector.
7755   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7756
7757     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7758     // Get the 128-bit vector.
7759     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7760     MVT EltVT = VecVT.getVectorElementType();
7761
7762     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7763
7764     //if (IdxVal >= NumElems/2)
7765     //  IdxVal -= NumElems/2;
7766     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7767     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7768                        DAG.getConstant(IdxVal, MVT::i32));
7769   }
7770
7771   assert(VecVT.is128BitVector() && "Unexpected vector length");
7772
7773   if (Subtarget->hasSSE41()) {
7774     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7775     if (Res.getNode())
7776       return Res;
7777   }
7778
7779   MVT VT = Op.getSimpleValueType();
7780   // TODO: handle v16i8.
7781   if (VT.getSizeInBits() == 16) {
7782     SDValue Vec = Op.getOperand(0);
7783     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7784     if (Idx == 0)
7785       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7786                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7787                                      DAG.getNode(ISD::BITCAST, dl,
7788                                                  MVT::v4i32, Vec),
7789                                      Op.getOperand(1)));
7790     // Transform it so it match pextrw which produces a 32-bit result.
7791     MVT EltVT = MVT::i32;
7792     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7793                                   Op.getOperand(0), Op.getOperand(1));
7794     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7795                                   DAG.getValueType(VT));
7796     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7797   }
7798
7799   if (VT.getSizeInBits() == 32) {
7800     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7801     if (Idx == 0)
7802       return Op;
7803
7804     // SHUFPS the element to the lowest double word, then movss.
7805     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7806     MVT VVT = Op.getOperand(0).getSimpleValueType();
7807     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7808                                        DAG.getUNDEF(VVT), Mask);
7809     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7810                        DAG.getIntPtrConstant(0));
7811   }
7812
7813   if (VT.getSizeInBits() == 64) {
7814     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7815     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7816     //        to match extract_elt for f64.
7817     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7818     if (Idx == 0)
7819       return Op;
7820
7821     // UNPCKHPD the element to the lowest double word, then movsd.
7822     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7823     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7824     int Mask[2] = { 1, -1 };
7825     MVT VVT = Op.getOperand(0).getSimpleValueType();
7826     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7827                                        DAG.getUNDEF(VVT), Mask);
7828     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7829                        DAG.getIntPtrConstant(0));
7830   }
7831
7832   return SDValue();
7833 }
7834
7835 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7836   MVT VT = Op.getSimpleValueType();
7837   MVT EltVT = VT.getVectorElementType();
7838   SDLoc dl(Op);
7839
7840   SDValue N0 = Op.getOperand(0);
7841   SDValue N1 = Op.getOperand(1);
7842   SDValue N2 = Op.getOperand(2);
7843
7844   if (!VT.is128BitVector())
7845     return SDValue();
7846
7847   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7848       isa<ConstantSDNode>(N2)) {
7849     unsigned Opc;
7850     if (VT == MVT::v8i16)
7851       Opc = X86ISD::PINSRW;
7852     else if (VT == MVT::v16i8)
7853       Opc = X86ISD::PINSRB;
7854     else
7855       Opc = X86ISD::PINSRB;
7856
7857     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7858     // argument.
7859     if (N1.getValueType() != MVT::i32)
7860       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7861     if (N2.getValueType() != MVT::i32)
7862       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7863     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7864   }
7865
7866   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7867     // Bits [7:6] of the constant are the source select.  This will always be
7868     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7869     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7870     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7871     // Bits [5:4] of the constant are the destination select.  This is the
7872     //  value of the incoming immediate.
7873     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7874     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7875     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7876     // Create this as a scalar to vector..
7877     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7878     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7879   }
7880
7881   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7882     // PINSR* works with constant index.
7883     return Op;
7884   }
7885   return SDValue();
7886 }
7887
7888 SDValue
7889 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7890   MVT VT = Op.getSimpleValueType();
7891   MVT EltVT = VT.getVectorElementType();
7892
7893   SDLoc dl(Op);
7894   SDValue N0 = Op.getOperand(0);
7895   SDValue N1 = Op.getOperand(1);
7896   SDValue N2 = Op.getOperand(2);
7897
7898   // If this is a 256-bit vector result, first extract the 128-bit vector,
7899   // insert the element into the extracted half and then place it back.
7900   if (VT.is256BitVector() || VT.is512BitVector()) {
7901     if (!isa<ConstantSDNode>(N2))
7902       return SDValue();
7903
7904     // Get the desired 128-bit vector half.
7905     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7906     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7907
7908     // Insert the element into the desired half.
7909     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7910     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7911
7912     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7913                     DAG.getConstant(IdxIn128, MVT::i32));
7914
7915     // Insert the changed part back to the 256-bit vector
7916     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7917   }
7918
7919   if (Subtarget->hasSSE41())
7920     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7921
7922   if (EltVT == MVT::i8)
7923     return SDValue();
7924
7925   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7926     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7927     // as its second argument.
7928     if (N1.getValueType() != MVT::i32)
7929       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7930     if (N2.getValueType() != MVT::i32)
7931       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7932     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7933   }
7934   return SDValue();
7935 }
7936
7937 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7938   SDLoc dl(Op);
7939   MVT OpVT = Op.getSimpleValueType();
7940
7941   // If this is a 256-bit vector result, first insert into a 128-bit
7942   // vector and then insert into the 256-bit vector.
7943   if (!OpVT.is128BitVector()) {
7944     // Insert into a 128-bit vector.
7945     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7946     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7947                                  OpVT.getVectorNumElements() / SizeFactor);
7948
7949     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7950
7951     // Insert the 128-bit vector.
7952     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7953   }
7954
7955   if (OpVT == MVT::v1i64 &&
7956       Op.getOperand(0).getValueType() == MVT::i64)
7957     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7958
7959   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7960   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7961   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7962                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7963 }
7964
7965 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7966 // a simple subregister reference or explicit instructions to grab
7967 // upper bits of a vector.
7968 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7969                                       SelectionDAG &DAG) {
7970   SDLoc dl(Op);
7971   SDValue In =  Op.getOperand(0);
7972   SDValue Idx = Op.getOperand(1);
7973   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7974   MVT ResVT   = Op.getSimpleValueType();
7975   MVT InVT    = In.getSimpleValueType();
7976
7977   if (Subtarget->hasFp256()) {
7978     if (ResVT.is128BitVector() &&
7979         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7980         isa<ConstantSDNode>(Idx)) {
7981       return Extract128BitVector(In, IdxVal, DAG, dl);
7982     }
7983     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7984         isa<ConstantSDNode>(Idx)) {
7985       return Extract256BitVector(In, IdxVal, DAG, dl);
7986     }
7987   }
7988   return SDValue();
7989 }
7990
7991 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7992 // simple superregister reference or explicit instructions to insert
7993 // the upper bits of a vector.
7994 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7995                                      SelectionDAG &DAG) {
7996   if (Subtarget->hasFp256()) {
7997     SDLoc dl(Op.getNode());
7998     SDValue Vec = Op.getNode()->getOperand(0);
7999     SDValue SubVec = Op.getNode()->getOperand(1);
8000     SDValue Idx = Op.getNode()->getOperand(2);
8001
8002     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8003          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8004         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8005         isa<ConstantSDNode>(Idx)) {
8006       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8007       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8008     }
8009
8010     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8011         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8012         isa<ConstantSDNode>(Idx)) {
8013       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8014       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8015     }
8016   }
8017   return SDValue();
8018 }
8019
8020 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8021 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8022 // one of the above mentioned nodes. It has to be wrapped because otherwise
8023 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8024 // be used to form addressing mode. These wrapped nodes will be selected
8025 // into MOV32ri.
8026 SDValue
8027 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8028   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8029
8030   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8031   // global base reg.
8032   unsigned char OpFlag = 0;
8033   unsigned WrapperKind = X86ISD::Wrapper;
8034   CodeModel::Model M = getTargetMachine().getCodeModel();
8035
8036   if (Subtarget->isPICStyleRIPRel() &&
8037       (M == CodeModel::Small || M == CodeModel::Kernel))
8038     WrapperKind = X86ISD::WrapperRIP;
8039   else if (Subtarget->isPICStyleGOT())
8040     OpFlag = X86II::MO_GOTOFF;
8041   else if (Subtarget->isPICStyleStubPIC())
8042     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8043
8044   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8045                                              CP->getAlignment(),
8046                                              CP->getOffset(), OpFlag);
8047   SDLoc DL(CP);
8048   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8049   // With PIC, the address is actually $g + Offset.
8050   if (OpFlag) {
8051     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8052                          DAG.getNode(X86ISD::GlobalBaseReg,
8053                                      SDLoc(), getPointerTy()),
8054                          Result);
8055   }
8056
8057   return Result;
8058 }
8059
8060 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8061   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8062
8063   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8064   // global base reg.
8065   unsigned char OpFlag = 0;
8066   unsigned WrapperKind = X86ISD::Wrapper;
8067   CodeModel::Model M = getTargetMachine().getCodeModel();
8068
8069   if (Subtarget->isPICStyleRIPRel() &&
8070       (M == CodeModel::Small || M == CodeModel::Kernel))
8071     WrapperKind = X86ISD::WrapperRIP;
8072   else if (Subtarget->isPICStyleGOT())
8073     OpFlag = X86II::MO_GOTOFF;
8074   else if (Subtarget->isPICStyleStubPIC())
8075     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8076
8077   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8078                                           OpFlag);
8079   SDLoc DL(JT);
8080   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8081
8082   // With PIC, the address is actually $g + Offset.
8083   if (OpFlag)
8084     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8085                          DAG.getNode(X86ISD::GlobalBaseReg,
8086                                      SDLoc(), getPointerTy()),
8087                          Result);
8088
8089   return Result;
8090 }
8091
8092 SDValue
8093 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8094   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8095
8096   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8097   // global base reg.
8098   unsigned char OpFlag = 0;
8099   unsigned WrapperKind = X86ISD::Wrapper;
8100   CodeModel::Model M = getTargetMachine().getCodeModel();
8101
8102   if (Subtarget->isPICStyleRIPRel() &&
8103       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8104     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8105       OpFlag = X86II::MO_GOTPCREL;
8106     WrapperKind = X86ISD::WrapperRIP;
8107   } else if (Subtarget->isPICStyleGOT()) {
8108     OpFlag = X86II::MO_GOT;
8109   } else if (Subtarget->isPICStyleStubPIC()) {
8110     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8111   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8112     OpFlag = X86II::MO_DARWIN_NONLAZY;
8113   }
8114
8115   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8116
8117   SDLoc DL(Op);
8118   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8119
8120   // With PIC, the address is actually $g + Offset.
8121   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8122       !Subtarget->is64Bit()) {
8123     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8124                          DAG.getNode(X86ISD::GlobalBaseReg,
8125                                      SDLoc(), getPointerTy()),
8126                          Result);
8127   }
8128
8129   // For symbols that require a load from a stub to get the address, emit the
8130   // load.
8131   if (isGlobalStubReference(OpFlag))
8132     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8133                          MachinePointerInfo::getGOT(), false, false, false, 0);
8134
8135   return Result;
8136 }
8137
8138 SDValue
8139 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8140   // Create the TargetBlockAddressAddress node.
8141   unsigned char OpFlags =
8142     Subtarget->ClassifyBlockAddressReference();
8143   CodeModel::Model M = getTargetMachine().getCodeModel();
8144   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8145   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8146   SDLoc dl(Op);
8147   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8148                                              OpFlags);
8149
8150   if (Subtarget->isPICStyleRIPRel() &&
8151       (M == CodeModel::Small || M == CodeModel::Kernel))
8152     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8153   else
8154     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8155
8156   // With PIC, the address is actually $g + Offset.
8157   if (isGlobalRelativeToPICBase(OpFlags)) {
8158     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8159                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8160                          Result);
8161   }
8162
8163   return Result;
8164 }
8165
8166 SDValue
8167 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8168                                       int64_t Offset, SelectionDAG &DAG) const {
8169   // Create the TargetGlobalAddress node, folding in the constant
8170   // offset if it is legal.
8171   unsigned char OpFlags =
8172     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8173   CodeModel::Model M = getTargetMachine().getCodeModel();
8174   SDValue Result;
8175   if (OpFlags == X86II::MO_NO_FLAG &&
8176       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8177     // A direct static reference to a global.
8178     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8179     Offset = 0;
8180   } else {
8181     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8182   }
8183
8184   if (Subtarget->isPICStyleRIPRel() &&
8185       (M == CodeModel::Small || M == CodeModel::Kernel))
8186     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8187   else
8188     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8189
8190   // With PIC, the address is actually $g + Offset.
8191   if (isGlobalRelativeToPICBase(OpFlags)) {
8192     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8193                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8194                          Result);
8195   }
8196
8197   // For globals that require a load from a stub to get the address, emit the
8198   // load.
8199   if (isGlobalStubReference(OpFlags))
8200     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8201                          MachinePointerInfo::getGOT(), false, false, false, 0);
8202
8203   // If there was a non-zero offset that we didn't fold, create an explicit
8204   // addition for it.
8205   if (Offset != 0)
8206     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8207                          DAG.getConstant(Offset, getPointerTy()));
8208
8209   return Result;
8210 }
8211
8212 SDValue
8213 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8214   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8215   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8216   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8217 }
8218
8219 static SDValue
8220 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8221            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8222            unsigned char OperandFlags, bool LocalDynamic = false) {
8223   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8224   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8225   SDLoc dl(GA);
8226   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8227                                            GA->getValueType(0),
8228                                            GA->getOffset(),
8229                                            OperandFlags);
8230
8231   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8232                                            : X86ISD::TLSADDR;
8233
8234   if (InFlag) {
8235     SDValue Ops[] = { Chain,  TGA, *InFlag };
8236     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8237   } else {
8238     SDValue Ops[]  = { Chain, TGA };
8239     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8240   }
8241
8242   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8243   MFI->setAdjustsStack(true);
8244
8245   SDValue Flag = Chain.getValue(1);
8246   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8247 }
8248
8249 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8250 static SDValue
8251 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8252                                 const EVT PtrVT) {
8253   SDValue InFlag;
8254   SDLoc dl(GA);  // ? function entry point might be better
8255   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8256                                    DAG.getNode(X86ISD::GlobalBaseReg,
8257                                                SDLoc(), PtrVT), InFlag);
8258   InFlag = Chain.getValue(1);
8259
8260   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8261 }
8262
8263 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8264 static SDValue
8265 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8266                                 const EVT PtrVT) {
8267   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8268                     X86::RAX, X86II::MO_TLSGD);
8269 }
8270
8271 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8272                                            SelectionDAG &DAG,
8273                                            const EVT PtrVT,
8274                                            bool is64Bit) {
8275   SDLoc dl(GA);
8276
8277   // Get the start address of the TLS block for this module.
8278   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8279       .getInfo<X86MachineFunctionInfo>();
8280   MFI->incNumLocalDynamicTLSAccesses();
8281
8282   SDValue Base;
8283   if (is64Bit) {
8284     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8285                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8286   } else {
8287     SDValue InFlag;
8288     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8289         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8290     InFlag = Chain.getValue(1);
8291     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8292                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8293   }
8294
8295   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8296   // of Base.
8297
8298   // Build x@dtpoff.
8299   unsigned char OperandFlags = X86II::MO_DTPOFF;
8300   unsigned WrapperKind = X86ISD::Wrapper;
8301   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8302                                            GA->getValueType(0),
8303                                            GA->getOffset(), OperandFlags);
8304   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8305
8306   // Add x@dtpoff with the base.
8307   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8308 }
8309
8310 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8311 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8312                                    const EVT PtrVT, TLSModel::Model model,
8313                                    bool is64Bit, bool isPIC) {
8314   SDLoc dl(GA);
8315
8316   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8317   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8318                                                          is64Bit ? 257 : 256));
8319
8320   SDValue ThreadPointer =
8321       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8322                   MachinePointerInfo(Ptr), false, false, false, 0);
8323
8324   unsigned char OperandFlags = 0;
8325   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8326   // initialexec.
8327   unsigned WrapperKind = X86ISD::Wrapper;
8328   if (model == TLSModel::LocalExec) {
8329     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8330   } else if (model == TLSModel::InitialExec) {
8331     if (is64Bit) {
8332       OperandFlags = X86II::MO_GOTTPOFF;
8333       WrapperKind = X86ISD::WrapperRIP;
8334     } else {
8335       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8336     }
8337   } else {
8338     llvm_unreachable("Unexpected model");
8339   }
8340
8341   // emit "addl x@ntpoff,%eax" (local exec)
8342   // or "addl x@indntpoff,%eax" (initial exec)
8343   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8344   SDValue TGA =
8345       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8346                                  GA->getOffset(), OperandFlags);
8347   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8348
8349   if (model == TLSModel::InitialExec) {
8350     if (isPIC && !is64Bit) {
8351       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8352                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8353                            Offset);
8354     }
8355
8356     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8357                          MachinePointerInfo::getGOT(), false, false, false, 0);
8358   }
8359
8360   // The address of the thread local variable is the add of the thread
8361   // pointer with the offset of the variable.
8362   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8363 }
8364
8365 SDValue
8366 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8367
8368   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8369   const GlobalValue *GV = GA->getGlobal();
8370
8371   if (Subtarget->isTargetELF()) {
8372     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8373
8374     switch (model) {
8375       case TLSModel::GeneralDynamic:
8376         if (Subtarget->is64Bit())
8377           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8378         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8379       case TLSModel::LocalDynamic:
8380         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8381                                            Subtarget->is64Bit());
8382       case TLSModel::InitialExec:
8383       case TLSModel::LocalExec:
8384         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8385                                    Subtarget->is64Bit(),
8386                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8387     }
8388     llvm_unreachable("Unknown TLS model.");
8389   }
8390
8391   if (Subtarget->isTargetDarwin()) {
8392     // Darwin only has one model of TLS.  Lower to that.
8393     unsigned char OpFlag = 0;
8394     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8395                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8396
8397     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8398     // global base reg.
8399     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8400                   !Subtarget->is64Bit();
8401     if (PIC32)
8402       OpFlag = X86II::MO_TLVP_PIC_BASE;
8403     else
8404       OpFlag = X86II::MO_TLVP;
8405     SDLoc DL(Op);
8406     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8407                                                 GA->getValueType(0),
8408                                                 GA->getOffset(), OpFlag);
8409     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8410
8411     // With PIC32, the address is actually $g + Offset.
8412     if (PIC32)
8413       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8414                            DAG.getNode(X86ISD::GlobalBaseReg,
8415                                        SDLoc(), getPointerTy()),
8416                            Offset);
8417
8418     // Lowering the machine isd will make sure everything is in the right
8419     // location.
8420     SDValue Chain = DAG.getEntryNode();
8421     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8422     SDValue Args[] = { Chain, Offset };
8423     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8424
8425     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8426     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8427     MFI->setAdjustsStack(true);
8428
8429     // And our return value (tls address) is in the standard call return value
8430     // location.
8431     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8432     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8433                               Chain.getValue(1));
8434   }
8435
8436   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8437     // Just use the implicit TLS architecture
8438     // Need to generate someting similar to:
8439     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8440     //                                  ; from TEB
8441     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8442     //   mov     rcx, qword [rdx+rcx*8]
8443     //   mov     eax, .tls$:tlsvar
8444     //   [rax+rcx] contains the address
8445     // Windows 64bit: gs:0x58
8446     // Windows 32bit: fs:__tls_array
8447
8448     // If GV is an alias then use the aliasee for determining
8449     // thread-localness.
8450     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8451       GV = GA->resolveAliasedGlobal(false);
8452     SDLoc dl(GA);
8453     SDValue Chain = DAG.getEntryNode();
8454
8455     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8456     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8457     // use its literal value of 0x2C.
8458     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8459                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8460                                                              256)
8461                                         : Type::getInt32PtrTy(*DAG.getContext(),
8462                                                               257));
8463
8464     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8465       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8466         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8467
8468     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8469                                         MachinePointerInfo(Ptr),
8470                                         false, false, false, 0);
8471
8472     // Load the _tls_index variable
8473     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8474     if (Subtarget->is64Bit())
8475       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8476                            IDX, MachinePointerInfo(), MVT::i32,
8477                            false, false, 0);
8478     else
8479       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8480                         false, false, false, 0);
8481
8482     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8483                                     getPointerTy());
8484     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8485
8486     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8487     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8488                       false, false, false, 0);
8489
8490     // Get the offset of start of .tls section
8491     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8492                                              GA->getValueType(0),
8493                                              GA->getOffset(), X86II::MO_SECREL);
8494     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8495
8496     // The address of the thread local variable is the add of the thread
8497     // pointer with the offset of the variable.
8498     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8499   }
8500
8501   llvm_unreachable("TLS not implemented for this target.");
8502 }
8503
8504 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8505 /// and take a 2 x i32 value to shift plus a shift amount.
8506 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8507   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8508   EVT VT = Op.getValueType();
8509   unsigned VTBits = VT.getSizeInBits();
8510   SDLoc dl(Op);
8511   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8512   SDValue ShOpLo = Op.getOperand(0);
8513   SDValue ShOpHi = Op.getOperand(1);
8514   SDValue ShAmt  = Op.getOperand(2);
8515   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8516   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8517   // during isel.
8518   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8519                                   DAG.getConstant(VTBits - 1, MVT::i8));
8520   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8521                                      DAG.getConstant(VTBits - 1, MVT::i8))
8522                        : DAG.getConstant(0, VT);
8523
8524   SDValue Tmp2, Tmp3;
8525   if (Op.getOpcode() == ISD::SHL_PARTS) {
8526     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8527     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8528   } else {
8529     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8530     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8531   }
8532
8533   // If the shift amount is larger or equal than the width of a part we can't
8534   // rely on the results of shld/shrd. Insert a test and select the appropriate
8535   // values for large shift amounts.
8536   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8537                                 DAG.getConstant(VTBits, MVT::i8));
8538   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8539                              AndNode, DAG.getConstant(0, MVT::i8));
8540
8541   SDValue Hi, Lo;
8542   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8543   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8544   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8545
8546   if (Op.getOpcode() == ISD::SHL_PARTS) {
8547     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8548     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8549   } else {
8550     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8551     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8552   }
8553
8554   SDValue Ops[2] = { Lo, Hi };
8555   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8556 }
8557
8558 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8559                                            SelectionDAG &DAG) const {
8560   EVT SrcVT = Op.getOperand(0).getValueType();
8561
8562   if (SrcVT.isVector())
8563     return SDValue();
8564
8565   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8566          "Unknown SINT_TO_FP to lower!");
8567
8568   // These are really Legal; return the operand so the caller accepts it as
8569   // Legal.
8570   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8571     return Op;
8572   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8573       Subtarget->is64Bit()) {
8574     return Op;
8575   }
8576
8577   SDLoc dl(Op);
8578   unsigned Size = SrcVT.getSizeInBits()/8;
8579   MachineFunction &MF = DAG.getMachineFunction();
8580   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8581   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8582   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8583                                StackSlot,
8584                                MachinePointerInfo::getFixedStack(SSFI),
8585                                false, false, 0);
8586   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8587 }
8588
8589 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8590                                      SDValue StackSlot,
8591                                      SelectionDAG &DAG) const {
8592   // Build the FILD
8593   SDLoc DL(Op);
8594   SDVTList Tys;
8595   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8596   if (useSSE)
8597     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8598   else
8599     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8600
8601   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8602
8603   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8604   MachineMemOperand *MMO;
8605   if (FI) {
8606     int SSFI = FI->getIndex();
8607     MMO =
8608       DAG.getMachineFunction()
8609       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8610                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8611   } else {
8612     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8613     StackSlot = StackSlot.getOperand(1);
8614   }
8615   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8616   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8617                                            X86ISD::FILD, DL,
8618                                            Tys, Ops, array_lengthof(Ops),
8619                                            SrcVT, MMO);
8620
8621   if (useSSE) {
8622     Chain = Result.getValue(1);
8623     SDValue InFlag = Result.getValue(2);
8624
8625     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8626     // shouldn't be necessary except that RFP cannot be live across
8627     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8628     MachineFunction &MF = DAG.getMachineFunction();
8629     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8630     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8631     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8632     Tys = DAG.getVTList(MVT::Other);
8633     SDValue Ops[] = {
8634       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8635     };
8636     MachineMemOperand *MMO =
8637       DAG.getMachineFunction()
8638       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8639                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8640
8641     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8642                                     Ops, array_lengthof(Ops),
8643                                     Op.getValueType(), MMO);
8644     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8645                          MachinePointerInfo::getFixedStack(SSFI),
8646                          false, false, false, 0);
8647   }
8648
8649   return Result;
8650 }
8651
8652 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8653 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8654                                                SelectionDAG &DAG) const {
8655   // This algorithm is not obvious. Here it is what we're trying to output:
8656   /*
8657      movq       %rax,  %xmm0
8658      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8659      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8660      #ifdef __SSE3__
8661        haddpd   %xmm0, %xmm0
8662      #else
8663        pshufd   $0x4e, %xmm0, %xmm1
8664        addpd    %xmm1, %xmm0
8665      #endif
8666   */
8667
8668   SDLoc dl(Op);
8669   LLVMContext *Context = DAG.getContext();
8670
8671   // Build some magic constants.
8672   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8673   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8674   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8675
8676   SmallVector<Constant*,2> CV1;
8677   CV1.push_back(
8678     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8679                                       APInt(64, 0x4330000000000000ULL))));
8680   CV1.push_back(
8681     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8682                                       APInt(64, 0x4530000000000000ULL))));
8683   Constant *C1 = ConstantVector::get(CV1);
8684   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8685
8686   // Load the 64-bit value into an XMM register.
8687   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8688                             Op.getOperand(0));
8689   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8690                               MachinePointerInfo::getConstantPool(),
8691                               false, false, false, 16);
8692   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8693                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8694                               CLod0);
8695
8696   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8697                               MachinePointerInfo::getConstantPool(),
8698                               false, false, false, 16);
8699   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8700   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8701   SDValue Result;
8702
8703   if (Subtarget->hasSSE3()) {
8704     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8705     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8706   } else {
8707     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8708     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8709                                            S2F, 0x4E, DAG);
8710     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8711                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8712                          Sub);
8713   }
8714
8715   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8716                      DAG.getIntPtrConstant(0));
8717 }
8718
8719 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8720 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8721                                                SelectionDAG &DAG) const {
8722   SDLoc dl(Op);
8723   // FP constant to bias correct the final result.
8724   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8725                                    MVT::f64);
8726
8727   // Load the 32-bit value into an XMM register.
8728   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8729                              Op.getOperand(0));
8730
8731   // Zero out the upper parts of the register.
8732   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8733
8734   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8735                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8736                      DAG.getIntPtrConstant(0));
8737
8738   // Or the load with the bias.
8739   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8740                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8741                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8742                                                    MVT::v2f64, Load)),
8743                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8744                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8745                                                    MVT::v2f64, Bias)));
8746   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8747                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8748                    DAG.getIntPtrConstant(0));
8749
8750   // Subtract the bias.
8751   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8752
8753   // Handle final rounding.
8754   EVT DestVT = Op.getValueType();
8755
8756   if (DestVT.bitsLT(MVT::f64))
8757     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8758                        DAG.getIntPtrConstant(0));
8759   if (DestVT.bitsGT(MVT::f64))
8760     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8761
8762   // Handle final rounding.
8763   return Sub;
8764 }
8765
8766 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8767                                                SelectionDAG &DAG) const {
8768   SDValue N0 = Op.getOperand(0);
8769   EVT SVT = N0.getValueType();
8770   SDLoc dl(Op);
8771
8772   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8773           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8774          "Custom UINT_TO_FP is not supported!");
8775
8776   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8777                              SVT.getVectorNumElements());
8778   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8779                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8780 }
8781
8782 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8783                                            SelectionDAG &DAG) const {
8784   SDValue N0 = Op.getOperand(0);
8785   SDLoc dl(Op);
8786
8787   if (Op.getValueType().isVector())
8788     return lowerUINT_TO_FP_vec(Op, DAG);
8789
8790   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8791   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8792   // the optimization here.
8793   if (DAG.SignBitIsZero(N0))
8794     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8795
8796   EVT SrcVT = N0.getValueType();
8797   EVT DstVT = Op.getValueType();
8798   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8799     return LowerUINT_TO_FP_i64(Op, DAG);
8800   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8801     return LowerUINT_TO_FP_i32(Op, DAG);
8802   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8803     return SDValue();
8804
8805   // Make a 64-bit buffer, and use it to build an FILD.
8806   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8807   if (SrcVT == MVT::i32) {
8808     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8809     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8810                                      getPointerTy(), StackSlot, WordOff);
8811     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8812                                   StackSlot, MachinePointerInfo(),
8813                                   false, false, 0);
8814     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8815                                   OffsetSlot, MachinePointerInfo(),
8816                                   false, false, 0);
8817     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8818     return Fild;
8819   }
8820
8821   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8822   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8823                                StackSlot, MachinePointerInfo(),
8824                                false, false, 0);
8825   // For i64 source, we need to add the appropriate power of 2 if the input
8826   // was negative.  This is the same as the optimization in
8827   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8828   // we must be careful to do the computation in x87 extended precision, not
8829   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8830   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8831   MachineMemOperand *MMO =
8832     DAG.getMachineFunction()
8833     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8834                           MachineMemOperand::MOLoad, 8, 8);
8835
8836   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8837   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8838   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8839                                          array_lengthof(Ops), MVT::i64, MMO);
8840
8841   APInt FF(32, 0x5F800000ULL);
8842
8843   // Check whether the sign bit is set.
8844   SDValue SignSet = DAG.getSetCC(dl,
8845                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8846                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8847                                  ISD::SETLT);
8848
8849   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8850   SDValue FudgePtr = DAG.getConstantPool(
8851                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8852                                          getPointerTy());
8853
8854   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8855   SDValue Zero = DAG.getIntPtrConstant(0);
8856   SDValue Four = DAG.getIntPtrConstant(4);
8857   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8858                                Zero, Four);
8859   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8860
8861   // Load the value out, extending it from f32 to f80.
8862   // FIXME: Avoid the extend by constructing the right constant pool?
8863   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8864                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8865                                  MVT::f32, false, false, 4);
8866   // Extend everything to 80 bits to force it to be done on x87.
8867   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8868   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8869 }
8870
8871 std::pair<SDValue,SDValue>
8872 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8873                                     bool IsSigned, bool IsReplace) const {
8874   SDLoc DL(Op);
8875
8876   EVT DstTy = Op.getValueType();
8877
8878   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8879     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8880     DstTy = MVT::i64;
8881   }
8882
8883   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8884          DstTy.getSimpleVT() >= MVT::i16 &&
8885          "Unknown FP_TO_INT to lower!");
8886
8887   // These are really Legal.
8888   if (DstTy == MVT::i32 &&
8889       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8890     return std::make_pair(SDValue(), SDValue());
8891   if (Subtarget->is64Bit() &&
8892       DstTy == MVT::i64 &&
8893       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8894     return std::make_pair(SDValue(), SDValue());
8895
8896   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8897   // stack slot, or into the FTOL runtime function.
8898   MachineFunction &MF = DAG.getMachineFunction();
8899   unsigned MemSize = DstTy.getSizeInBits()/8;
8900   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8901   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8902
8903   unsigned Opc;
8904   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8905     Opc = X86ISD::WIN_FTOL;
8906   else
8907     switch (DstTy.getSimpleVT().SimpleTy) {
8908     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8909     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8910     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8911     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8912     }
8913
8914   SDValue Chain = DAG.getEntryNode();
8915   SDValue Value = Op.getOperand(0);
8916   EVT TheVT = Op.getOperand(0).getValueType();
8917   // FIXME This causes a redundant load/store if the SSE-class value is already
8918   // in memory, such as if it is on the callstack.
8919   if (isScalarFPTypeInSSEReg(TheVT)) {
8920     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8921     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8922                          MachinePointerInfo::getFixedStack(SSFI),
8923                          false, false, 0);
8924     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8925     SDValue Ops[] = {
8926       Chain, StackSlot, DAG.getValueType(TheVT)
8927     };
8928
8929     MachineMemOperand *MMO =
8930       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8931                               MachineMemOperand::MOLoad, MemSize, MemSize);
8932     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8933                                     array_lengthof(Ops), DstTy, MMO);
8934     Chain = Value.getValue(1);
8935     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8936     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8937   }
8938
8939   MachineMemOperand *MMO =
8940     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8941                             MachineMemOperand::MOStore, MemSize, MemSize);
8942
8943   if (Opc != X86ISD::WIN_FTOL) {
8944     // Build the FP_TO_INT*_IN_MEM
8945     SDValue Ops[] = { Chain, Value, StackSlot };
8946     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8947                                            Ops, array_lengthof(Ops), DstTy,
8948                                            MMO);
8949     return std::make_pair(FIST, StackSlot);
8950   } else {
8951     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8952       DAG.getVTList(MVT::Other, MVT::Glue),
8953       Chain, Value);
8954     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8955       MVT::i32, ftol.getValue(1));
8956     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8957       MVT::i32, eax.getValue(2));
8958     SDValue Ops[] = { eax, edx };
8959     SDValue pair = IsReplace
8960       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8961       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8962     return std::make_pair(pair, SDValue());
8963   }
8964 }
8965
8966 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8967                               const X86Subtarget *Subtarget) {
8968   MVT VT = Op->getSimpleValueType(0);
8969   SDValue In = Op->getOperand(0);
8970   MVT InVT = In.getSimpleValueType();
8971   SDLoc dl(Op);
8972
8973   // Optimize vectors in AVX mode:
8974   //
8975   //   v8i16 -> v8i32
8976   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8977   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8978   //   Concat upper and lower parts.
8979   //
8980   //   v4i32 -> v4i64
8981   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8982   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8983   //   Concat upper and lower parts.
8984   //
8985
8986   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
8987       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8988       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8989     return SDValue();
8990
8991   if (Subtarget->hasInt256())
8992     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8993
8994   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8995   SDValue Undef = DAG.getUNDEF(InVT);
8996   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8997   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8998   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8999
9000   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9001                              VT.getVectorNumElements()/2);
9002
9003   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9004   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9005
9006   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9007 }
9008
9009 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9010                                         SelectionDAG &DAG) {
9011   MVT VT = Op->getValueType(0).getSimpleVT();
9012   SDValue In = Op->getOperand(0);
9013   MVT InVT = In.getValueType().getSimpleVT();
9014   SDLoc DL(Op);
9015   unsigned int NumElts = VT.getVectorNumElements();
9016   if (NumElts != 8 && NumElts != 16)
9017     return SDValue();
9018
9019   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9020     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9021
9022   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9024   // Now we have only mask extension
9025   assert(InVT.getVectorElementType() == MVT::i1);
9026   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9027   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9028   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9029   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9030   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9031                            MachinePointerInfo::getConstantPool(),
9032                            false, false, false, Alignment);
9033
9034   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9035   if (VT.is512BitVector())
9036     return Brcst;
9037   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9038 }
9039
9040 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9041                                SelectionDAG &DAG) {
9042   if (Subtarget->hasFp256()) {
9043     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9044     if (Res.getNode())
9045       return Res;
9046   }
9047
9048   return SDValue();
9049 }
9050
9051 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9052                                 SelectionDAG &DAG) {
9053   SDLoc DL(Op);
9054   MVT VT = Op.getSimpleValueType();
9055   SDValue In = Op.getOperand(0);
9056   MVT SVT = In.getSimpleValueType();
9057
9058   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9059     return LowerZERO_EXTEND_AVX512(Op, DAG);
9060
9061   if (Subtarget->hasFp256()) {
9062     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9063     if (Res.getNode())
9064       return Res;
9065   }
9066
9067   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9068          VT.getVectorNumElements() != SVT.getVectorNumElements());
9069   return SDValue();
9070 }
9071
9072 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9073   SDLoc DL(Op);
9074   MVT VT = Op.getSimpleValueType();
9075   SDValue In = Op.getOperand(0);
9076   MVT InVT = In.getSimpleValueType();
9077
9078   if (VT == MVT::i1) {
9079     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9080            "Invalid scalar TRUNCATE operation");
9081     In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(1, InVT));
9082     if (InVT.getSizeInBits() == 64)
9083       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9084     else if (InVT.getSizeInBits() < 32)
9085       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9086     return DAG.getNode(X86ISD::TRUNC, DL, VT, In);
9087   }
9088   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9089          "Invalid TRUNCATE operation");
9090
9091   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9092     if (VT.getVectorElementType().getSizeInBits() >=8)
9093       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9094
9095     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9096     unsigned NumElts = InVT.getVectorNumElements();
9097     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9098     if (InVT.getSizeInBits() < 512) {
9099       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9100       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9101       InVT = ExtVT;
9102     }
9103     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9104     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9105     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9106     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9107     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9108                            MachinePointerInfo::getConstantPool(),
9109                            false, false, false, Alignment);
9110     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9111     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9112     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9113   }
9114
9115   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9116     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9117     if (Subtarget->hasInt256()) {
9118       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9119       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9120       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9121                                 ShufMask);
9122       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9123                          DAG.getIntPtrConstant(0));
9124     }
9125
9126     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
9127     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9128                                DAG.getIntPtrConstant(0));
9129     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9130                                DAG.getIntPtrConstant(2));
9131
9132     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9133     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9134
9135     // The PSHUFD mask:
9136     static const int ShufMask1[] = {0, 2, 0, 0};
9137     SDValue Undef = DAG.getUNDEF(VT);
9138     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
9139     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
9140
9141     // The MOVLHPS mask:
9142     static const int ShufMask2[] = {0, 1, 4, 5};
9143     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
9144   }
9145
9146   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9147     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9148     if (Subtarget->hasInt256()) {
9149       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9150
9151       SmallVector<SDValue,32> pshufbMask;
9152       for (unsigned i = 0; i < 2; ++i) {
9153         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9154         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9155         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9156         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9157         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9158         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9159         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9160         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9161         for (unsigned j = 0; j < 8; ++j)
9162           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9163       }
9164       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9165                                &pshufbMask[0], 32);
9166       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9167       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9168
9169       static const int ShufMask[] = {0,  2,  -1,  -1};
9170       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9171                                 &ShufMask[0]);
9172       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9173                        DAG.getIntPtrConstant(0));
9174       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9175     }
9176
9177     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9178                                DAG.getIntPtrConstant(0));
9179
9180     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9181                                DAG.getIntPtrConstant(4));
9182
9183     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9184     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9185
9186     // The PSHUFB mask:
9187     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9188                                    -1, -1, -1, -1, -1, -1, -1, -1};
9189
9190     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9191     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9192     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9193
9194     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9195     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9196
9197     // The MOVLHPS Mask:
9198     static const int ShufMask2[] = {0, 1, 4, 5};
9199     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9200     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9201   }
9202
9203   // Handle truncation of V256 to V128 using shuffles.
9204   if (!VT.is128BitVector() || !InVT.is256BitVector())
9205     return SDValue();
9206
9207   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9208
9209   unsigned NumElems = VT.getVectorNumElements();
9210   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9211                              NumElems * 2);
9212
9213   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9214   // Prepare truncation shuffle mask
9215   for (unsigned i = 0; i != NumElems; ++i)
9216     MaskVec[i] = i * 2;
9217   SDValue V = DAG.getVectorShuffle(NVT, DL,
9218                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9219                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9220   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9221                      DAG.getIntPtrConstant(0));
9222 }
9223
9224 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9225                                            SelectionDAG &DAG) const {
9226   MVT VT = Op.getSimpleValueType();
9227   if (VT.isVector()) {
9228     if (VT == MVT::v8i16)
9229       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9230                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9231                                      MVT::v8i32, Op.getOperand(0)));
9232     return SDValue();
9233   }
9234
9235   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9236     /*IsSigned=*/ true, /*IsReplace=*/ false);
9237   SDValue FIST = Vals.first, StackSlot = Vals.second;
9238   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9239   if (FIST.getNode() == 0) return Op;
9240
9241   if (StackSlot.getNode())
9242     // Load the result.
9243     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9244                        FIST, StackSlot, MachinePointerInfo(),
9245                        false, false, false, 0);
9246
9247   // The node is the result.
9248   return FIST;
9249 }
9250
9251 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9252                                            SelectionDAG &DAG) const {
9253   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9254     /*IsSigned=*/ false, /*IsReplace=*/ false);
9255   SDValue FIST = Vals.first, StackSlot = Vals.second;
9256   assert(FIST.getNode() && "Unexpected failure");
9257
9258   if (StackSlot.getNode())
9259     // Load the result.
9260     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9261                        FIST, StackSlot, MachinePointerInfo(),
9262                        false, false, false, 0);
9263
9264   // The node is the result.
9265   return FIST;
9266 }
9267
9268 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9269   SDLoc DL(Op);
9270   MVT VT = Op.getSimpleValueType();
9271   SDValue In = Op.getOperand(0);
9272   MVT SVT = In.getSimpleValueType();
9273
9274   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9275
9276   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9277                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9278                                  In, DAG.getUNDEF(SVT)));
9279 }
9280
9281 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9282   LLVMContext *Context = DAG.getContext();
9283   SDLoc dl(Op);
9284   MVT VT = Op.getSimpleValueType();
9285   MVT EltVT = VT;
9286   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9287   if (VT.isVector()) {
9288     EltVT = VT.getVectorElementType();
9289     NumElts = VT.getVectorNumElements();
9290   }
9291   Constant *C;
9292   if (EltVT == MVT::f64)
9293     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9294                                           APInt(64, ~(1ULL << 63))));
9295   else
9296     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9297                                           APInt(32, ~(1U << 31))));
9298   C = ConstantVector::getSplat(NumElts, C);
9299   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9300   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9301   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9302                              MachinePointerInfo::getConstantPool(),
9303                              false, false, false, Alignment);
9304   if (VT.isVector()) {
9305     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9306     return DAG.getNode(ISD::BITCAST, dl, VT,
9307                        DAG.getNode(ISD::AND, dl, ANDVT,
9308                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9309                                                Op.getOperand(0)),
9310                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9311   }
9312   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9313 }
9314
9315 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9316   LLVMContext *Context = DAG.getContext();
9317   SDLoc dl(Op);
9318   MVT VT = Op.getSimpleValueType();
9319   MVT EltVT = VT;
9320   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9321   if (VT.isVector()) {
9322     EltVT = VT.getVectorElementType();
9323     NumElts = VT.getVectorNumElements();
9324   }
9325   Constant *C;
9326   if (EltVT == MVT::f64)
9327     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9328                                           APInt(64, 1ULL << 63)));
9329   else
9330     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9331                                           APInt(32, 1U << 31)));
9332   C = ConstantVector::getSplat(NumElts, C);
9333   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9334   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9335   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9336                              MachinePointerInfo::getConstantPool(),
9337                              false, false, false, Alignment);
9338   if (VT.isVector()) {
9339     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9340     return DAG.getNode(ISD::BITCAST, dl, VT,
9341                        DAG.getNode(ISD::XOR, dl, XORVT,
9342                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9343                                                Op.getOperand(0)),
9344                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9345   }
9346
9347   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9348 }
9349
9350 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9351   LLVMContext *Context = DAG.getContext();
9352   SDValue Op0 = Op.getOperand(0);
9353   SDValue Op1 = Op.getOperand(1);
9354   SDLoc dl(Op);
9355   MVT VT = Op.getSimpleValueType();
9356   MVT SrcVT = Op1.getSimpleValueType();
9357
9358   // If second operand is smaller, extend it first.
9359   if (SrcVT.bitsLT(VT)) {
9360     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9361     SrcVT = VT;
9362   }
9363   // And if it is bigger, shrink it first.
9364   if (SrcVT.bitsGT(VT)) {
9365     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9366     SrcVT = VT;
9367   }
9368
9369   // At this point the operands and the result should have the same
9370   // type, and that won't be f80 since that is not custom lowered.
9371
9372   // First get the sign bit of second operand.
9373   SmallVector<Constant*,4> CV;
9374   if (SrcVT == MVT::f64) {
9375     const fltSemantics &Sem = APFloat::IEEEdouble;
9376     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9377     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9378   } else {
9379     const fltSemantics &Sem = APFloat::IEEEsingle;
9380     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9381     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9382     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9383     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9384   }
9385   Constant *C = ConstantVector::get(CV);
9386   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9387   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9388                               MachinePointerInfo::getConstantPool(),
9389                               false, false, false, 16);
9390   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9391
9392   // Shift sign bit right or left if the two operands have different types.
9393   if (SrcVT.bitsGT(VT)) {
9394     // Op0 is MVT::f32, Op1 is MVT::f64.
9395     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9396     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9397                           DAG.getConstant(32, MVT::i32));
9398     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9399     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9400                           DAG.getIntPtrConstant(0));
9401   }
9402
9403   // Clear first operand sign bit.
9404   CV.clear();
9405   if (VT == MVT::f64) {
9406     const fltSemantics &Sem = APFloat::IEEEdouble;
9407     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9408                                                    APInt(64, ~(1ULL << 63)))));
9409     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9410   } else {
9411     const fltSemantics &Sem = APFloat::IEEEsingle;
9412     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9413                                                    APInt(32, ~(1U << 31)))));
9414     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9415     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9416     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9417   }
9418   C = ConstantVector::get(CV);
9419   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9420   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9421                               MachinePointerInfo::getConstantPool(),
9422                               false, false, false, 16);
9423   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9424
9425   // Or the value with the sign bit.
9426   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9427 }
9428
9429 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9430   SDValue N0 = Op.getOperand(0);
9431   SDLoc dl(Op);
9432   MVT VT = Op.getSimpleValueType();
9433
9434   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9435   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9436                                   DAG.getConstant(1, VT));
9437   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9438 }
9439
9440 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9441 //
9442 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9443                                       SelectionDAG &DAG) {
9444   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9445
9446   if (!Subtarget->hasSSE41())
9447     return SDValue();
9448
9449   if (!Op->hasOneUse())
9450     return SDValue();
9451
9452   SDNode *N = Op.getNode();
9453   SDLoc DL(N);
9454
9455   SmallVector<SDValue, 8> Opnds;
9456   DenseMap<SDValue, unsigned> VecInMap;
9457   EVT VT = MVT::Other;
9458
9459   // Recognize a special case where a vector is casted into wide integer to
9460   // test all 0s.
9461   Opnds.push_back(N->getOperand(0));
9462   Opnds.push_back(N->getOperand(1));
9463
9464   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9465     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9466     // BFS traverse all OR'd operands.
9467     if (I->getOpcode() == ISD::OR) {
9468       Opnds.push_back(I->getOperand(0));
9469       Opnds.push_back(I->getOperand(1));
9470       // Re-evaluate the number of nodes to be traversed.
9471       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9472       continue;
9473     }
9474
9475     // Quit if a non-EXTRACT_VECTOR_ELT
9476     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9477       return SDValue();
9478
9479     // Quit if without a constant index.
9480     SDValue Idx = I->getOperand(1);
9481     if (!isa<ConstantSDNode>(Idx))
9482       return SDValue();
9483
9484     SDValue ExtractedFromVec = I->getOperand(0);
9485     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9486     if (M == VecInMap.end()) {
9487       VT = ExtractedFromVec.getValueType();
9488       // Quit if not 128/256-bit vector.
9489       if (!VT.is128BitVector() && !VT.is256BitVector())
9490         return SDValue();
9491       // Quit if not the same type.
9492       if (VecInMap.begin() != VecInMap.end() &&
9493           VT != VecInMap.begin()->first.getValueType())
9494         return SDValue();
9495       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9496     }
9497     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9498   }
9499
9500   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9501          "Not extracted from 128-/256-bit vector.");
9502
9503   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9504   SmallVector<SDValue, 8> VecIns;
9505
9506   for (DenseMap<SDValue, unsigned>::const_iterator
9507         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9508     // Quit if not all elements are used.
9509     if (I->second != FullMask)
9510       return SDValue();
9511     VecIns.push_back(I->first);
9512   }
9513
9514   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9515
9516   // Cast all vectors into TestVT for PTEST.
9517   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9518     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9519
9520   // If more than one full vectors are evaluated, OR them first before PTEST.
9521   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9522     // Each iteration will OR 2 nodes and append the result until there is only
9523     // 1 node left, i.e. the final OR'd value of all vectors.
9524     SDValue LHS = VecIns[Slot];
9525     SDValue RHS = VecIns[Slot + 1];
9526     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9527   }
9528
9529   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9530                      VecIns.back(), VecIns.back());
9531 }
9532
9533 /// Emit nodes that will be selected as "test Op0,Op0", or something
9534 /// equivalent.
9535 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9536                                     SelectionDAG &DAG) const {
9537   SDLoc dl(Op);
9538
9539   // CF and OF aren't always set the way we want. Determine which
9540   // of these we need.
9541   bool NeedCF = false;
9542   bool NeedOF = false;
9543   switch (X86CC) {
9544   default: break;
9545   case X86::COND_A: case X86::COND_AE:
9546   case X86::COND_B: case X86::COND_BE:
9547     NeedCF = true;
9548     break;
9549   case X86::COND_G: case X86::COND_GE:
9550   case X86::COND_L: case X86::COND_LE:
9551   case X86::COND_O: case X86::COND_NO:
9552     NeedOF = true;
9553     break;
9554   }
9555
9556   // See if we can use the EFLAGS value from the operand instead of
9557   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9558   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9559   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9560     // Emit a CMP with 0, which is the TEST pattern.
9561     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9562                        DAG.getConstant(0, Op.getValueType()));
9563
9564   unsigned Opcode = 0;
9565   unsigned NumOperands = 0;
9566
9567   // Truncate operations may prevent the merge of the SETCC instruction
9568   // and the arithmetic instruction before it. Attempt to truncate the operands
9569   // of the arithmetic instruction and use a reduced bit-width instruction.
9570   bool NeedTruncation = false;
9571   SDValue ArithOp = Op;
9572   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9573     SDValue Arith = Op->getOperand(0);
9574     // Both the trunc and the arithmetic op need to have one user each.
9575     if (Arith->hasOneUse())
9576       switch (Arith.getOpcode()) {
9577         default: break;
9578         case ISD::ADD:
9579         case ISD::SUB:
9580         case ISD::AND:
9581         case ISD::OR:
9582         case ISD::XOR: {
9583           NeedTruncation = true;
9584           ArithOp = Arith;
9585         }
9586       }
9587   }
9588
9589   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9590   // which may be the result of a CAST.  We use the variable 'Op', which is the
9591   // non-casted variable when we check for possible users.
9592   switch (ArithOp.getOpcode()) {
9593   case ISD::ADD:
9594     // Due to an isel shortcoming, be conservative if this add is likely to be
9595     // selected as part of a load-modify-store instruction. When the root node
9596     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9597     // uses of other nodes in the match, such as the ADD in this case. This
9598     // leads to the ADD being left around and reselected, with the result being
9599     // two adds in the output.  Alas, even if none our users are stores, that
9600     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9601     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9602     // climbing the DAG back to the root, and it doesn't seem to be worth the
9603     // effort.
9604     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9605          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9606       if (UI->getOpcode() != ISD::CopyToReg &&
9607           UI->getOpcode() != ISD::SETCC &&
9608           UI->getOpcode() != ISD::STORE)
9609         goto default_case;
9610
9611     if (ConstantSDNode *C =
9612         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9613       // An add of one will be selected as an INC.
9614       if (C->getAPIntValue() == 1) {
9615         Opcode = X86ISD::INC;
9616         NumOperands = 1;
9617         break;
9618       }
9619
9620       // An add of negative one (subtract of one) will be selected as a DEC.
9621       if (C->getAPIntValue().isAllOnesValue()) {
9622         Opcode = X86ISD::DEC;
9623         NumOperands = 1;
9624         break;
9625       }
9626     }
9627
9628     // Otherwise use a regular EFLAGS-setting add.
9629     Opcode = X86ISD::ADD;
9630     NumOperands = 2;
9631     break;
9632   case ISD::AND: {
9633     // If the primary and result isn't used, don't bother using X86ISD::AND,
9634     // because a TEST instruction will be better.
9635     bool NonFlagUse = false;
9636     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9637            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9638       SDNode *User = *UI;
9639       unsigned UOpNo = UI.getOperandNo();
9640       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9641         // Look pass truncate.
9642         UOpNo = User->use_begin().getOperandNo();
9643         User = *User->use_begin();
9644       }
9645
9646       if (User->getOpcode() != ISD::BRCOND &&
9647           User->getOpcode() != ISD::SETCC &&
9648           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9649         NonFlagUse = true;
9650         break;
9651       }
9652     }
9653
9654     if (!NonFlagUse)
9655       break;
9656   }
9657     // FALL THROUGH
9658   case ISD::SUB:
9659   case ISD::OR:
9660   case ISD::XOR:
9661     // Due to the ISEL shortcoming noted above, be conservative if this op is
9662     // likely to be selected as part of a load-modify-store instruction.
9663     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9664            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9665       if (UI->getOpcode() == ISD::STORE)
9666         goto default_case;
9667
9668     // Otherwise use a regular EFLAGS-setting instruction.
9669     switch (ArithOp.getOpcode()) {
9670     default: llvm_unreachable("unexpected operator!");
9671     case ISD::SUB: Opcode = X86ISD::SUB; break;
9672     case ISD::XOR: Opcode = X86ISD::XOR; break;
9673     case ISD::AND: Opcode = X86ISD::AND; break;
9674     case ISD::OR: {
9675       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9676         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9677         if (EFLAGS.getNode())
9678           return EFLAGS;
9679       }
9680       Opcode = X86ISD::OR;
9681       break;
9682     }
9683     }
9684
9685     NumOperands = 2;
9686     break;
9687   case X86ISD::ADD:
9688   case X86ISD::SUB:
9689   case X86ISD::INC:
9690   case X86ISD::DEC:
9691   case X86ISD::OR:
9692   case X86ISD::XOR:
9693   case X86ISD::AND:
9694     return SDValue(Op.getNode(), 1);
9695   default:
9696   default_case:
9697     break;
9698   }
9699
9700   // If we found that truncation is beneficial, perform the truncation and
9701   // update 'Op'.
9702   if (NeedTruncation) {
9703     EVT VT = Op.getValueType();
9704     SDValue WideVal = Op->getOperand(0);
9705     EVT WideVT = WideVal.getValueType();
9706     unsigned ConvertedOp = 0;
9707     // Use a target machine opcode to prevent further DAGCombine
9708     // optimizations that may separate the arithmetic operations
9709     // from the setcc node.
9710     switch (WideVal.getOpcode()) {
9711       default: break;
9712       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9713       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9714       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9715       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9716       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9717     }
9718
9719     if (ConvertedOp) {
9720       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9721       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9722         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9723         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9724         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9725       }
9726     }
9727   }
9728
9729   if (Opcode == 0)
9730     // Emit a CMP with 0, which is the TEST pattern.
9731     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9732                        DAG.getConstant(0, Op.getValueType()));
9733
9734   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9735   SmallVector<SDValue, 4> Ops;
9736   for (unsigned i = 0; i != NumOperands; ++i)
9737     Ops.push_back(Op.getOperand(i));
9738
9739   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9740   DAG.ReplaceAllUsesWith(Op, New);
9741   return SDValue(New.getNode(), 1);
9742 }
9743
9744 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9745 /// equivalent.
9746 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9747                                    SelectionDAG &DAG) const {
9748   SDLoc dl(Op0);
9749   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9750     if (C->getAPIntValue() == 0)
9751       return EmitTest(Op0, X86CC, DAG);
9752
9753      if (Op0.getValueType() == MVT::i1) {
9754       Op0 = DAG.getNode(ISD::XOR, dl, MVT::i1, Op0, DAG.getConstant(-1, MVT::i1));
9755       return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op0, Op0);
9756      }
9757   }
9758  
9759   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9760        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9761     // Do the comparison at i32 if it's smaller. This avoids subregister
9762     // aliasing issues. Keep the smaller reference if we're optimizing for
9763     // size, however, as that'll allow better folding of memory operations.
9764     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9765         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9766              AttributeSet::FunctionIndex, Attribute::MinSize)) {
9767       unsigned ExtendOp =
9768           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9769       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9770       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9771     }
9772     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9773     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9774     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9775                               Op0, Op1);
9776     return SDValue(Sub.getNode(), 1);
9777   }
9778   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9779 }
9780
9781 /// Convert a comparison if required by the subtarget.
9782 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9783                                                  SelectionDAG &DAG) const {
9784   // If the subtarget does not support the FUCOMI instruction, floating-point
9785   // comparisons have to be converted.
9786   if (Subtarget->hasCMov() ||
9787       Cmp.getOpcode() != X86ISD::CMP ||
9788       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9789       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9790     return Cmp;
9791
9792   // The instruction selector will select an FUCOM instruction instead of
9793   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9794   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9795   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9796   SDLoc dl(Cmp);
9797   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9798   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9799   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9800                             DAG.getConstant(8, MVT::i8));
9801   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9802   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9803 }
9804
9805 static bool isAllOnes(SDValue V) {
9806   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9807   return C && C->isAllOnesValue();
9808 }
9809
9810 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9811 /// if it's possible.
9812 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9813                                      SDLoc dl, SelectionDAG &DAG) const {
9814   SDValue Op0 = And.getOperand(0);
9815   SDValue Op1 = And.getOperand(1);
9816   if (Op0.getOpcode() == ISD::TRUNCATE)
9817     Op0 = Op0.getOperand(0);
9818   if (Op1.getOpcode() == ISD::TRUNCATE)
9819     Op1 = Op1.getOperand(0);
9820
9821   SDValue LHS, RHS;
9822   if (Op1.getOpcode() == ISD::SHL)
9823     std::swap(Op0, Op1);
9824   if (Op0.getOpcode() == ISD::SHL) {
9825     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9826       if (And00C->getZExtValue() == 1) {
9827         // If we looked past a truncate, check that it's only truncating away
9828         // known zeros.
9829         unsigned BitWidth = Op0.getValueSizeInBits();
9830         unsigned AndBitWidth = And.getValueSizeInBits();
9831         if (BitWidth > AndBitWidth) {
9832           APInt Zeros, Ones;
9833           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9834           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9835             return SDValue();
9836         }
9837         LHS = Op1;
9838         RHS = Op0.getOperand(1);
9839       }
9840   } else if (Op1.getOpcode() == ISD::Constant) {
9841     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9842     uint64_t AndRHSVal = AndRHS->getZExtValue();
9843     SDValue AndLHS = Op0;
9844
9845     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9846       LHS = AndLHS.getOperand(0);
9847       RHS = AndLHS.getOperand(1);
9848     }
9849
9850     // Use BT if the immediate can't be encoded in a TEST instruction.
9851     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9852       LHS = AndLHS;
9853       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9854     }
9855   }
9856
9857   if (LHS.getNode()) {
9858     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9859     // instruction.  Since the shift amount is in-range-or-undefined, we know
9860     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9861     // the encoding for the i16 version is larger than the i32 version.
9862     // Also promote i16 to i32 for performance / code size reason.
9863     if (LHS.getValueType() == MVT::i8 ||
9864         LHS.getValueType() == MVT::i16)
9865       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9866
9867     // If the operand types disagree, extend the shift amount to match.  Since
9868     // BT ignores high bits (like shifts) we can use anyextend.
9869     if (LHS.getValueType() != RHS.getValueType())
9870       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9871
9872     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9873     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9874     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9875                        DAG.getConstant(Cond, MVT::i8), BT);
9876   }
9877
9878   return SDValue();
9879 }
9880
9881 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9882 /// mask CMPs.
9883 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9884                               SDValue &Op1) {
9885   unsigned SSECC;
9886   bool Swap = false;
9887
9888   // SSE Condition code mapping:
9889   //  0 - EQ
9890   //  1 - LT
9891   //  2 - LE
9892   //  3 - UNORD
9893   //  4 - NEQ
9894   //  5 - NLT
9895   //  6 - NLE
9896   //  7 - ORD
9897   switch (SetCCOpcode) {
9898   default: llvm_unreachable("Unexpected SETCC condition");
9899   case ISD::SETOEQ:
9900   case ISD::SETEQ:  SSECC = 0; break;
9901   case ISD::SETOGT:
9902   case ISD::SETGT:  Swap = true; // Fallthrough
9903   case ISD::SETLT:
9904   case ISD::SETOLT: SSECC = 1; break;
9905   case ISD::SETOGE:
9906   case ISD::SETGE:  Swap = true; // Fallthrough
9907   case ISD::SETLE:
9908   case ISD::SETOLE: SSECC = 2; break;
9909   case ISD::SETUO:  SSECC = 3; break;
9910   case ISD::SETUNE:
9911   case ISD::SETNE:  SSECC = 4; break;
9912   case ISD::SETULE: Swap = true; // Fallthrough
9913   case ISD::SETUGE: SSECC = 5; break;
9914   case ISD::SETULT: Swap = true; // Fallthrough
9915   case ISD::SETUGT: SSECC = 6; break;
9916   case ISD::SETO:   SSECC = 7; break;
9917   case ISD::SETUEQ:
9918   case ISD::SETONE: SSECC = 8; break;
9919   }
9920   if (Swap)
9921     std::swap(Op0, Op1);
9922
9923   return SSECC;
9924 }
9925
9926 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9927 // ones, and then concatenate the result back.
9928 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9929   MVT VT = Op.getSimpleValueType();
9930
9931   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9932          "Unsupported value type for operation");
9933
9934   unsigned NumElems = VT.getVectorNumElements();
9935   SDLoc dl(Op);
9936   SDValue CC = Op.getOperand(2);
9937
9938   // Extract the LHS vectors
9939   SDValue LHS = Op.getOperand(0);
9940   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9941   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9942
9943   // Extract the RHS vectors
9944   SDValue RHS = Op.getOperand(1);
9945   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9946   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9947
9948   // Issue the operation on the smaller types and concatenate the result back
9949   MVT EltVT = VT.getVectorElementType();
9950   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9951   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9952                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9953                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9954 }
9955
9956 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9957   SDValue Op0 = Op.getOperand(0);
9958   SDValue Op1 = Op.getOperand(1);
9959   SDValue CC = Op.getOperand(2);
9960   MVT VT = Op.getSimpleValueType();
9961
9962   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9963          Op.getValueType().getScalarType() == MVT::i1 &&
9964          "Cannot set masked compare for this operation");
9965
9966   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9967   SDLoc dl(Op);
9968
9969   bool Unsigned = false;
9970   unsigned SSECC;
9971   switch (SetCCOpcode) {
9972   default: llvm_unreachable("Unexpected SETCC condition");
9973   case ISD::SETNE:  SSECC = 4; break;
9974   case ISD::SETEQ:  SSECC = 0; break;
9975   case ISD::SETUGT: Unsigned = true;
9976   case ISD::SETGT:  SSECC = 6; break; // NLE
9977   case ISD::SETULT: Unsigned = true;
9978   case ISD::SETLT:  SSECC = 1; break;
9979   case ISD::SETUGE: Unsigned = true;
9980   case ISD::SETGE:  SSECC = 5; break; // NLT
9981   case ISD::SETULE: Unsigned = true;
9982   case ISD::SETLE:  SSECC = 2; break;
9983   }
9984   unsigned  Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9985   return DAG.getNode(Opc, dl, VT, Op0, Op1,
9986                      DAG.getConstant(SSECC, MVT::i8));
9987
9988 }
9989
9990 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9991                            SelectionDAG &DAG) {
9992   SDValue Op0 = Op.getOperand(0);
9993   SDValue Op1 = Op.getOperand(1);
9994   SDValue CC = Op.getOperand(2);
9995   MVT VT = Op.getSimpleValueType();
9996   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9997   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
9998   SDLoc dl(Op);
9999
10000   if (isFP) {
10001 #ifndef NDEBUG
10002     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10003     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10004 #endif
10005
10006     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10007     unsigned Opc = X86ISD::CMPP;
10008     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10009       assert(VT.getVectorNumElements() <= 16);
10010       Opc = X86ISD::CMPM;
10011     }
10012     // In the two special cases we can't handle, emit two comparisons.
10013     if (SSECC == 8) {
10014       unsigned CC0, CC1;
10015       unsigned CombineOpc;
10016       if (SetCCOpcode == ISD::SETUEQ) {
10017         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10018       } else {
10019         assert(SetCCOpcode == ISD::SETONE);
10020         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10021       }
10022
10023       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10024                                  DAG.getConstant(CC0, MVT::i8));
10025       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10026                                  DAG.getConstant(CC1, MVT::i8));
10027       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10028     }
10029     // Handle all other FP comparisons here.
10030     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10031                        DAG.getConstant(SSECC, MVT::i8));
10032   }
10033
10034   // Break 256-bit integer vector compare into smaller ones.
10035   if (VT.is256BitVector() && !Subtarget->hasInt256())
10036     return Lower256IntVSETCC(Op, DAG);
10037
10038   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10039   EVT OpVT = Op1.getValueType();
10040   if (Subtarget->hasAVX512()) {
10041     if (Op1.getValueType().is512BitVector() ||
10042         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10043       return LowerIntVSETCC_AVX512(Op, DAG);
10044
10045     // In AVX-512 architecture setcc returns mask with i1 elements,
10046     // But there is no compare instruction for i8 and i16 elements.
10047     // We are not talking about 512-bit operands in this case, these
10048     // types are illegal.
10049     if (MaskResult &&
10050         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10051          OpVT.getVectorElementType().getSizeInBits() >= 8))
10052       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10053                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10054   }
10055
10056   // We are handling one of the integer comparisons here.  Since SSE only has
10057   // GT and EQ comparisons for integer, swapping operands and multiple
10058   // operations may be required for some comparisons.
10059   unsigned Opc;
10060   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10061
10062   switch (SetCCOpcode) {
10063   default: llvm_unreachable("Unexpected SETCC condition");
10064   case ISD::SETNE:  Invert = true;
10065   case ISD::SETEQ:  Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
10066   case ISD::SETLT:  Swap = true;
10067   case ISD::SETGT:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
10068   case ISD::SETGE:  Swap = true;
10069   case ISD::SETLE:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10070                     Invert = true; break;
10071   case ISD::SETULT: Swap = true;
10072   case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10073                     FlipSigns = true; break;
10074   case ISD::SETUGE: Swap = true;
10075   case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10076                     FlipSigns = true; Invert = true; break;
10077   }
10078
10079   // Special case: Use min/max operations for SETULE/SETUGE
10080   MVT VET = VT.getVectorElementType();
10081   bool hasMinMax =
10082        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10083     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10084
10085   if (hasMinMax) {
10086     switch (SetCCOpcode) {
10087     default: break;
10088     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10089     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10090     }
10091
10092     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10093   }
10094
10095   if (Swap)
10096     std::swap(Op0, Op1);
10097
10098   // Check that the operation in question is available (most are plain SSE2,
10099   // but PCMPGTQ and PCMPEQQ have different requirements).
10100   if (VT == MVT::v2i64) {
10101     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10102       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10103
10104       // First cast everything to the right type.
10105       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10106       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10107
10108       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10109       // bits of the inputs before performing those operations. The lower
10110       // compare is always unsigned.
10111       SDValue SB;
10112       if (FlipSigns) {
10113         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10114       } else {
10115         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10116         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10117         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10118                          Sign, Zero, Sign, Zero);
10119       }
10120       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10121       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10122
10123       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10124       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10125       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10126
10127       // Create masks for only the low parts/high parts of the 64 bit integers.
10128       static const int MaskHi[] = { 1, 1, 3, 3 };
10129       static const int MaskLo[] = { 0, 0, 2, 2 };
10130       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10131       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10132       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10133
10134       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10135       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10136
10137       if (Invert)
10138         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10139
10140       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10141     }
10142
10143     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10144       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10145       // pcmpeqd + pshufd + pand.
10146       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10147
10148       // First cast everything to the right type.
10149       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10150       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10151
10152       // Do the compare.
10153       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10154
10155       // Make sure the lower and upper halves are both all-ones.
10156       static const int Mask[] = { 1, 0, 3, 2 };
10157       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10158       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10159
10160       if (Invert)
10161         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10162
10163       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10164     }
10165   }
10166
10167   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10168   // bits of the inputs before performing those operations.
10169   if (FlipSigns) {
10170     EVT EltVT = VT.getVectorElementType();
10171     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10172     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10173     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10174   }
10175
10176   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10177
10178   // If the logical-not of the result is required, perform that now.
10179   if (Invert)
10180     Result = DAG.getNOT(dl, Result, VT);
10181
10182   if (MinMax)
10183     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10184
10185   return Result;
10186 }
10187
10188 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10189
10190   MVT VT = Op.getSimpleValueType();
10191
10192   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10193
10194   assert((VT == MVT::i8 || (Subtarget->hasAVX512() && VT == MVT::i1))
10195          && "SetCC type must be 8-bit or 1-bit integer");
10196   SDValue Op0 = Op.getOperand(0);
10197   SDValue Op1 = Op.getOperand(1);
10198   SDLoc dl(Op);
10199   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10200
10201   // Optimize to BT if possible.
10202   // Lower (X & (1 << N)) == 0 to BT(X, N).
10203   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10204   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10205   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10206       Op1.getOpcode() == ISD::Constant &&
10207       cast<ConstantSDNode>(Op1)->isNullValue() &&
10208       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10209     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10210     if (NewSetCC.getNode())
10211       return NewSetCC;
10212   }
10213
10214   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10215   // these.
10216   if (Op1.getOpcode() == ISD::Constant &&
10217       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10218        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10219       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10220
10221     // If the input is a setcc, then reuse the input setcc or use a new one with
10222     // the inverted condition.
10223     if (Op0.getOpcode() == X86ISD::SETCC) {
10224       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10225       bool Invert = (CC == ISD::SETNE) ^
10226         cast<ConstantSDNode>(Op1)->isNullValue();
10227       if (!Invert) return Op0;
10228
10229       CCode = X86::GetOppositeBranchCondition(CCode);
10230       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10231                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
10232     }
10233   }
10234
10235   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10236   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10237   if (X86CC == X86::COND_INVALID)
10238     return SDValue();
10239
10240   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10241   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10242   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10243                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10244 }
10245
10246 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10247 static bool isX86LogicalCmp(SDValue Op) {
10248   unsigned Opc = Op.getNode()->getOpcode();
10249   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10250       Opc == X86ISD::SAHF)
10251     return true;
10252   if (Op.getResNo() == 1 &&
10253       (Opc == X86ISD::ADD ||
10254        Opc == X86ISD::SUB ||
10255        Opc == X86ISD::ADC ||
10256        Opc == X86ISD::SBB ||
10257        Opc == X86ISD::SMUL ||
10258        Opc == X86ISD::UMUL ||
10259        Opc == X86ISD::INC ||
10260        Opc == X86ISD::DEC ||
10261        Opc == X86ISD::OR ||
10262        Opc == X86ISD::XOR ||
10263        Opc == X86ISD::AND))
10264     return true;
10265
10266   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10267     return true;
10268
10269   return false;
10270 }
10271
10272 static bool isZero(SDValue V) {
10273   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10274   return C && C->isNullValue();
10275 }
10276
10277 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10278   if (V.getOpcode() != ISD::TRUNCATE)
10279     return false;
10280
10281   SDValue VOp0 = V.getOperand(0);
10282   unsigned InBits = VOp0.getValueSizeInBits();
10283   unsigned Bits = V.getValueSizeInBits();
10284   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10285 }
10286
10287 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10288   bool addTest = true;
10289   SDValue Cond  = Op.getOperand(0);
10290   SDValue Op1 = Op.getOperand(1);
10291   SDValue Op2 = Op.getOperand(2);
10292   SDLoc DL(Op);
10293   EVT VT = Op1.getValueType();
10294   SDValue CC;
10295
10296   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10297   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10298   // sequence later on.
10299   if (Cond.getOpcode() == ISD::SETCC &&
10300       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10301        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10302       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10303     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10304     int SSECC = translateX86FSETCC(
10305         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10306
10307     if (SSECC != 8) {
10308       if (Subtarget->hasAVX512()) {
10309         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10310                                   DAG.getConstant(SSECC, MVT::i8));
10311         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10312       }
10313       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10314                                 DAG.getConstant(SSECC, MVT::i8));
10315       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10316       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10317       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10318     }
10319   }
10320
10321   if (Cond.getOpcode() == ISD::SETCC) {
10322     SDValue NewCond = LowerSETCC(Cond, DAG);
10323     if (NewCond.getNode())
10324       Cond = NewCond;
10325   }
10326
10327   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10328   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10329   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10330   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10331   if (Cond.getOpcode() == X86ISD::SETCC &&
10332       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10333       isZero(Cond.getOperand(1).getOperand(1))) {
10334     SDValue Cmp = Cond.getOperand(1);
10335
10336     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10337
10338     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10339         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10340       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10341
10342       SDValue CmpOp0 = Cmp.getOperand(0);
10343       // Apply further optimizations for special cases
10344       // (select (x != 0), -1, 0) -> neg & sbb
10345       // (select (x == 0), 0, -1) -> neg & sbb
10346       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10347         if (YC->isNullValue() &&
10348             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10349           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10350           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10351                                     DAG.getConstant(0, CmpOp0.getValueType()),
10352                                     CmpOp0);
10353           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10354                                     DAG.getConstant(X86::COND_B, MVT::i8),
10355                                     SDValue(Neg.getNode(), 1));
10356           return Res;
10357         }
10358
10359       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10360                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10361       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10362
10363       SDValue Res =   // Res = 0 or -1.
10364         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10365                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10366
10367       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10368         Res = DAG.getNOT(DL, Res, Res.getValueType());
10369
10370       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10371       if (N2C == 0 || !N2C->isNullValue())
10372         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10373       return Res;
10374     }
10375   }
10376
10377   // Look past (and (setcc_carry (cmp ...)), 1).
10378   if (Cond.getOpcode() == ISD::AND &&
10379       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10380     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10381     if (C && C->getAPIntValue() == 1)
10382       Cond = Cond.getOperand(0);
10383   }
10384
10385   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10386   // setting operand in place of the X86ISD::SETCC.
10387   unsigned CondOpcode = Cond.getOpcode();
10388   if (CondOpcode == X86ISD::SETCC ||
10389       CondOpcode == X86ISD::SETCC_CARRY) {
10390     CC = Cond.getOperand(0);
10391
10392     SDValue Cmp = Cond.getOperand(1);
10393     unsigned Opc = Cmp.getOpcode();
10394     MVT VT = Op.getSimpleValueType();
10395
10396     bool IllegalFPCMov = false;
10397     if (VT.isFloatingPoint() && !VT.isVector() &&
10398         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10399       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10400
10401     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10402         Opc == X86ISD::BT) { // FIXME
10403       Cond = Cmp;
10404       addTest = false;
10405     }
10406   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10407              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10408              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10409               Cond.getOperand(0).getValueType() != MVT::i8)) {
10410     SDValue LHS = Cond.getOperand(0);
10411     SDValue RHS = Cond.getOperand(1);
10412     unsigned X86Opcode;
10413     unsigned X86Cond;
10414     SDVTList VTs;
10415     switch (CondOpcode) {
10416     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10417     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10418     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10419     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10420     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10421     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10422     default: llvm_unreachable("unexpected overflowing operator");
10423     }
10424     if (CondOpcode == ISD::UMULO)
10425       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10426                           MVT::i32);
10427     else
10428       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10429
10430     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10431
10432     if (CondOpcode == ISD::UMULO)
10433       Cond = X86Op.getValue(2);
10434     else
10435       Cond = X86Op.getValue(1);
10436
10437     CC = DAG.getConstant(X86Cond, MVT::i8);
10438     addTest = false;
10439   }
10440
10441   if (addTest) {
10442     // Look pass the truncate if the high bits are known zero.
10443     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10444         Cond = Cond.getOperand(0);
10445
10446     // We know the result of AND is compared against zero. Try to match
10447     // it to BT.
10448     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10449       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10450       if (NewSetCC.getNode()) {
10451         CC = NewSetCC.getOperand(0);
10452         Cond = NewSetCC.getOperand(1);
10453         addTest = false;
10454       }
10455     }
10456   }
10457
10458   if (addTest) {
10459     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10460     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10461   }
10462
10463   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10464   // a <  b ?  0 : -1 -> RES = setcc_carry
10465   // a >= b ? -1 :  0 -> RES = setcc_carry
10466   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10467   if (Cond.getOpcode() == X86ISD::SUB) {
10468     Cond = ConvertCmpIfNecessary(Cond, DAG);
10469     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10470
10471     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10472         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10473       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10474                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10475       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10476         return DAG.getNOT(DL, Res, Res.getValueType());
10477       return Res;
10478     }
10479   }
10480
10481   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10482   // widen the cmov and push the truncate through. This avoids introducing a new
10483   // branch during isel and doesn't add any extensions.
10484   if (Op.getValueType() == MVT::i8 &&
10485       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10486     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10487     if (T1.getValueType() == T2.getValueType() &&
10488         // Blacklist CopyFromReg to avoid partial register stalls.
10489         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10490       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10491       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10492       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10493     }
10494   }
10495
10496   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10497   // condition is true.
10498   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10499   SDValue Ops[] = { Op2, Op1, CC, Cond };
10500   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10501 }
10502
10503 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10504   MVT VT = Op->getSimpleValueType(0);
10505   SDValue In = Op->getOperand(0);
10506   MVT InVT = In.getSimpleValueType();
10507   SDLoc dl(Op);
10508
10509   unsigned int NumElts = VT.getVectorNumElements();
10510   if (NumElts != 8 && NumElts != 16)
10511     return SDValue();
10512
10513   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10514     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10515
10516   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10517   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10518
10519   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10520   Constant *C = ConstantInt::get(*DAG.getContext(),
10521     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10522
10523   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10524   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10525   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10526                           MachinePointerInfo::getConstantPool(),
10527                           false, false, false, Alignment);
10528   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10529   if (VT.is512BitVector())
10530     return Brcst;
10531   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10532 }
10533
10534 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10535                                 SelectionDAG &DAG) {
10536   MVT VT = Op->getSimpleValueType(0);
10537   SDValue In = Op->getOperand(0);
10538   MVT InVT = In.getSimpleValueType();
10539   SDLoc dl(Op);
10540
10541   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10542     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10543
10544   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10545       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10546       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10547     return SDValue();
10548
10549   if (Subtarget->hasInt256())
10550     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10551
10552   // Optimize vectors in AVX mode
10553   // Sign extend  v8i16 to v8i32 and
10554   //              v4i32 to v4i64
10555   //
10556   // Divide input vector into two parts
10557   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10558   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10559   // concat the vectors to original VT
10560
10561   unsigned NumElems = InVT.getVectorNumElements();
10562   SDValue Undef = DAG.getUNDEF(InVT);
10563
10564   SmallVector<int,8> ShufMask1(NumElems, -1);
10565   for (unsigned i = 0; i != NumElems/2; ++i)
10566     ShufMask1[i] = i;
10567
10568   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10569
10570   SmallVector<int,8> ShufMask2(NumElems, -1);
10571   for (unsigned i = 0; i != NumElems/2; ++i)
10572     ShufMask2[i] = i + NumElems/2;
10573
10574   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10575
10576   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10577                                 VT.getVectorNumElements()/2);
10578
10579   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10580   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10581
10582   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10583 }
10584
10585 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10586 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10587 // from the AND / OR.
10588 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10589   Opc = Op.getOpcode();
10590   if (Opc != ISD::OR && Opc != ISD::AND)
10591     return false;
10592   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10593           Op.getOperand(0).hasOneUse() &&
10594           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10595           Op.getOperand(1).hasOneUse());
10596 }
10597
10598 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10599 // 1 and that the SETCC node has a single use.
10600 static bool isXor1OfSetCC(SDValue Op) {
10601   if (Op.getOpcode() != ISD::XOR)
10602     return false;
10603   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10604   if (N1C && N1C->getAPIntValue() == 1) {
10605     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10606       Op.getOperand(0).hasOneUse();
10607   }
10608   return false;
10609 }
10610
10611 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10612   bool addTest = true;
10613   SDValue Chain = Op.getOperand(0);
10614   SDValue Cond  = Op.getOperand(1);
10615   SDValue Dest  = Op.getOperand(2);
10616   SDLoc dl(Op);
10617   SDValue CC;
10618   bool Inverted = false;
10619
10620   if (Cond.getOpcode() == ISD::SETCC) {
10621     // Check for setcc([su]{add,sub,mul}o == 0).
10622     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10623         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10624         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10625         Cond.getOperand(0).getResNo() == 1 &&
10626         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10627          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10628          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10629          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10630          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10631          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10632       Inverted = true;
10633       Cond = Cond.getOperand(0);
10634     } else {
10635       SDValue NewCond = LowerSETCC(Cond, DAG);
10636       if (NewCond.getNode())
10637         Cond = NewCond;
10638     }
10639   }
10640 #if 0
10641   // FIXME: LowerXALUO doesn't handle these!!
10642   else if (Cond.getOpcode() == X86ISD::ADD  ||
10643            Cond.getOpcode() == X86ISD::SUB  ||
10644            Cond.getOpcode() == X86ISD::SMUL ||
10645            Cond.getOpcode() == X86ISD::UMUL)
10646     Cond = LowerXALUO(Cond, DAG);
10647 #endif
10648
10649   // Look pass (and (setcc_carry (cmp ...)), 1).
10650   if (Cond.getOpcode() == ISD::AND &&
10651       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10652     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10653     if (C && C->getAPIntValue() == 1)
10654       Cond = Cond.getOperand(0);
10655   }
10656
10657   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10658   // setting operand in place of the X86ISD::SETCC.
10659   unsigned CondOpcode = Cond.getOpcode();
10660   if (CondOpcode == X86ISD::SETCC ||
10661       CondOpcode == X86ISD::SETCC_CARRY) {
10662     CC = Cond.getOperand(0);
10663
10664     SDValue Cmp = Cond.getOperand(1);
10665     unsigned Opc = Cmp.getOpcode();
10666     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10667     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10668       Cond = Cmp;
10669       addTest = false;
10670     } else {
10671       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10672       default: break;
10673       case X86::COND_O:
10674       case X86::COND_B:
10675         // These can only come from an arithmetic instruction with overflow,
10676         // e.g. SADDO, UADDO.
10677         Cond = Cond.getNode()->getOperand(1);
10678         addTest = false;
10679         break;
10680       }
10681     }
10682   }
10683   CondOpcode = Cond.getOpcode();
10684   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10685       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10686       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10687        Cond.getOperand(0).getValueType() != MVT::i8)) {
10688     SDValue LHS = Cond.getOperand(0);
10689     SDValue RHS = Cond.getOperand(1);
10690     unsigned X86Opcode;
10691     unsigned X86Cond;
10692     SDVTList VTs;
10693     switch (CondOpcode) {
10694     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10695     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10696     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10697     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10698     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10699     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10700     default: llvm_unreachable("unexpected overflowing operator");
10701     }
10702     if (Inverted)
10703       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10704     if (CondOpcode == ISD::UMULO)
10705       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10706                           MVT::i32);
10707     else
10708       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10709
10710     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10711
10712     if (CondOpcode == ISD::UMULO)
10713       Cond = X86Op.getValue(2);
10714     else
10715       Cond = X86Op.getValue(1);
10716
10717     CC = DAG.getConstant(X86Cond, MVT::i8);
10718     addTest = false;
10719   } else {
10720     unsigned CondOpc;
10721     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10722       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10723       if (CondOpc == ISD::OR) {
10724         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10725         // two branches instead of an explicit OR instruction with a
10726         // separate test.
10727         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10728             isX86LogicalCmp(Cmp)) {
10729           CC = Cond.getOperand(0).getOperand(0);
10730           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10731                               Chain, Dest, CC, Cmp);
10732           CC = Cond.getOperand(1).getOperand(0);
10733           Cond = Cmp;
10734           addTest = false;
10735         }
10736       } else { // ISD::AND
10737         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10738         // two branches instead of an explicit AND instruction with a
10739         // separate test. However, we only do this if this block doesn't
10740         // have a fall-through edge, because this requires an explicit
10741         // jmp when the condition is false.
10742         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10743             isX86LogicalCmp(Cmp) &&
10744             Op.getNode()->hasOneUse()) {
10745           X86::CondCode CCode =
10746             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10747           CCode = X86::GetOppositeBranchCondition(CCode);
10748           CC = DAG.getConstant(CCode, MVT::i8);
10749           SDNode *User = *Op.getNode()->use_begin();
10750           // Look for an unconditional branch following this conditional branch.
10751           // We need this because we need to reverse the successors in order
10752           // to implement FCMP_OEQ.
10753           if (User->getOpcode() == ISD::BR) {
10754             SDValue FalseBB = User->getOperand(1);
10755             SDNode *NewBR =
10756               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10757             assert(NewBR == User);
10758             (void)NewBR;
10759             Dest = FalseBB;
10760
10761             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10762                                 Chain, Dest, CC, Cmp);
10763             X86::CondCode CCode =
10764               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10765             CCode = X86::GetOppositeBranchCondition(CCode);
10766             CC = DAG.getConstant(CCode, MVT::i8);
10767             Cond = Cmp;
10768             addTest = false;
10769           }
10770         }
10771       }
10772     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10773       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10774       // It should be transformed during dag combiner except when the condition
10775       // is set by a arithmetics with overflow node.
10776       X86::CondCode CCode =
10777         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10778       CCode = X86::GetOppositeBranchCondition(CCode);
10779       CC = DAG.getConstant(CCode, MVT::i8);
10780       Cond = Cond.getOperand(0).getOperand(1);
10781       addTest = false;
10782     } else if (Cond.getOpcode() == ISD::SETCC &&
10783                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10784       // For FCMP_OEQ, we can emit
10785       // two branches instead of an explicit AND instruction with a
10786       // separate test. However, we only do this if this block doesn't
10787       // have a fall-through edge, because this requires an explicit
10788       // jmp when the condition is false.
10789       if (Op.getNode()->hasOneUse()) {
10790         SDNode *User = *Op.getNode()->use_begin();
10791         // Look for an unconditional branch following this conditional branch.
10792         // We need this because we need to reverse the successors in order
10793         // to implement FCMP_OEQ.
10794         if (User->getOpcode() == ISD::BR) {
10795           SDValue FalseBB = User->getOperand(1);
10796           SDNode *NewBR =
10797             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10798           assert(NewBR == User);
10799           (void)NewBR;
10800           Dest = FalseBB;
10801
10802           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10803                                     Cond.getOperand(0), Cond.getOperand(1));
10804           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10805           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10806           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10807                               Chain, Dest, CC, Cmp);
10808           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10809           Cond = Cmp;
10810           addTest = false;
10811         }
10812       }
10813     } else if (Cond.getOpcode() == ISD::SETCC &&
10814                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10815       // For FCMP_UNE, we can emit
10816       // two branches instead of an explicit AND instruction with a
10817       // separate test. However, we only do this if this block doesn't
10818       // have a fall-through edge, because this requires an explicit
10819       // jmp when the condition is false.
10820       if (Op.getNode()->hasOneUse()) {
10821         SDNode *User = *Op.getNode()->use_begin();
10822         // Look for an unconditional branch following this conditional branch.
10823         // We need this because we need to reverse the successors in order
10824         // to implement FCMP_UNE.
10825         if (User->getOpcode() == ISD::BR) {
10826           SDValue FalseBB = User->getOperand(1);
10827           SDNode *NewBR =
10828             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10829           assert(NewBR == User);
10830           (void)NewBR;
10831
10832           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10833                                     Cond.getOperand(0), Cond.getOperand(1));
10834           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10835           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10836           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10837                               Chain, Dest, CC, Cmp);
10838           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10839           Cond = Cmp;
10840           addTest = false;
10841           Dest = FalseBB;
10842         }
10843       }
10844     }
10845   }
10846
10847   if (addTest) {
10848     // Look pass the truncate if the high bits are known zero.
10849     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10850         Cond = Cond.getOperand(0);
10851
10852     // We know the result of AND is compared against zero. Try to match
10853     // it to BT.
10854     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10855       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10856       if (NewSetCC.getNode()) {
10857         CC = NewSetCC.getOperand(0);
10858         Cond = NewSetCC.getOperand(1);
10859         addTest = false;
10860       }
10861     }
10862   }
10863
10864   if (addTest) {
10865     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10866     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10867   }
10868   Cond = ConvertCmpIfNecessary(Cond, DAG);
10869   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10870                      Chain, Dest, CC, Cond);
10871 }
10872
10873 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10874 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10875 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10876 // that the guard pages used by the OS virtual memory manager are allocated in
10877 // correct sequence.
10878 SDValue
10879 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10880                                            SelectionDAG &DAG) const {
10881   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10882           getTargetMachine().Options.EnableSegmentedStacks) &&
10883          "This should be used only on Windows targets or when segmented stacks "
10884          "are being used");
10885   assert(!Subtarget->isTargetMacho() && "Not implemented");
10886   SDLoc dl(Op);
10887
10888   // Get the inputs.
10889   SDValue Chain = Op.getOperand(0);
10890   SDValue Size  = Op.getOperand(1);
10891   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10892   EVT VT = Op.getNode()->getValueType(0);
10893
10894   bool Is64Bit = Subtarget->is64Bit();
10895   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10896
10897   if (getTargetMachine().Options.EnableSegmentedStacks) {
10898     MachineFunction &MF = DAG.getMachineFunction();
10899     MachineRegisterInfo &MRI = MF.getRegInfo();
10900
10901     if (Is64Bit) {
10902       // The 64 bit implementation of segmented stacks needs to clobber both r10
10903       // r11. This makes it impossible to use it along with nested parameters.
10904       const Function *F = MF.getFunction();
10905
10906       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10907            I != E; ++I)
10908         if (I->hasNestAttr())
10909           report_fatal_error("Cannot use segmented stacks with functions that "
10910                              "have nested arguments.");
10911     }
10912
10913     const TargetRegisterClass *AddrRegClass =
10914       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10915     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10916     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10917     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10918                                 DAG.getRegister(Vreg, SPTy));
10919     SDValue Ops1[2] = { Value, Chain };
10920     return DAG.getMergeValues(Ops1, 2, dl);
10921   } else {
10922     SDValue Flag;
10923     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10924
10925     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10926     Flag = Chain.getValue(1);
10927     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10928
10929     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10930
10931     const X86RegisterInfo *RegInfo =
10932       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10933     unsigned SPReg = RegInfo->getStackRegister();
10934     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
10935     Chain = SP.getValue(1);
10936
10937     if (Align) {
10938       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10939                        DAG.getConstant(-(uint64_t)Align, VT));
10940       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
10941     }
10942
10943     SDValue Ops1[2] = { SP, Chain };
10944     return DAG.getMergeValues(Ops1, 2, dl);
10945   }
10946 }
10947
10948 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10949   MachineFunction &MF = DAG.getMachineFunction();
10950   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10951
10952   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10953   SDLoc DL(Op);
10954
10955   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10956     // vastart just stores the address of the VarArgsFrameIndex slot into the
10957     // memory location argument.
10958     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10959                                    getPointerTy());
10960     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10961                         MachinePointerInfo(SV), false, false, 0);
10962   }
10963
10964   // __va_list_tag:
10965   //   gp_offset         (0 - 6 * 8)
10966   //   fp_offset         (48 - 48 + 8 * 16)
10967   //   overflow_arg_area (point to parameters coming in memory).
10968   //   reg_save_area
10969   SmallVector<SDValue, 8> MemOps;
10970   SDValue FIN = Op.getOperand(1);
10971   // Store gp_offset
10972   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10973                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10974                                                MVT::i32),
10975                                FIN, MachinePointerInfo(SV), false, false, 0);
10976   MemOps.push_back(Store);
10977
10978   // Store fp_offset
10979   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10980                     FIN, DAG.getIntPtrConstant(4));
10981   Store = DAG.getStore(Op.getOperand(0), DL,
10982                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10983                                        MVT::i32),
10984                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10985   MemOps.push_back(Store);
10986
10987   // Store ptr to overflow_arg_area
10988   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10989                     FIN, DAG.getIntPtrConstant(4));
10990   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10991                                     getPointerTy());
10992   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10993                        MachinePointerInfo(SV, 8),
10994                        false, false, 0);
10995   MemOps.push_back(Store);
10996
10997   // Store ptr to reg_save_area.
10998   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10999                     FIN, DAG.getIntPtrConstant(8));
11000   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11001                                     getPointerTy());
11002   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11003                        MachinePointerInfo(SV, 16), false, false, 0);
11004   MemOps.push_back(Store);
11005   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11006                      &MemOps[0], MemOps.size());
11007 }
11008
11009 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11010   assert(Subtarget->is64Bit() &&
11011          "LowerVAARG only handles 64-bit va_arg!");
11012   assert((Subtarget->isTargetLinux() ||
11013           Subtarget->isTargetDarwin()) &&
11014           "Unhandled target in LowerVAARG");
11015   assert(Op.getNode()->getNumOperands() == 4);
11016   SDValue Chain = Op.getOperand(0);
11017   SDValue SrcPtr = Op.getOperand(1);
11018   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11019   unsigned Align = Op.getConstantOperandVal(3);
11020   SDLoc dl(Op);
11021
11022   EVT ArgVT = Op.getNode()->getValueType(0);
11023   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11024   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11025   uint8_t ArgMode;
11026
11027   // Decide which area this value should be read from.
11028   // TODO: Implement the AMD64 ABI in its entirety. This simple
11029   // selection mechanism works only for the basic types.
11030   if (ArgVT == MVT::f80) {
11031     llvm_unreachable("va_arg for f80 not yet implemented");
11032   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11033     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11034   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11035     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11036   } else {
11037     llvm_unreachable("Unhandled argument type in LowerVAARG");
11038   }
11039
11040   if (ArgMode == 2) {
11041     // Sanity Check: Make sure using fp_offset makes sense.
11042     assert(!getTargetMachine().Options.UseSoftFloat &&
11043            !(DAG.getMachineFunction()
11044                 .getFunction()->getAttributes()
11045                 .hasAttribute(AttributeSet::FunctionIndex,
11046                               Attribute::NoImplicitFloat)) &&
11047            Subtarget->hasSSE1());
11048   }
11049
11050   // Insert VAARG_64 node into the DAG
11051   // VAARG_64 returns two values: Variable Argument Address, Chain
11052   SmallVector<SDValue, 11> InstOps;
11053   InstOps.push_back(Chain);
11054   InstOps.push_back(SrcPtr);
11055   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11056   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11057   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11058   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11059   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11060                                           VTs, &InstOps[0], InstOps.size(),
11061                                           MVT::i64,
11062                                           MachinePointerInfo(SV),
11063                                           /*Align=*/0,
11064                                           /*Volatile=*/false,
11065                                           /*ReadMem=*/true,
11066                                           /*WriteMem=*/true);
11067   Chain = VAARG.getValue(1);
11068
11069   // Load the next argument and return it
11070   return DAG.getLoad(ArgVT, dl,
11071                      Chain,
11072                      VAARG,
11073                      MachinePointerInfo(),
11074                      false, false, false, 0);
11075 }
11076
11077 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11078                            SelectionDAG &DAG) {
11079   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11080   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11081   SDValue Chain = Op.getOperand(0);
11082   SDValue DstPtr = Op.getOperand(1);
11083   SDValue SrcPtr = Op.getOperand(2);
11084   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11085   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11086   SDLoc DL(Op);
11087
11088   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11089                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11090                        false,
11091                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11092 }
11093
11094 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11095 // amount is a constant. Takes immediate version of shift as input.
11096 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, EVT VT,
11097                                           SDValue SrcOp, uint64_t ShiftAmt,
11098                                           SelectionDAG &DAG) {
11099
11100   // Check for ShiftAmt >= element width
11101   if (ShiftAmt >= VT.getVectorElementType().getSizeInBits()) {
11102     if (Opc == X86ISD::VSRAI)
11103       ShiftAmt = VT.getVectorElementType().getSizeInBits() - 1;
11104     else
11105       return DAG.getConstant(0, VT);
11106   }
11107
11108   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11109          && "Unknown target vector shift-by-constant node");
11110
11111   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11112 }
11113
11114 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11115 // may or may not be a constant. Takes immediate version of shift as input.
11116 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
11117                                    SDValue SrcOp, SDValue ShAmt,
11118                                    SelectionDAG &DAG) {
11119   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11120
11121   // Catch shift-by-constant.
11122   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11123     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11124                                       CShAmt->getZExtValue(), DAG);
11125
11126   // Change opcode to non-immediate version
11127   switch (Opc) {
11128     default: llvm_unreachable("Unknown target vector shift node");
11129     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11130     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11131     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11132   }
11133
11134   // Need to build a vector containing shift amount
11135   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11136   SDValue ShOps[4];
11137   ShOps[0] = ShAmt;
11138   ShOps[1] = DAG.getConstant(0, MVT::i32);
11139   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11140   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11141
11142   // The return type has to be a 128-bit type with the same element
11143   // type as the input type.
11144   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11145   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11146
11147   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11148   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11149 }
11150
11151 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11152   SDLoc dl(Op);
11153   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11154   switch (IntNo) {
11155   default: return SDValue();    // Don't custom lower most intrinsics.
11156   // Comparison intrinsics.
11157   case Intrinsic::x86_sse_comieq_ss:
11158   case Intrinsic::x86_sse_comilt_ss:
11159   case Intrinsic::x86_sse_comile_ss:
11160   case Intrinsic::x86_sse_comigt_ss:
11161   case Intrinsic::x86_sse_comige_ss:
11162   case Intrinsic::x86_sse_comineq_ss:
11163   case Intrinsic::x86_sse_ucomieq_ss:
11164   case Intrinsic::x86_sse_ucomilt_ss:
11165   case Intrinsic::x86_sse_ucomile_ss:
11166   case Intrinsic::x86_sse_ucomigt_ss:
11167   case Intrinsic::x86_sse_ucomige_ss:
11168   case Intrinsic::x86_sse_ucomineq_ss:
11169   case Intrinsic::x86_sse2_comieq_sd:
11170   case Intrinsic::x86_sse2_comilt_sd:
11171   case Intrinsic::x86_sse2_comile_sd:
11172   case Intrinsic::x86_sse2_comigt_sd:
11173   case Intrinsic::x86_sse2_comige_sd:
11174   case Intrinsic::x86_sse2_comineq_sd:
11175   case Intrinsic::x86_sse2_ucomieq_sd:
11176   case Intrinsic::x86_sse2_ucomilt_sd:
11177   case Intrinsic::x86_sse2_ucomile_sd:
11178   case Intrinsic::x86_sse2_ucomigt_sd:
11179   case Intrinsic::x86_sse2_ucomige_sd:
11180   case Intrinsic::x86_sse2_ucomineq_sd: {
11181     unsigned Opc;
11182     ISD::CondCode CC;
11183     switch (IntNo) {
11184     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11185     case Intrinsic::x86_sse_comieq_ss:
11186     case Intrinsic::x86_sse2_comieq_sd:
11187       Opc = X86ISD::COMI;
11188       CC = ISD::SETEQ;
11189       break;
11190     case Intrinsic::x86_sse_comilt_ss:
11191     case Intrinsic::x86_sse2_comilt_sd:
11192       Opc = X86ISD::COMI;
11193       CC = ISD::SETLT;
11194       break;
11195     case Intrinsic::x86_sse_comile_ss:
11196     case Intrinsic::x86_sse2_comile_sd:
11197       Opc = X86ISD::COMI;
11198       CC = ISD::SETLE;
11199       break;
11200     case Intrinsic::x86_sse_comigt_ss:
11201     case Intrinsic::x86_sse2_comigt_sd:
11202       Opc = X86ISD::COMI;
11203       CC = ISD::SETGT;
11204       break;
11205     case Intrinsic::x86_sse_comige_ss:
11206     case Intrinsic::x86_sse2_comige_sd:
11207       Opc = X86ISD::COMI;
11208       CC = ISD::SETGE;
11209       break;
11210     case Intrinsic::x86_sse_comineq_ss:
11211     case Intrinsic::x86_sse2_comineq_sd:
11212       Opc = X86ISD::COMI;
11213       CC = ISD::SETNE;
11214       break;
11215     case Intrinsic::x86_sse_ucomieq_ss:
11216     case Intrinsic::x86_sse2_ucomieq_sd:
11217       Opc = X86ISD::UCOMI;
11218       CC = ISD::SETEQ;
11219       break;
11220     case Intrinsic::x86_sse_ucomilt_ss:
11221     case Intrinsic::x86_sse2_ucomilt_sd:
11222       Opc = X86ISD::UCOMI;
11223       CC = ISD::SETLT;
11224       break;
11225     case Intrinsic::x86_sse_ucomile_ss:
11226     case Intrinsic::x86_sse2_ucomile_sd:
11227       Opc = X86ISD::UCOMI;
11228       CC = ISD::SETLE;
11229       break;
11230     case Intrinsic::x86_sse_ucomigt_ss:
11231     case Intrinsic::x86_sse2_ucomigt_sd:
11232       Opc = X86ISD::UCOMI;
11233       CC = ISD::SETGT;
11234       break;
11235     case Intrinsic::x86_sse_ucomige_ss:
11236     case Intrinsic::x86_sse2_ucomige_sd:
11237       Opc = X86ISD::UCOMI;
11238       CC = ISD::SETGE;
11239       break;
11240     case Intrinsic::x86_sse_ucomineq_ss:
11241     case Intrinsic::x86_sse2_ucomineq_sd:
11242       Opc = X86ISD::UCOMI;
11243       CC = ISD::SETNE;
11244       break;
11245     }
11246
11247     SDValue LHS = Op.getOperand(1);
11248     SDValue RHS = Op.getOperand(2);
11249     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11250     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11251     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11252     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11253                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11254     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11255   }
11256
11257   // Arithmetic intrinsics.
11258   case Intrinsic::x86_sse2_pmulu_dq:
11259   case Intrinsic::x86_avx2_pmulu_dq:
11260     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11261                        Op.getOperand(1), Op.getOperand(2));
11262
11263   // SSE2/AVX2 sub with unsigned saturation intrinsics
11264   case Intrinsic::x86_sse2_psubus_b:
11265   case Intrinsic::x86_sse2_psubus_w:
11266   case Intrinsic::x86_avx2_psubus_b:
11267   case Intrinsic::x86_avx2_psubus_w:
11268     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11269                        Op.getOperand(1), Op.getOperand(2));
11270
11271   // SSE3/AVX horizontal add/sub intrinsics
11272   case Intrinsic::x86_sse3_hadd_ps:
11273   case Intrinsic::x86_sse3_hadd_pd:
11274   case Intrinsic::x86_avx_hadd_ps_256:
11275   case Intrinsic::x86_avx_hadd_pd_256:
11276   case Intrinsic::x86_sse3_hsub_ps:
11277   case Intrinsic::x86_sse3_hsub_pd:
11278   case Intrinsic::x86_avx_hsub_ps_256:
11279   case Intrinsic::x86_avx_hsub_pd_256:
11280   case Intrinsic::x86_ssse3_phadd_w_128:
11281   case Intrinsic::x86_ssse3_phadd_d_128:
11282   case Intrinsic::x86_avx2_phadd_w:
11283   case Intrinsic::x86_avx2_phadd_d:
11284   case Intrinsic::x86_ssse3_phsub_w_128:
11285   case Intrinsic::x86_ssse3_phsub_d_128:
11286   case Intrinsic::x86_avx2_phsub_w:
11287   case Intrinsic::x86_avx2_phsub_d: {
11288     unsigned Opcode;
11289     switch (IntNo) {
11290     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11291     case Intrinsic::x86_sse3_hadd_ps:
11292     case Intrinsic::x86_sse3_hadd_pd:
11293     case Intrinsic::x86_avx_hadd_ps_256:
11294     case Intrinsic::x86_avx_hadd_pd_256:
11295       Opcode = X86ISD::FHADD;
11296       break;
11297     case Intrinsic::x86_sse3_hsub_ps:
11298     case Intrinsic::x86_sse3_hsub_pd:
11299     case Intrinsic::x86_avx_hsub_ps_256:
11300     case Intrinsic::x86_avx_hsub_pd_256:
11301       Opcode = X86ISD::FHSUB;
11302       break;
11303     case Intrinsic::x86_ssse3_phadd_w_128:
11304     case Intrinsic::x86_ssse3_phadd_d_128:
11305     case Intrinsic::x86_avx2_phadd_w:
11306     case Intrinsic::x86_avx2_phadd_d:
11307       Opcode = X86ISD::HADD;
11308       break;
11309     case Intrinsic::x86_ssse3_phsub_w_128:
11310     case Intrinsic::x86_ssse3_phsub_d_128:
11311     case Intrinsic::x86_avx2_phsub_w:
11312     case Intrinsic::x86_avx2_phsub_d:
11313       Opcode = X86ISD::HSUB;
11314       break;
11315     }
11316     return DAG.getNode(Opcode, dl, Op.getValueType(),
11317                        Op.getOperand(1), Op.getOperand(2));
11318   }
11319
11320   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11321   case Intrinsic::x86_sse2_pmaxu_b:
11322   case Intrinsic::x86_sse41_pmaxuw:
11323   case Intrinsic::x86_sse41_pmaxud:
11324   case Intrinsic::x86_avx2_pmaxu_b:
11325   case Intrinsic::x86_avx2_pmaxu_w:
11326   case Intrinsic::x86_avx2_pmaxu_d:
11327   case Intrinsic::x86_avx512_pmaxu_d:
11328   case Intrinsic::x86_avx512_pmaxu_q:
11329   case Intrinsic::x86_sse2_pminu_b:
11330   case Intrinsic::x86_sse41_pminuw:
11331   case Intrinsic::x86_sse41_pminud:
11332   case Intrinsic::x86_avx2_pminu_b:
11333   case Intrinsic::x86_avx2_pminu_w:
11334   case Intrinsic::x86_avx2_pminu_d:
11335   case Intrinsic::x86_avx512_pminu_d:
11336   case Intrinsic::x86_avx512_pminu_q:
11337   case Intrinsic::x86_sse41_pmaxsb:
11338   case Intrinsic::x86_sse2_pmaxs_w:
11339   case Intrinsic::x86_sse41_pmaxsd:
11340   case Intrinsic::x86_avx2_pmaxs_b:
11341   case Intrinsic::x86_avx2_pmaxs_w:
11342   case Intrinsic::x86_avx2_pmaxs_d:
11343   case Intrinsic::x86_avx512_pmaxs_d:
11344   case Intrinsic::x86_avx512_pmaxs_q:
11345   case Intrinsic::x86_sse41_pminsb:
11346   case Intrinsic::x86_sse2_pmins_w:
11347   case Intrinsic::x86_sse41_pminsd:
11348   case Intrinsic::x86_avx2_pmins_b:
11349   case Intrinsic::x86_avx2_pmins_w:
11350   case Intrinsic::x86_avx2_pmins_d:
11351   case Intrinsic::x86_avx512_pmins_d:
11352   case Intrinsic::x86_avx512_pmins_q: {
11353     unsigned Opcode;
11354     switch (IntNo) {
11355     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11356     case Intrinsic::x86_sse2_pmaxu_b:
11357     case Intrinsic::x86_sse41_pmaxuw:
11358     case Intrinsic::x86_sse41_pmaxud:
11359     case Intrinsic::x86_avx2_pmaxu_b:
11360     case Intrinsic::x86_avx2_pmaxu_w:
11361     case Intrinsic::x86_avx2_pmaxu_d:
11362     case Intrinsic::x86_avx512_pmaxu_d:
11363     case Intrinsic::x86_avx512_pmaxu_q:
11364       Opcode = X86ISD::UMAX;
11365       break;
11366     case Intrinsic::x86_sse2_pminu_b:
11367     case Intrinsic::x86_sse41_pminuw:
11368     case Intrinsic::x86_sse41_pminud:
11369     case Intrinsic::x86_avx2_pminu_b:
11370     case Intrinsic::x86_avx2_pminu_w:
11371     case Intrinsic::x86_avx2_pminu_d:
11372     case Intrinsic::x86_avx512_pminu_d:
11373     case Intrinsic::x86_avx512_pminu_q:
11374       Opcode = X86ISD::UMIN;
11375       break;
11376     case Intrinsic::x86_sse41_pmaxsb:
11377     case Intrinsic::x86_sse2_pmaxs_w:
11378     case Intrinsic::x86_sse41_pmaxsd:
11379     case Intrinsic::x86_avx2_pmaxs_b:
11380     case Intrinsic::x86_avx2_pmaxs_w:
11381     case Intrinsic::x86_avx2_pmaxs_d:
11382     case Intrinsic::x86_avx512_pmaxs_d:
11383     case Intrinsic::x86_avx512_pmaxs_q:
11384       Opcode = X86ISD::SMAX;
11385       break;
11386     case Intrinsic::x86_sse41_pminsb:
11387     case Intrinsic::x86_sse2_pmins_w:
11388     case Intrinsic::x86_sse41_pminsd:
11389     case Intrinsic::x86_avx2_pmins_b:
11390     case Intrinsic::x86_avx2_pmins_w:
11391     case Intrinsic::x86_avx2_pmins_d:
11392     case Intrinsic::x86_avx512_pmins_d:
11393     case Intrinsic::x86_avx512_pmins_q:
11394       Opcode = X86ISD::SMIN;
11395       break;
11396     }
11397     return DAG.getNode(Opcode, dl, Op.getValueType(),
11398                        Op.getOperand(1), Op.getOperand(2));
11399   }
11400
11401   // SSE/SSE2/AVX floating point max/min intrinsics.
11402   case Intrinsic::x86_sse_max_ps:
11403   case Intrinsic::x86_sse2_max_pd:
11404   case Intrinsic::x86_avx_max_ps_256:
11405   case Intrinsic::x86_avx_max_pd_256:
11406   case Intrinsic::x86_avx512_max_ps_512:
11407   case Intrinsic::x86_avx512_max_pd_512:
11408   case Intrinsic::x86_sse_min_ps:
11409   case Intrinsic::x86_sse2_min_pd:
11410   case Intrinsic::x86_avx_min_ps_256:
11411   case Intrinsic::x86_avx_min_pd_256:
11412   case Intrinsic::x86_avx512_min_ps_512:
11413   case Intrinsic::x86_avx512_min_pd_512:  {
11414     unsigned Opcode;
11415     switch (IntNo) {
11416     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11417     case Intrinsic::x86_sse_max_ps:
11418     case Intrinsic::x86_sse2_max_pd:
11419     case Intrinsic::x86_avx_max_ps_256:
11420     case Intrinsic::x86_avx_max_pd_256:
11421     case Intrinsic::x86_avx512_max_ps_512:
11422     case Intrinsic::x86_avx512_max_pd_512:
11423       Opcode = X86ISD::FMAX;
11424       break;
11425     case Intrinsic::x86_sse_min_ps:
11426     case Intrinsic::x86_sse2_min_pd:
11427     case Intrinsic::x86_avx_min_ps_256:
11428     case Intrinsic::x86_avx_min_pd_256:
11429     case Intrinsic::x86_avx512_min_ps_512:
11430     case Intrinsic::x86_avx512_min_pd_512:
11431       Opcode = X86ISD::FMIN;
11432       break;
11433     }
11434     return DAG.getNode(Opcode, dl, Op.getValueType(),
11435                        Op.getOperand(1), Op.getOperand(2));
11436   }
11437
11438   // AVX2 variable shift intrinsics
11439   case Intrinsic::x86_avx2_psllv_d:
11440   case Intrinsic::x86_avx2_psllv_q:
11441   case Intrinsic::x86_avx2_psllv_d_256:
11442   case Intrinsic::x86_avx2_psllv_q_256:
11443   case Intrinsic::x86_avx2_psrlv_d:
11444   case Intrinsic::x86_avx2_psrlv_q:
11445   case Intrinsic::x86_avx2_psrlv_d_256:
11446   case Intrinsic::x86_avx2_psrlv_q_256:
11447   case Intrinsic::x86_avx2_psrav_d:
11448   case Intrinsic::x86_avx2_psrav_d_256: {
11449     unsigned Opcode;
11450     switch (IntNo) {
11451     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11452     case Intrinsic::x86_avx2_psllv_d:
11453     case Intrinsic::x86_avx2_psllv_q:
11454     case Intrinsic::x86_avx2_psllv_d_256:
11455     case Intrinsic::x86_avx2_psllv_q_256:
11456       Opcode = ISD::SHL;
11457       break;
11458     case Intrinsic::x86_avx2_psrlv_d:
11459     case Intrinsic::x86_avx2_psrlv_q:
11460     case Intrinsic::x86_avx2_psrlv_d_256:
11461     case Intrinsic::x86_avx2_psrlv_q_256:
11462       Opcode = ISD::SRL;
11463       break;
11464     case Intrinsic::x86_avx2_psrav_d:
11465     case Intrinsic::x86_avx2_psrav_d_256:
11466       Opcode = ISD::SRA;
11467       break;
11468     }
11469     return DAG.getNode(Opcode, dl, Op.getValueType(),
11470                        Op.getOperand(1), Op.getOperand(2));
11471   }
11472
11473   case Intrinsic::x86_ssse3_pshuf_b_128:
11474   case Intrinsic::x86_avx2_pshuf_b:
11475     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11476                        Op.getOperand(1), Op.getOperand(2));
11477
11478   case Intrinsic::x86_ssse3_psign_b_128:
11479   case Intrinsic::x86_ssse3_psign_w_128:
11480   case Intrinsic::x86_ssse3_psign_d_128:
11481   case Intrinsic::x86_avx2_psign_b:
11482   case Intrinsic::x86_avx2_psign_w:
11483   case Intrinsic::x86_avx2_psign_d:
11484     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11485                        Op.getOperand(1), Op.getOperand(2));
11486
11487   case Intrinsic::x86_sse41_insertps:
11488     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11489                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11490
11491   case Intrinsic::x86_avx_vperm2f128_ps_256:
11492   case Intrinsic::x86_avx_vperm2f128_pd_256:
11493   case Intrinsic::x86_avx_vperm2f128_si_256:
11494   case Intrinsic::x86_avx2_vperm2i128:
11495     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11496                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11497
11498   case Intrinsic::x86_avx2_permd:
11499   case Intrinsic::x86_avx2_permps:
11500     // Operands intentionally swapped. Mask is last operand to intrinsic,
11501     // but second operand for node/instruction.
11502     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11503                        Op.getOperand(2), Op.getOperand(1));
11504
11505   case Intrinsic::x86_sse_sqrt_ps:
11506   case Intrinsic::x86_sse2_sqrt_pd:
11507   case Intrinsic::x86_avx_sqrt_ps_256:
11508   case Intrinsic::x86_avx_sqrt_pd_256:
11509     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11510
11511   // ptest and testp intrinsics. The intrinsic these come from are designed to
11512   // return an integer value, not just an instruction so lower it to the ptest
11513   // or testp pattern and a setcc for the result.
11514   case Intrinsic::x86_sse41_ptestz:
11515   case Intrinsic::x86_sse41_ptestc:
11516   case Intrinsic::x86_sse41_ptestnzc:
11517   case Intrinsic::x86_avx_ptestz_256:
11518   case Intrinsic::x86_avx_ptestc_256:
11519   case Intrinsic::x86_avx_ptestnzc_256:
11520   case Intrinsic::x86_avx_vtestz_ps:
11521   case Intrinsic::x86_avx_vtestc_ps:
11522   case Intrinsic::x86_avx_vtestnzc_ps:
11523   case Intrinsic::x86_avx_vtestz_pd:
11524   case Intrinsic::x86_avx_vtestc_pd:
11525   case Intrinsic::x86_avx_vtestnzc_pd:
11526   case Intrinsic::x86_avx_vtestz_ps_256:
11527   case Intrinsic::x86_avx_vtestc_ps_256:
11528   case Intrinsic::x86_avx_vtestnzc_ps_256:
11529   case Intrinsic::x86_avx_vtestz_pd_256:
11530   case Intrinsic::x86_avx_vtestc_pd_256:
11531   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11532     bool IsTestPacked = false;
11533     unsigned X86CC;
11534     switch (IntNo) {
11535     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11536     case Intrinsic::x86_avx_vtestz_ps:
11537     case Intrinsic::x86_avx_vtestz_pd:
11538     case Intrinsic::x86_avx_vtestz_ps_256:
11539     case Intrinsic::x86_avx_vtestz_pd_256:
11540       IsTestPacked = true; // Fallthrough
11541     case Intrinsic::x86_sse41_ptestz:
11542     case Intrinsic::x86_avx_ptestz_256:
11543       // ZF = 1
11544       X86CC = X86::COND_E;
11545       break;
11546     case Intrinsic::x86_avx_vtestc_ps:
11547     case Intrinsic::x86_avx_vtestc_pd:
11548     case Intrinsic::x86_avx_vtestc_ps_256:
11549     case Intrinsic::x86_avx_vtestc_pd_256:
11550       IsTestPacked = true; // Fallthrough
11551     case Intrinsic::x86_sse41_ptestc:
11552     case Intrinsic::x86_avx_ptestc_256:
11553       // CF = 1
11554       X86CC = X86::COND_B;
11555       break;
11556     case Intrinsic::x86_avx_vtestnzc_ps:
11557     case Intrinsic::x86_avx_vtestnzc_pd:
11558     case Intrinsic::x86_avx_vtestnzc_ps_256:
11559     case Intrinsic::x86_avx_vtestnzc_pd_256:
11560       IsTestPacked = true; // Fallthrough
11561     case Intrinsic::x86_sse41_ptestnzc:
11562     case Intrinsic::x86_avx_ptestnzc_256:
11563       // ZF and CF = 0
11564       X86CC = X86::COND_A;
11565       break;
11566     }
11567
11568     SDValue LHS = Op.getOperand(1);
11569     SDValue RHS = Op.getOperand(2);
11570     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11571     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11572     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11573     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11574     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11575   }
11576   case Intrinsic::x86_avx512_kortestz_w:
11577   case Intrinsic::x86_avx512_kortestc_w: {
11578     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11579     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11580     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11581     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11582     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11583     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11584     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11585   }
11586
11587   // SSE/AVX shift intrinsics
11588   case Intrinsic::x86_sse2_psll_w:
11589   case Intrinsic::x86_sse2_psll_d:
11590   case Intrinsic::x86_sse2_psll_q:
11591   case Intrinsic::x86_avx2_psll_w:
11592   case Intrinsic::x86_avx2_psll_d:
11593   case Intrinsic::x86_avx2_psll_q:
11594   case Intrinsic::x86_sse2_psrl_w:
11595   case Intrinsic::x86_sse2_psrl_d:
11596   case Intrinsic::x86_sse2_psrl_q:
11597   case Intrinsic::x86_avx2_psrl_w:
11598   case Intrinsic::x86_avx2_psrl_d:
11599   case Intrinsic::x86_avx2_psrl_q:
11600   case Intrinsic::x86_sse2_psra_w:
11601   case Intrinsic::x86_sse2_psra_d:
11602   case Intrinsic::x86_avx2_psra_w:
11603   case Intrinsic::x86_avx2_psra_d: {
11604     unsigned Opcode;
11605     switch (IntNo) {
11606     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11607     case Intrinsic::x86_sse2_psll_w:
11608     case Intrinsic::x86_sse2_psll_d:
11609     case Intrinsic::x86_sse2_psll_q:
11610     case Intrinsic::x86_avx2_psll_w:
11611     case Intrinsic::x86_avx2_psll_d:
11612     case Intrinsic::x86_avx2_psll_q:
11613       Opcode = X86ISD::VSHL;
11614       break;
11615     case Intrinsic::x86_sse2_psrl_w:
11616     case Intrinsic::x86_sse2_psrl_d:
11617     case Intrinsic::x86_sse2_psrl_q:
11618     case Intrinsic::x86_avx2_psrl_w:
11619     case Intrinsic::x86_avx2_psrl_d:
11620     case Intrinsic::x86_avx2_psrl_q:
11621       Opcode = X86ISD::VSRL;
11622       break;
11623     case Intrinsic::x86_sse2_psra_w:
11624     case Intrinsic::x86_sse2_psra_d:
11625     case Intrinsic::x86_avx2_psra_w:
11626     case Intrinsic::x86_avx2_psra_d:
11627       Opcode = X86ISD::VSRA;
11628       break;
11629     }
11630     return DAG.getNode(Opcode, dl, Op.getValueType(),
11631                        Op.getOperand(1), Op.getOperand(2));
11632   }
11633
11634   // SSE/AVX immediate shift intrinsics
11635   case Intrinsic::x86_sse2_pslli_w:
11636   case Intrinsic::x86_sse2_pslli_d:
11637   case Intrinsic::x86_sse2_pslli_q:
11638   case Intrinsic::x86_avx2_pslli_w:
11639   case Intrinsic::x86_avx2_pslli_d:
11640   case Intrinsic::x86_avx2_pslli_q:
11641   case Intrinsic::x86_sse2_psrli_w:
11642   case Intrinsic::x86_sse2_psrli_d:
11643   case Intrinsic::x86_sse2_psrli_q:
11644   case Intrinsic::x86_avx2_psrli_w:
11645   case Intrinsic::x86_avx2_psrli_d:
11646   case Intrinsic::x86_avx2_psrli_q:
11647   case Intrinsic::x86_sse2_psrai_w:
11648   case Intrinsic::x86_sse2_psrai_d:
11649   case Intrinsic::x86_avx2_psrai_w:
11650   case Intrinsic::x86_avx2_psrai_d: {
11651     unsigned Opcode;
11652     switch (IntNo) {
11653     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11654     case Intrinsic::x86_sse2_pslli_w:
11655     case Intrinsic::x86_sse2_pslli_d:
11656     case Intrinsic::x86_sse2_pslli_q:
11657     case Intrinsic::x86_avx2_pslli_w:
11658     case Intrinsic::x86_avx2_pslli_d:
11659     case Intrinsic::x86_avx2_pslli_q:
11660       Opcode = X86ISD::VSHLI;
11661       break;
11662     case Intrinsic::x86_sse2_psrli_w:
11663     case Intrinsic::x86_sse2_psrli_d:
11664     case Intrinsic::x86_sse2_psrli_q:
11665     case Intrinsic::x86_avx2_psrli_w:
11666     case Intrinsic::x86_avx2_psrli_d:
11667     case Intrinsic::x86_avx2_psrli_q:
11668       Opcode = X86ISD::VSRLI;
11669       break;
11670     case Intrinsic::x86_sse2_psrai_w:
11671     case Intrinsic::x86_sse2_psrai_d:
11672     case Intrinsic::x86_avx2_psrai_w:
11673     case Intrinsic::x86_avx2_psrai_d:
11674       Opcode = X86ISD::VSRAI;
11675       break;
11676     }
11677     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11678                                Op.getOperand(1), Op.getOperand(2), DAG);
11679   }
11680
11681   case Intrinsic::x86_sse42_pcmpistria128:
11682   case Intrinsic::x86_sse42_pcmpestria128:
11683   case Intrinsic::x86_sse42_pcmpistric128:
11684   case Intrinsic::x86_sse42_pcmpestric128:
11685   case Intrinsic::x86_sse42_pcmpistrio128:
11686   case Intrinsic::x86_sse42_pcmpestrio128:
11687   case Intrinsic::x86_sse42_pcmpistris128:
11688   case Intrinsic::x86_sse42_pcmpestris128:
11689   case Intrinsic::x86_sse42_pcmpistriz128:
11690   case Intrinsic::x86_sse42_pcmpestriz128: {
11691     unsigned Opcode;
11692     unsigned X86CC;
11693     switch (IntNo) {
11694     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11695     case Intrinsic::x86_sse42_pcmpistria128:
11696       Opcode = X86ISD::PCMPISTRI;
11697       X86CC = X86::COND_A;
11698       break;
11699     case Intrinsic::x86_sse42_pcmpestria128:
11700       Opcode = X86ISD::PCMPESTRI;
11701       X86CC = X86::COND_A;
11702       break;
11703     case Intrinsic::x86_sse42_pcmpistric128:
11704       Opcode = X86ISD::PCMPISTRI;
11705       X86CC = X86::COND_B;
11706       break;
11707     case Intrinsic::x86_sse42_pcmpestric128:
11708       Opcode = X86ISD::PCMPESTRI;
11709       X86CC = X86::COND_B;
11710       break;
11711     case Intrinsic::x86_sse42_pcmpistrio128:
11712       Opcode = X86ISD::PCMPISTRI;
11713       X86CC = X86::COND_O;
11714       break;
11715     case Intrinsic::x86_sse42_pcmpestrio128:
11716       Opcode = X86ISD::PCMPESTRI;
11717       X86CC = X86::COND_O;
11718       break;
11719     case Intrinsic::x86_sse42_pcmpistris128:
11720       Opcode = X86ISD::PCMPISTRI;
11721       X86CC = X86::COND_S;
11722       break;
11723     case Intrinsic::x86_sse42_pcmpestris128:
11724       Opcode = X86ISD::PCMPESTRI;
11725       X86CC = X86::COND_S;
11726       break;
11727     case Intrinsic::x86_sse42_pcmpistriz128:
11728       Opcode = X86ISD::PCMPISTRI;
11729       X86CC = X86::COND_E;
11730       break;
11731     case Intrinsic::x86_sse42_pcmpestriz128:
11732       Opcode = X86ISD::PCMPESTRI;
11733       X86CC = X86::COND_E;
11734       break;
11735     }
11736     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11737     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11738     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11739     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11740                                 DAG.getConstant(X86CC, MVT::i8),
11741                                 SDValue(PCMP.getNode(), 1));
11742     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11743   }
11744
11745   case Intrinsic::x86_sse42_pcmpistri128:
11746   case Intrinsic::x86_sse42_pcmpestri128: {
11747     unsigned Opcode;
11748     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11749       Opcode = X86ISD::PCMPISTRI;
11750     else
11751       Opcode = X86ISD::PCMPESTRI;
11752
11753     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11754     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11755     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11756   }
11757   case Intrinsic::x86_fma_vfmadd_ps:
11758   case Intrinsic::x86_fma_vfmadd_pd:
11759   case Intrinsic::x86_fma_vfmsub_ps:
11760   case Intrinsic::x86_fma_vfmsub_pd:
11761   case Intrinsic::x86_fma_vfnmadd_ps:
11762   case Intrinsic::x86_fma_vfnmadd_pd:
11763   case Intrinsic::x86_fma_vfnmsub_ps:
11764   case Intrinsic::x86_fma_vfnmsub_pd:
11765   case Intrinsic::x86_fma_vfmaddsub_ps:
11766   case Intrinsic::x86_fma_vfmaddsub_pd:
11767   case Intrinsic::x86_fma_vfmsubadd_ps:
11768   case Intrinsic::x86_fma_vfmsubadd_pd:
11769   case Intrinsic::x86_fma_vfmadd_ps_256:
11770   case Intrinsic::x86_fma_vfmadd_pd_256:
11771   case Intrinsic::x86_fma_vfmsub_ps_256:
11772   case Intrinsic::x86_fma_vfmsub_pd_256:
11773   case Intrinsic::x86_fma_vfnmadd_ps_256:
11774   case Intrinsic::x86_fma_vfnmadd_pd_256:
11775   case Intrinsic::x86_fma_vfnmsub_ps_256:
11776   case Intrinsic::x86_fma_vfnmsub_pd_256:
11777   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11778   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11779   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11780   case Intrinsic::x86_fma_vfmsubadd_pd_256:
11781   case Intrinsic::x86_fma_vfmadd_ps_512:
11782   case Intrinsic::x86_fma_vfmadd_pd_512:
11783   case Intrinsic::x86_fma_vfmsub_ps_512:
11784   case Intrinsic::x86_fma_vfmsub_pd_512:
11785   case Intrinsic::x86_fma_vfnmadd_ps_512:
11786   case Intrinsic::x86_fma_vfnmadd_pd_512:
11787   case Intrinsic::x86_fma_vfnmsub_ps_512:
11788   case Intrinsic::x86_fma_vfnmsub_pd_512:
11789   case Intrinsic::x86_fma_vfmaddsub_ps_512:
11790   case Intrinsic::x86_fma_vfmaddsub_pd_512:
11791   case Intrinsic::x86_fma_vfmsubadd_ps_512:
11792   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11793     unsigned Opc;
11794     switch (IntNo) {
11795     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11796     case Intrinsic::x86_fma_vfmadd_ps:
11797     case Intrinsic::x86_fma_vfmadd_pd:
11798     case Intrinsic::x86_fma_vfmadd_ps_256:
11799     case Intrinsic::x86_fma_vfmadd_pd_256:
11800     case Intrinsic::x86_fma_vfmadd_ps_512:
11801     case Intrinsic::x86_fma_vfmadd_pd_512:
11802       Opc = X86ISD::FMADD;
11803       break;
11804     case Intrinsic::x86_fma_vfmsub_ps:
11805     case Intrinsic::x86_fma_vfmsub_pd:
11806     case Intrinsic::x86_fma_vfmsub_ps_256:
11807     case Intrinsic::x86_fma_vfmsub_pd_256:
11808     case Intrinsic::x86_fma_vfmsub_ps_512:
11809     case Intrinsic::x86_fma_vfmsub_pd_512:
11810       Opc = X86ISD::FMSUB;
11811       break;
11812     case Intrinsic::x86_fma_vfnmadd_ps:
11813     case Intrinsic::x86_fma_vfnmadd_pd:
11814     case Intrinsic::x86_fma_vfnmadd_ps_256:
11815     case Intrinsic::x86_fma_vfnmadd_pd_256:
11816     case Intrinsic::x86_fma_vfnmadd_ps_512:
11817     case Intrinsic::x86_fma_vfnmadd_pd_512:
11818       Opc = X86ISD::FNMADD;
11819       break;
11820     case Intrinsic::x86_fma_vfnmsub_ps:
11821     case Intrinsic::x86_fma_vfnmsub_pd:
11822     case Intrinsic::x86_fma_vfnmsub_ps_256:
11823     case Intrinsic::x86_fma_vfnmsub_pd_256:
11824     case Intrinsic::x86_fma_vfnmsub_ps_512:
11825     case Intrinsic::x86_fma_vfnmsub_pd_512:
11826       Opc = X86ISD::FNMSUB;
11827       break;
11828     case Intrinsic::x86_fma_vfmaddsub_ps:
11829     case Intrinsic::x86_fma_vfmaddsub_pd:
11830     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11831     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11832     case Intrinsic::x86_fma_vfmaddsub_ps_512:
11833     case Intrinsic::x86_fma_vfmaddsub_pd_512:
11834       Opc = X86ISD::FMADDSUB;
11835       break;
11836     case Intrinsic::x86_fma_vfmsubadd_ps:
11837     case Intrinsic::x86_fma_vfmsubadd_pd:
11838     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11839     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11840     case Intrinsic::x86_fma_vfmsubadd_ps_512:
11841     case Intrinsic::x86_fma_vfmsubadd_pd_512:
11842       Opc = X86ISD::FMSUBADD;
11843       break;
11844     }
11845
11846     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11847                        Op.getOperand(2), Op.getOperand(3));
11848   }
11849   }
11850 }
11851
11852 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11853                              SDValue Base, SDValue Index,
11854                              SDValue ScaleOp, SDValue Chain,
11855                              const X86Subtarget * Subtarget) {
11856   SDLoc dl(Op);
11857   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11858   assert(C && "Invalid scale type");
11859   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11860   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11861   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11862                                 Index.getValueType().getVectorNumElements());
11863   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11864   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11865   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11866   SDValue Segment = DAG.getRegister(0, MVT::i32);
11867   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11868   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11869   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11870   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11871 }
11872
11873 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11874                               SDValue Src, SDValue Mask, SDValue Base,
11875                               SDValue Index, SDValue ScaleOp, SDValue Chain,
11876                               const X86Subtarget * Subtarget) {
11877   SDLoc dl(Op);
11878   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11879   assert(C && "Invalid scale type");
11880   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11881   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11882                                 Index.getValueType().getVectorNumElements());
11883   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11884   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11885   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11886   SDValue Segment = DAG.getRegister(0, MVT::i32);
11887   if (Src.getOpcode() == ISD::UNDEF)
11888     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11889   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11890   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11891   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11892   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11893 }
11894
11895 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11896                               SDValue Src, SDValue Base, SDValue Index,
11897                               SDValue ScaleOp, SDValue Chain) {
11898   SDLoc dl(Op);
11899   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11900   assert(C && "Invalid scale type");
11901   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11902   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11903   SDValue Segment = DAG.getRegister(0, MVT::i32);
11904   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11905                                 Index.getValueType().getVectorNumElements());
11906   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11907   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11908   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11909   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11910   return SDValue(Res, 1);
11911 }
11912
11913 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11914                                SDValue Src, SDValue Mask, SDValue Base,
11915                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
11916   SDLoc dl(Op);
11917   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11918   assert(C && "Invalid scale type");
11919   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11920   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11921   SDValue Segment = DAG.getRegister(0, MVT::i32);
11922   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11923                                 Index.getValueType().getVectorNumElements());
11924   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11925   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11926   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11927   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11928   return SDValue(Res, 1);
11929 }
11930
11931 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
11932                                       SelectionDAG &DAG) {
11933   SDLoc dl(Op);
11934   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11935   switch (IntNo) {
11936   default: return SDValue();    // Don't custom lower most intrinsics.
11937
11938   // RDRAND/RDSEED intrinsics.
11939   case Intrinsic::x86_rdrand_16:
11940   case Intrinsic::x86_rdrand_32:
11941   case Intrinsic::x86_rdrand_64:
11942   case Intrinsic::x86_rdseed_16:
11943   case Intrinsic::x86_rdseed_32:
11944   case Intrinsic::x86_rdseed_64: {
11945     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11946                        IntNo == Intrinsic::x86_rdseed_32 ||
11947                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11948                                                             X86ISD::RDRAND;
11949     // Emit the node with the right value type.
11950     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11951     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11952
11953     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11954     // Otherwise return the value from Rand, which is always 0, casted to i32.
11955     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11956                       DAG.getConstant(1, Op->getValueType(1)),
11957                       DAG.getConstant(X86::COND_B, MVT::i32),
11958                       SDValue(Result.getNode(), 1) };
11959     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11960                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11961                                   Ops, array_lengthof(Ops));
11962
11963     // Return { result, isValid, chain }.
11964     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11965                        SDValue(Result.getNode(), 2));
11966   }
11967   //int_gather(index, base, scale);
11968   case Intrinsic::x86_avx512_gather_qpd_512:
11969   case Intrinsic::x86_avx512_gather_qps_512:
11970   case Intrinsic::x86_avx512_gather_dpd_512:
11971   case Intrinsic::x86_avx512_gather_qpi_512:
11972   case Intrinsic::x86_avx512_gather_qpq_512:
11973   case Intrinsic::x86_avx512_gather_dpq_512:
11974   case Intrinsic::x86_avx512_gather_dps_512:
11975   case Intrinsic::x86_avx512_gather_dpi_512: {
11976     unsigned Opc;
11977     switch (IntNo) {
11978       default: llvm_unreachable("Unexpected intrinsic!");
11979       case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
11980       case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
11981       case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
11982       case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
11983       case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
11984       case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
11985       case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
11986       case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
11987     }
11988     SDValue Chain = Op.getOperand(0);
11989     SDValue Index = Op.getOperand(2);
11990     SDValue Base  = Op.getOperand(3);
11991     SDValue Scale = Op.getOperand(4);
11992     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
11993   }
11994   //int_gather_mask(v1, mask, index, base, scale);
11995   case Intrinsic::x86_avx512_gather_qps_mask_512:
11996   case Intrinsic::x86_avx512_gather_qpd_mask_512:
11997   case Intrinsic::x86_avx512_gather_dpd_mask_512:
11998   case Intrinsic::x86_avx512_gather_dps_mask_512:
11999   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12000   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12001   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12002   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12003     unsigned Opc;
12004     switch (IntNo) {
12005       default: llvm_unreachable("Unexpected intrinsic!");
12006       case Intrinsic::x86_avx512_gather_qps_mask_512:
12007         Opc = X86::VGATHERQPSZrm; break;
12008       case Intrinsic::x86_avx512_gather_qpd_mask_512:
12009         Opc = X86::VGATHERQPDZrm; break;
12010       case Intrinsic::x86_avx512_gather_dpd_mask_512:
12011         Opc = X86::VGATHERDPDZrm; break;
12012       case Intrinsic::x86_avx512_gather_dps_mask_512:
12013         Opc = X86::VGATHERDPSZrm; break;
12014       case Intrinsic::x86_avx512_gather_qpi_mask_512:
12015         Opc = X86::VPGATHERQDZrm; break;
12016       case Intrinsic::x86_avx512_gather_qpq_mask_512:
12017         Opc = X86::VPGATHERQQZrm; break;
12018       case Intrinsic::x86_avx512_gather_dpi_mask_512:
12019         Opc = X86::VPGATHERDDZrm; break;
12020       case Intrinsic::x86_avx512_gather_dpq_mask_512:
12021         Opc = X86::VPGATHERDQZrm; break;
12022     }
12023     SDValue Chain = Op.getOperand(0);
12024     SDValue Src   = Op.getOperand(2);
12025     SDValue Mask  = Op.getOperand(3);
12026     SDValue Index = Op.getOperand(4);
12027     SDValue Base  = Op.getOperand(5);
12028     SDValue Scale = Op.getOperand(6);
12029     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12030                           Subtarget);
12031   }
12032   //int_scatter(base, index, v1, scale);
12033   case Intrinsic::x86_avx512_scatter_qpd_512:
12034   case Intrinsic::x86_avx512_scatter_qps_512:
12035   case Intrinsic::x86_avx512_scatter_dpd_512:
12036   case Intrinsic::x86_avx512_scatter_qpi_512:
12037   case Intrinsic::x86_avx512_scatter_qpq_512:
12038   case Intrinsic::x86_avx512_scatter_dpq_512:
12039   case Intrinsic::x86_avx512_scatter_dps_512:
12040   case Intrinsic::x86_avx512_scatter_dpi_512: {
12041     unsigned Opc;
12042     switch (IntNo) {
12043       default: llvm_unreachable("Unexpected intrinsic!");
12044       case Intrinsic::x86_avx512_scatter_qpd_512:
12045         Opc = X86::VSCATTERQPDZmr; break;
12046       case Intrinsic::x86_avx512_scatter_qps_512:
12047         Opc = X86::VSCATTERQPSZmr; break;
12048       case Intrinsic::x86_avx512_scatter_dpd_512:
12049         Opc = X86::VSCATTERDPDZmr; break;
12050       case Intrinsic::x86_avx512_scatter_dps_512:
12051         Opc = X86::VSCATTERDPSZmr; break;
12052       case Intrinsic::x86_avx512_scatter_qpi_512:
12053         Opc = X86::VPSCATTERQDZmr; break;
12054       case Intrinsic::x86_avx512_scatter_qpq_512:
12055         Opc = X86::VPSCATTERQQZmr; break;
12056       case Intrinsic::x86_avx512_scatter_dpq_512:
12057         Opc = X86::VPSCATTERDQZmr; break;
12058       case Intrinsic::x86_avx512_scatter_dpi_512:
12059         Opc = X86::VPSCATTERDDZmr; break;
12060     }
12061     SDValue Chain = Op.getOperand(0);
12062     SDValue Base  = Op.getOperand(2);
12063     SDValue Index = Op.getOperand(3);
12064     SDValue Src   = Op.getOperand(4);
12065     SDValue Scale = Op.getOperand(5);
12066     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12067   }
12068   //int_scatter_mask(base, mask, index, v1, scale);
12069   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12070   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12071   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12072   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12073   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12074   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12075   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12076   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12077     unsigned Opc;
12078     switch (IntNo) {
12079       default: llvm_unreachable("Unexpected intrinsic!");
12080       case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12081         Opc = X86::VSCATTERQPDZmr; break;
12082       case Intrinsic::x86_avx512_scatter_qps_mask_512:
12083         Opc = X86::VSCATTERQPSZmr; break;
12084       case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12085         Opc = X86::VSCATTERDPDZmr; break;
12086       case Intrinsic::x86_avx512_scatter_dps_mask_512:
12087         Opc = X86::VSCATTERDPSZmr; break;
12088       case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12089         Opc = X86::VPSCATTERQDZmr; break;
12090       case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12091         Opc = X86::VPSCATTERQQZmr; break;
12092       case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12093         Opc = X86::VPSCATTERDQZmr; break;
12094       case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12095         Opc = X86::VPSCATTERDDZmr; break;
12096     }
12097     SDValue Chain = Op.getOperand(0);
12098     SDValue Base  = Op.getOperand(2);
12099     SDValue Mask  = Op.getOperand(3);
12100     SDValue Index = Op.getOperand(4);
12101     SDValue Src   = Op.getOperand(5);
12102     SDValue Scale = Op.getOperand(6);
12103     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12104   }
12105   // XTEST intrinsics.
12106   case Intrinsic::x86_xtest: {
12107     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12108     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12109     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12110                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12111                                 InTrans);
12112     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12113     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12114                        Ret, SDValue(InTrans.getNode(), 1));
12115   }
12116   }
12117 }
12118
12119 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12120                                            SelectionDAG &DAG) const {
12121   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12122   MFI->setReturnAddressIsTaken(true);
12123
12124   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12125   SDLoc dl(Op);
12126   EVT PtrVT = getPointerTy();
12127
12128   if (Depth > 0) {
12129     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12130     const X86RegisterInfo *RegInfo =
12131       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12132     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12133     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12134                        DAG.getNode(ISD::ADD, dl, PtrVT,
12135                                    FrameAddr, Offset),
12136                        MachinePointerInfo(), false, false, false, 0);
12137   }
12138
12139   // Just load the return address.
12140   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12141   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12142                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12143 }
12144
12145 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12146   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12147   MFI->setFrameAddressIsTaken(true);
12148
12149   EVT VT = Op.getValueType();
12150   SDLoc dl(Op);  // FIXME probably not meaningful
12151   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12152   const X86RegisterInfo *RegInfo =
12153     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12154   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12155   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12156           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12157          "Invalid Frame Register!");
12158   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12159   while (Depth--)
12160     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12161                             MachinePointerInfo(),
12162                             false, false, false, 0);
12163   return FrameAddr;
12164 }
12165
12166 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12167                                                      SelectionDAG &DAG) const {
12168   const X86RegisterInfo *RegInfo =
12169     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12170   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12171 }
12172
12173 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12174   SDValue Chain     = Op.getOperand(0);
12175   SDValue Offset    = Op.getOperand(1);
12176   SDValue Handler   = Op.getOperand(2);
12177   SDLoc dl      (Op);
12178
12179   EVT PtrVT = getPointerTy();
12180   const X86RegisterInfo *RegInfo =
12181     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12182   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12183   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12184           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12185          "Invalid Frame Register!");
12186   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12187   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12188
12189   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12190                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12191   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12192   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12193                        false, false, 0);
12194   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12195
12196   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12197                      DAG.getRegister(StoreAddrReg, PtrVT));
12198 }
12199
12200 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12201                                                SelectionDAG &DAG) const {
12202   SDLoc DL(Op);
12203   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12204                      DAG.getVTList(MVT::i32, MVT::Other),
12205                      Op.getOperand(0), Op.getOperand(1));
12206 }
12207
12208 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12209                                                 SelectionDAG &DAG) const {
12210   SDLoc DL(Op);
12211   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12212                      Op.getOperand(0), Op.getOperand(1));
12213 }
12214
12215 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12216   return Op.getOperand(0);
12217 }
12218
12219 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12220                                                 SelectionDAG &DAG) const {
12221   SDValue Root = Op.getOperand(0);
12222   SDValue Trmp = Op.getOperand(1); // trampoline
12223   SDValue FPtr = Op.getOperand(2); // nested function
12224   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12225   SDLoc dl (Op);
12226
12227   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12228   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12229
12230   if (Subtarget->is64Bit()) {
12231     SDValue OutChains[6];
12232
12233     // Large code-model.
12234     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12235     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12236
12237     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12238     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12239
12240     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12241
12242     // Load the pointer to the nested function into R11.
12243     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12244     SDValue Addr = Trmp;
12245     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12246                                 Addr, MachinePointerInfo(TrmpAddr),
12247                                 false, false, 0);
12248
12249     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12250                        DAG.getConstant(2, MVT::i64));
12251     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12252                                 MachinePointerInfo(TrmpAddr, 2),
12253                                 false, false, 2);
12254
12255     // Load the 'nest' parameter value into R10.
12256     // R10 is specified in X86CallingConv.td
12257     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12258     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12259                        DAG.getConstant(10, MVT::i64));
12260     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12261                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12262                                 false, false, 0);
12263
12264     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12265                        DAG.getConstant(12, MVT::i64));
12266     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12267                                 MachinePointerInfo(TrmpAddr, 12),
12268                                 false, false, 2);
12269
12270     // Jump to the nested function.
12271     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12272     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12273                        DAG.getConstant(20, MVT::i64));
12274     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12275                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12276                                 false, false, 0);
12277
12278     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12279     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12280                        DAG.getConstant(22, MVT::i64));
12281     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12282                                 MachinePointerInfo(TrmpAddr, 22),
12283                                 false, false, 0);
12284
12285     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12286   } else {
12287     const Function *Func =
12288       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12289     CallingConv::ID CC = Func->getCallingConv();
12290     unsigned NestReg;
12291
12292     switch (CC) {
12293     default:
12294       llvm_unreachable("Unsupported calling convention");
12295     case CallingConv::C:
12296     case CallingConv::X86_StdCall: {
12297       // Pass 'nest' parameter in ECX.
12298       // Must be kept in sync with X86CallingConv.td
12299       NestReg = X86::ECX;
12300
12301       // Check that ECX wasn't needed by an 'inreg' parameter.
12302       FunctionType *FTy = Func->getFunctionType();
12303       const AttributeSet &Attrs = Func->getAttributes();
12304
12305       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12306         unsigned InRegCount = 0;
12307         unsigned Idx = 1;
12308
12309         for (FunctionType::param_iterator I = FTy->param_begin(),
12310              E = FTy->param_end(); I != E; ++I, ++Idx)
12311           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12312             // FIXME: should only count parameters that are lowered to integers.
12313             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12314
12315         if (InRegCount > 2) {
12316           report_fatal_error("Nest register in use - reduce number of inreg"
12317                              " parameters!");
12318         }
12319       }
12320       break;
12321     }
12322     case CallingConv::X86_FastCall:
12323     case CallingConv::X86_ThisCall:
12324     case CallingConv::Fast:
12325       // Pass 'nest' parameter in EAX.
12326       // Must be kept in sync with X86CallingConv.td
12327       NestReg = X86::EAX;
12328       break;
12329     }
12330
12331     SDValue OutChains[4];
12332     SDValue Addr, Disp;
12333
12334     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12335                        DAG.getConstant(10, MVT::i32));
12336     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12337
12338     // This is storing the opcode for MOV32ri.
12339     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12340     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12341     OutChains[0] = DAG.getStore(Root, dl,
12342                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12343                                 Trmp, MachinePointerInfo(TrmpAddr),
12344                                 false, false, 0);
12345
12346     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12347                        DAG.getConstant(1, MVT::i32));
12348     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12349                                 MachinePointerInfo(TrmpAddr, 1),
12350                                 false, false, 1);
12351
12352     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12353     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12354                        DAG.getConstant(5, MVT::i32));
12355     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12356                                 MachinePointerInfo(TrmpAddr, 5),
12357                                 false, false, 1);
12358
12359     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12360                        DAG.getConstant(6, MVT::i32));
12361     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12362                                 MachinePointerInfo(TrmpAddr, 6),
12363                                 false, false, 1);
12364
12365     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12366   }
12367 }
12368
12369 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12370                                             SelectionDAG &DAG) const {
12371   /*
12372    The rounding mode is in bits 11:10 of FPSR, and has the following
12373    settings:
12374      00 Round to nearest
12375      01 Round to -inf
12376      10 Round to +inf
12377      11 Round to 0
12378
12379   FLT_ROUNDS, on the other hand, expects the following:
12380     -1 Undefined
12381      0 Round to 0
12382      1 Round to nearest
12383      2 Round to +inf
12384      3 Round to -inf
12385
12386   To perform the conversion, we do:
12387     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12388   */
12389
12390   MachineFunction &MF = DAG.getMachineFunction();
12391   const TargetMachine &TM = MF.getTarget();
12392   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12393   unsigned StackAlignment = TFI.getStackAlignment();
12394   EVT VT = Op.getValueType();
12395   SDLoc DL(Op);
12396
12397   // Save FP Control Word to stack slot
12398   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12399   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12400
12401   MachineMemOperand *MMO =
12402    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12403                            MachineMemOperand::MOStore, 2, 2);
12404
12405   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12406   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12407                                           DAG.getVTList(MVT::Other),
12408                                           Ops, array_lengthof(Ops), MVT::i16,
12409                                           MMO);
12410
12411   // Load FP Control Word from stack slot
12412   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12413                             MachinePointerInfo(), false, false, false, 0);
12414
12415   // Transform as necessary
12416   SDValue CWD1 =
12417     DAG.getNode(ISD::SRL, DL, MVT::i16,
12418                 DAG.getNode(ISD::AND, DL, MVT::i16,
12419                             CWD, DAG.getConstant(0x800, MVT::i16)),
12420                 DAG.getConstant(11, MVT::i8));
12421   SDValue CWD2 =
12422     DAG.getNode(ISD::SRL, DL, MVT::i16,
12423                 DAG.getNode(ISD::AND, DL, MVT::i16,
12424                             CWD, DAG.getConstant(0x400, MVT::i16)),
12425                 DAG.getConstant(9, MVT::i8));
12426
12427   SDValue RetVal =
12428     DAG.getNode(ISD::AND, DL, MVT::i16,
12429                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12430                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12431                             DAG.getConstant(1, MVT::i16)),
12432                 DAG.getConstant(3, MVT::i16));
12433
12434   return DAG.getNode((VT.getSizeInBits() < 16 ?
12435                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12436 }
12437
12438 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12439   EVT VT = Op.getValueType();
12440   EVT OpVT = VT;
12441   unsigned NumBits = VT.getSizeInBits();
12442   SDLoc dl(Op);
12443
12444   Op = Op.getOperand(0);
12445   if (VT == MVT::i8) {
12446     // Zero extend to i32 since there is not an i8 bsr.
12447     OpVT = MVT::i32;
12448     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12449   }
12450
12451   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12452   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12453   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12454
12455   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12456   SDValue Ops[] = {
12457     Op,
12458     DAG.getConstant(NumBits+NumBits-1, OpVT),
12459     DAG.getConstant(X86::COND_E, MVT::i8),
12460     Op.getValue(1)
12461   };
12462   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12463
12464   // Finally xor with NumBits-1.
12465   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12466
12467   if (VT == MVT::i8)
12468     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12469   return Op;
12470 }
12471
12472 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12473   EVT VT = Op.getValueType();
12474   EVT OpVT = VT;
12475   unsigned NumBits = VT.getSizeInBits();
12476   SDLoc dl(Op);
12477
12478   Op = Op.getOperand(0);
12479   if (VT == MVT::i8) {
12480     // Zero extend to i32 since there is not an i8 bsr.
12481     OpVT = MVT::i32;
12482     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12483   }
12484
12485   // Issue a bsr (scan bits in reverse).
12486   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12487   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12488
12489   // And xor with NumBits-1.
12490   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12491
12492   if (VT == MVT::i8)
12493     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12494   return Op;
12495 }
12496
12497 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12498   EVT VT = Op.getValueType();
12499   unsigned NumBits = VT.getSizeInBits();
12500   SDLoc dl(Op);
12501   Op = Op.getOperand(0);
12502
12503   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12504   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12505   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12506
12507   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12508   SDValue Ops[] = {
12509     Op,
12510     DAG.getConstant(NumBits, VT),
12511     DAG.getConstant(X86::COND_E, MVT::i8),
12512     Op.getValue(1)
12513   };
12514   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12515 }
12516
12517 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12518 // ones, and then concatenate the result back.
12519 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12520   EVT VT = Op.getValueType();
12521
12522   assert(VT.is256BitVector() && VT.isInteger() &&
12523          "Unsupported value type for operation");
12524
12525   unsigned NumElems = VT.getVectorNumElements();
12526   SDLoc dl(Op);
12527
12528   // Extract the LHS vectors
12529   SDValue LHS = Op.getOperand(0);
12530   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12531   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12532
12533   // Extract the RHS vectors
12534   SDValue RHS = Op.getOperand(1);
12535   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12536   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12537
12538   MVT EltVT = VT.getVectorElementType().getSimpleVT();
12539   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12540
12541   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12542                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12543                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12544 }
12545
12546 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12547   assert(Op.getValueType().is256BitVector() &&
12548          Op.getValueType().isInteger() &&
12549          "Only handle AVX 256-bit vector integer operation");
12550   return Lower256IntArith(Op, DAG);
12551 }
12552
12553 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12554   assert(Op.getValueType().is256BitVector() &&
12555          Op.getValueType().isInteger() &&
12556          "Only handle AVX 256-bit vector integer operation");
12557   return Lower256IntArith(Op, DAG);
12558 }
12559
12560 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12561                         SelectionDAG &DAG) {
12562   SDLoc dl(Op);
12563   EVT VT = Op.getValueType();
12564
12565   // Decompose 256-bit ops into smaller 128-bit ops.
12566   if (VT.is256BitVector() && !Subtarget->hasInt256())
12567     return Lower256IntArith(Op, DAG);
12568
12569   SDValue A = Op.getOperand(0);
12570   SDValue B = Op.getOperand(1);
12571
12572   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12573   if (VT == MVT::v4i32) {
12574     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12575            "Should not custom lower when pmuldq is available!");
12576
12577     // Extract the odd parts.
12578     static const int UnpackMask[] = { 1, -1, 3, -1 };
12579     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12580     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12581
12582     // Multiply the even parts.
12583     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12584     // Now multiply odd parts.
12585     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12586
12587     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12588     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12589
12590     // Merge the two vectors back together with a shuffle. This expands into 2
12591     // shuffles.
12592     static const int ShufMask[] = { 0, 4, 2, 6 };
12593     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12594   }
12595
12596   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12597          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12598
12599   //  Ahi = psrlqi(a, 32);
12600   //  Bhi = psrlqi(b, 32);
12601   //
12602   //  AloBlo = pmuludq(a, b);
12603   //  AloBhi = pmuludq(a, Bhi);
12604   //  AhiBlo = pmuludq(Ahi, b);
12605
12606   //  AloBhi = psllqi(AloBhi, 32);
12607   //  AhiBlo = psllqi(AhiBlo, 32);
12608   //  return AloBlo + AloBhi + AhiBlo;
12609
12610   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12611   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12612
12613   // Bit cast to 32-bit vectors for MULUDQ
12614   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12615                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12616   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12617   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12618   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12619   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12620
12621   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12622   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12623   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12624
12625   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12626   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12627
12628   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12629   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12630 }
12631
12632 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12633   EVT VT = Op.getValueType();
12634   EVT EltTy = VT.getVectorElementType();
12635   unsigned NumElts = VT.getVectorNumElements();
12636   SDValue N0 = Op.getOperand(0);
12637   SDLoc dl(Op);
12638
12639   // Lower sdiv X, pow2-const.
12640   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12641   if (!C)
12642     return SDValue();
12643
12644   APInt SplatValue, SplatUndef;
12645   unsigned SplatBitSize;
12646   bool HasAnyUndefs;
12647   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12648                           HasAnyUndefs) ||
12649       EltTy.getSizeInBits() < SplatBitSize)
12650     return SDValue();
12651
12652   if ((SplatValue != 0) &&
12653       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12654     unsigned Lg2 = SplatValue.countTrailingZeros();
12655     // Splat the sign bit.
12656     SmallVector<SDValue, 16> Sz(NumElts,
12657                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12658                                                 EltTy));
12659     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12660                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12661                                           NumElts));
12662     // Add (N0 < 0) ? abs2 - 1 : 0;
12663     SmallVector<SDValue, 16> Amt(NumElts,
12664                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12665                                                  EltTy));
12666     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12667                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12668                                           NumElts));
12669     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12670     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12671     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12672                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12673                                           NumElts));
12674
12675     // If we're dividing by a positive value, we're done.  Otherwise, we must
12676     // negate the result.
12677     if (SplatValue.isNonNegative())
12678       return SRA;
12679
12680     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12681     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12682     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12683   }
12684   return SDValue();
12685 }
12686
12687 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12688                                          const X86Subtarget *Subtarget) {
12689   EVT VT = Op.getValueType();
12690   SDLoc dl(Op);
12691   SDValue R = Op.getOperand(0);
12692   SDValue Amt = Op.getOperand(1);
12693
12694   // Optimize shl/srl/sra with constant shift amount.
12695   if (isSplatVector(Amt.getNode())) {
12696     SDValue SclrAmt = Amt->getOperand(0);
12697     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12698       uint64_t ShiftAmt = C->getZExtValue();
12699
12700       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12701           (Subtarget->hasInt256() &&
12702            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12703           (Subtarget->hasAVX512() &&
12704            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12705         if (Op.getOpcode() == ISD::SHL)
12706           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12707                                             DAG);
12708         if (Op.getOpcode() == ISD::SRL)
12709           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12710                                             DAG);
12711         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12712           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12713                                             DAG);
12714       }
12715
12716       if (VT == MVT::v16i8) {
12717         if (Op.getOpcode() == ISD::SHL) {
12718           // Make a large shift.
12719           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12720                                                    MVT::v8i16, R, ShiftAmt,
12721                                                    DAG);
12722           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12723           // Zero out the rightmost bits.
12724           SmallVector<SDValue, 16> V(16,
12725                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12726                                                      MVT::i8));
12727           return DAG.getNode(ISD::AND, dl, VT, SHL,
12728                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12729         }
12730         if (Op.getOpcode() == ISD::SRL) {
12731           // Make a large shift.
12732           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12733                                                    MVT::v8i16, R, ShiftAmt,
12734                                                    DAG);
12735           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12736           // Zero out the leftmost bits.
12737           SmallVector<SDValue, 16> V(16,
12738                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12739                                                      MVT::i8));
12740           return DAG.getNode(ISD::AND, dl, VT, SRL,
12741                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12742         }
12743         if (Op.getOpcode() == ISD::SRA) {
12744           if (ShiftAmt == 7) {
12745             // R s>> 7  ===  R s< 0
12746             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12747             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12748           }
12749
12750           // R s>> a === ((R u>> a) ^ m) - m
12751           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12752           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12753                                                          MVT::i8));
12754           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12755           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12756           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12757           return Res;
12758         }
12759         llvm_unreachable("Unknown shift opcode.");
12760       }
12761
12762       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12763         if (Op.getOpcode() == ISD::SHL) {
12764           // Make a large shift.
12765           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12766                                                    MVT::v16i16, R, ShiftAmt,
12767                                                    DAG);
12768           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12769           // Zero out the rightmost bits.
12770           SmallVector<SDValue, 32> V(32,
12771                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12772                                                      MVT::i8));
12773           return DAG.getNode(ISD::AND, dl, VT, SHL,
12774                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12775         }
12776         if (Op.getOpcode() == ISD::SRL) {
12777           // Make a large shift.
12778           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12779                                                    MVT::v16i16, R, ShiftAmt,
12780                                                    DAG);
12781           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12782           // Zero out the leftmost bits.
12783           SmallVector<SDValue, 32> V(32,
12784                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12785                                                      MVT::i8));
12786           return DAG.getNode(ISD::AND, dl, VT, SRL,
12787                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12788         }
12789         if (Op.getOpcode() == ISD::SRA) {
12790           if (ShiftAmt == 7) {
12791             // R s>> 7  ===  R s< 0
12792             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12793             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12794           }
12795
12796           // R s>> a === ((R u>> a) ^ m) - m
12797           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12798           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12799                                                          MVT::i8));
12800           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12801           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12802           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12803           return Res;
12804         }
12805         llvm_unreachable("Unknown shift opcode.");
12806       }
12807     }
12808   }
12809
12810   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12811   if (!Subtarget->is64Bit() &&
12812       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12813       Amt.getOpcode() == ISD::BITCAST &&
12814       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12815     Amt = Amt.getOperand(0);
12816     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12817                      VT.getVectorNumElements();
12818     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12819     uint64_t ShiftAmt = 0;
12820     for (unsigned i = 0; i != Ratio; ++i) {
12821       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12822       if (C == 0)
12823         return SDValue();
12824       // 6 == Log2(64)
12825       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12826     }
12827     // Check remaining shift amounts.
12828     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12829       uint64_t ShAmt = 0;
12830       for (unsigned j = 0; j != Ratio; ++j) {
12831         ConstantSDNode *C =
12832           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12833         if (C == 0)
12834           return SDValue();
12835         // 6 == Log2(64)
12836         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12837       }
12838       if (ShAmt != ShiftAmt)
12839         return SDValue();
12840     }
12841     switch (Op.getOpcode()) {
12842     default:
12843       llvm_unreachable("Unknown shift opcode!");
12844     case ISD::SHL:
12845       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12846                                         DAG);
12847     case ISD::SRL:
12848       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12849                                         DAG);
12850     case ISD::SRA:
12851       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12852                                         DAG);
12853     }
12854   }
12855
12856   return SDValue();
12857 }
12858
12859 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12860                                         const X86Subtarget* Subtarget) {
12861   EVT VT = Op.getValueType();
12862   SDLoc dl(Op);
12863   SDValue R = Op.getOperand(0);
12864   SDValue Amt = Op.getOperand(1);
12865
12866   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12867       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12868       (Subtarget->hasInt256() &&
12869        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12870         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12871        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12872     SDValue BaseShAmt;
12873     EVT EltVT = VT.getVectorElementType();
12874
12875     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12876       unsigned NumElts = VT.getVectorNumElements();
12877       unsigned i, j;
12878       for (i = 0; i != NumElts; ++i) {
12879         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12880           continue;
12881         break;
12882       }
12883       for (j = i; j != NumElts; ++j) {
12884         SDValue Arg = Amt.getOperand(j);
12885         if (Arg.getOpcode() == ISD::UNDEF) continue;
12886         if (Arg != Amt.getOperand(i))
12887           break;
12888       }
12889       if (i != NumElts && j == NumElts)
12890         BaseShAmt = Amt.getOperand(i);
12891     } else {
12892       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12893         Amt = Amt.getOperand(0);
12894       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12895                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12896         SDValue InVec = Amt.getOperand(0);
12897         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12898           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12899           unsigned i = 0;
12900           for (; i != NumElts; ++i) {
12901             SDValue Arg = InVec.getOperand(i);
12902             if (Arg.getOpcode() == ISD::UNDEF) continue;
12903             BaseShAmt = Arg;
12904             break;
12905           }
12906         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12907            if (ConstantSDNode *C =
12908                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12909              unsigned SplatIdx =
12910                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12911              if (C->getZExtValue() == SplatIdx)
12912                BaseShAmt = InVec.getOperand(1);
12913            }
12914         }
12915         if (BaseShAmt.getNode() == 0)
12916           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12917                                   DAG.getIntPtrConstant(0));
12918       }
12919     }
12920
12921     if (BaseShAmt.getNode()) {
12922       if (EltVT.bitsGT(MVT::i32))
12923         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12924       else if (EltVT.bitsLT(MVT::i32))
12925         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12926
12927       switch (Op.getOpcode()) {
12928       default:
12929         llvm_unreachable("Unknown shift opcode!");
12930       case ISD::SHL:
12931         switch (VT.getSimpleVT().SimpleTy) {
12932         default: return SDValue();
12933         case MVT::v2i64:
12934         case MVT::v4i32:
12935         case MVT::v8i16:
12936         case MVT::v4i64:
12937         case MVT::v8i32:
12938         case MVT::v16i16:
12939         case MVT::v16i32:
12940         case MVT::v8i64:
12941           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12942         }
12943       case ISD::SRA:
12944         switch (VT.getSimpleVT().SimpleTy) {
12945         default: return SDValue();
12946         case MVT::v4i32:
12947         case MVT::v8i16:
12948         case MVT::v8i32:
12949         case MVT::v16i16:
12950         case MVT::v16i32:
12951         case MVT::v8i64:
12952           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12953         }
12954       case ISD::SRL:
12955         switch (VT.getSimpleVT().SimpleTy) {
12956         default: return SDValue();
12957         case MVT::v2i64:
12958         case MVT::v4i32:
12959         case MVT::v8i16:
12960         case MVT::v4i64:
12961         case MVT::v8i32:
12962         case MVT::v16i16:
12963         case MVT::v16i32:
12964         case MVT::v8i64:
12965           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12966         }
12967       }
12968     }
12969   }
12970
12971   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12972   if (!Subtarget->is64Bit() &&
12973       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
12974       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
12975       Amt.getOpcode() == ISD::BITCAST &&
12976       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12977     Amt = Amt.getOperand(0);
12978     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12979                      VT.getVectorNumElements();
12980     std::vector<SDValue> Vals(Ratio);
12981     for (unsigned i = 0; i != Ratio; ++i)
12982       Vals[i] = Amt.getOperand(i);
12983     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12984       for (unsigned j = 0; j != Ratio; ++j)
12985         if (Vals[j] != Amt.getOperand(i + j))
12986           return SDValue();
12987     }
12988     switch (Op.getOpcode()) {
12989     default:
12990       llvm_unreachable("Unknown shift opcode!");
12991     case ISD::SHL:
12992       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12993     case ISD::SRL:
12994       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12995     case ISD::SRA:
12996       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12997     }
12998   }
12999
13000   return SDValue();
13001 }
13002
13003 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13004                           SelectionDAG &DAG) {
13005
13006   EVT VT = Op.getValueType();
13007   SDLoc dl(Op);
13008   SDValue R = Op.getOperand(0);
13009   SDValue Amt = Op.getOperand(1);
13010   SDValue V;
13011
13012   if (!Subtarget->hasSSE2())
13013     return SDValue();
13014
13015   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13016   if (V.getNode())
13017     return V;
13018
13019   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13020   if (V.getNode())
13021       return V;
13022
13023   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13024     return Op;
13025   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13026   if (Subtarget->hasInt256()) {
13027     if (Op.getOpcode() == ISD::SRL &&
13028         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13029          VT == MVT::v4i64 || VT == MVT::v8i32))
13030       return Op;
13031     if (Op.getOpcode() == ISD::SHL &&
13032         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13033          VT == MVT::v4i64 || VT == MVT::v8i32))
13034       return Op;
13035     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13036       return Op;
13037   }
13038
13039   // Lower SHL with variable shift amount.
13040   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13041     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13042
13043     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13044     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13045     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13046     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13047   }
13048   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13049     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13050
13051     // a = a << 5;
13052     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13053     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13054
13055     // Turn 'a' into a mask suitable for VSELECT
13056     SDValue VSelM = DAG.getConstant(0x80, VT);
13057     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13058     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13059
13060     SDValue CM1 = DAG.getConstant(0x0f, VT);
13061     SDValue CM2 = DAG.getConstant(0x3f, VT);
13062
13063     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13064     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13065     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13066     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13067     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13068
13069     // a += a
13070     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13071     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13072     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13073
13074     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13075     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13076     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13077     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13078     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13079
13080     // a += a
13081     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13082     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13083     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13084
13085     // return VSELECT(r, r+r, a);
13086     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13087                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13088     return R;
13089   }
13090
13091   // Decompose 256-bit shifts into smaller 128-bit shifts.
13092   if (VT.is256BitVector()) {
13093     unsigned NumElems = VT.getVectorNumElements();
13094     MVT EltVT = VT.getVectorElementType().getSimpleVT();
13095     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13096
13097     // Extract the two vectors
13098     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13099     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13100
13101     // Recreate the shift amount vectors
13102     SDValue Amt1, Amt2;
13103     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13104       // Constant shift amount
13105       SmallVector<SDValue, 4> Amt1Csts;
13106       SmallVector<SDValue, 4> Amt2Csts;
13107       for (unsigned i = 0; i != NumElems/2; ++i)
13108         Amt1Csts.push_back(Amt->getOperand(i));
13109       for (unsigned i = NumElems/2; i != NumElems; ++i)
13110         Amt2Csts.push_back(Amt->getOperand(i));
13111
13112       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13113                                  &Amt1Csts[0], NumElems/2);
13114       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13115                                  &Amt2Csts[0], NumElems/2);
13116     } else {
13117       // Variable shift amount
13118       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13119       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13120     }
13121
13122     // Issue new vector shifts for the smaller types
13123     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13124     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13125
13126     // Concatenate the result back
13127     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13128   }
13129
13130   return SDValue();
13131 }
13132
13133 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13134   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13135   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13136   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13137   // has only one use.
13138   SDNode *N = Op.getNode();
13139   SDValue LHS = N->getOperand(0);
13140   SDValue RHS = N->getOperand(1);
13141   unsigned BaseOp = 0;
13142   unsigned Cond = 0;
13143   SDLoc DL(Op);
13144   switch (Op.getOpcode()) {
13145   default: llvm_unreachable("Unknown ovf instruction!");
13146   case ISD::SADDO:
13147     // A subtract of one will be selected as a INC. Note that INC doesn't
13148     // set CF, so we can't do this for UADDO.
13149     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13150       if (C->isOne()) {
13151         BaseOp = X86ISD::INC;
13152         Cond = X86::COND_O;
13153         break;
13154       }
13155     BaseOp = X86ISD::ADD;
13156     Cond = X86::COND_O;
13157     break;
13158   case ISD::UADDO:
13159     BaseOp = X86ISD::ADD;
13160     Cond = X86::COND_B;
13161     break;
13162   case ISD::SSUBO:
13163     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13164     // set CF, so we can't do this for USUBO.
13165     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13166       if (C->isOne()) {
13167         BaseOp = X86ISD::DEC;
13168         Cond = X86::COND_O;
13169         break;
13170       }
13171     BaseOp = X86ISD::SUB;
13172     Cond = X86::COND_O;
13173     break;
13174   case ISD::USUBO:
13175     BaseOp = X86ISD::SUB;
13176     Cond = X86::COND_B;
13177     break;
13178   case ISD::SMULO:
13179     BaseOp = X86ISD::SMUL;
13180     Cond = X86::COND_O;
13181     break;
13182   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13183     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13184                                  MVT::i32);
13185     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13186
13187     SDValue SetCC =
13188       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13189                   DAG.getConstant(X86::COND_O, MVT::i32),
13190                   SDValue(Sum.getNode(), 2));
13191
13192     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13193   }
13194   }
13195
13196   // Also sets EFLAGS.
13197   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13198   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13199
13200   SDValue SetCC =
13201     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13202                 DAG.getConstant(Cond, MVT::i32),
13203                 SDValue(Sum.getNode(), 1));
13204
13205   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13206 }
13207
13208 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13209                                                   SelectionDAG &DAG) const {
13210   SDLoc dl(Op);
13211   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13212   EVT VT = Op.getValueType();
13213
13214   if (!Subtarget->hasSSE2() || !VT.isVector())
13215     return SDValue();
13216
13217   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13218                       ExtraVT.getScalarType().getSizeInBits();
13219
13220   switch (VT.getSimpleVT().SimpleTy) {
13221     default: return SDValue();
13222     case MVT::v8i32:
13223     case MVT::v16i16:
13224       if (!Subtarget->hasFp256())
13225         return SDValue();
13226       if (!Subtarget->hasInt256()) {
13227         // needs to be split
13228         unsigned NumElems = VT.getVectorNumElements();
13229
13230         // Extract the LHS vectors
13231         SDValue LHS = Op.getOperand(0);
13232         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13233         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13234
13235         MVT EltVT = VT.getVectorElementType().getSimpleVT();
13236         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13237
13238         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13239         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13240         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13241                                    ExtraNumElems/2);
13242         SDValue Extra = DAG.getValueType(ExtraVT);
13243
13244         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13245         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13246
13247         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13248       }
13249       // fall through
13250     case MVT::v4i32:
13251     case MVT::v8i16: {
13252       SDValue Op0 = Op.getOperand(0);
13253       SDValue Op00 = Op0.getOperand(0);
13254       SDValue Tmp1;
13255       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13256       if (Op0.getOpcode() == ISD::BITCAST &&
13257           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13258         // (sext (vzext x)) -> (vsext x)
13259         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13260         if (Tmp1.getNode()) {
13261           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13262           // This folding is only valid when the in-reg type is a vector of i8,
13263           // i16, or i32.
13264           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13265               ExtraEltVT == MVT::i32) {
13266             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13267             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13268                    "This optimization is invalid without a VZEXT.");
13269             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13270           }
13271           Op0 = Tmp1;
13272         }
13273       }
13274
13275       // If the above didn't work, then just use Shift-Left + Shift-Right.
13276       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13277                                         DAG);
13278       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13279                                         DAG);
13280     }
13281   }
13282 }
13283
13284 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13285                                  SelectionDAG &DAG) {
13286   SDLoc dl(Op);
13287   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13288     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13289   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13290     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13291
13292   // The only fence that needs an instruction is a sequentially-consistent
13293   // cross-thread fence.
13294   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13295     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13296     // no-sse2). There isn't any reason to disable it if the target processor
13297     // supports it.
13298     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13299       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13300
13301     SDValue Chain = Op.getOperand(0);
13302     SDValue Zero = DAG.getConstant(0, MVT::i32);
13303     SDValue Ops[] = {
13304       DAG.getRegister(X86::ESP, MVT::i32), // Base
13305       DAG.getTargetConstant(1, MVT::i8),   // Scale
13306       DAG.getRegister(0, MVT::i32),        // Index
13307       DAG.getTargetConstant(0, MVT::i32),  // Disp
13308       DAG.getRegister(0, MVT::i32),        // Segment.
13309       Zero,
13310       Chain
13311     };
13312     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13313     return SDValue(Res, 0);
13314   }
13315
13316   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13317   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13318 }
13319
13320 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13321                              SelectionDAG &DAG) {
13322   EVT T = Op.getValueType();
13323   SDLoc DL(Op);
13324   unsigned Reg = 0;
13325   unsigned size = 0;
13326   switch(T.getSimpleVT().SimpleTy) {
13327   default: llvm_unreachable("Invalid value type!");
13328   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13329   case MVT::i16: Reg = X86::AX;  size = 2; break;
13330   case MVT::i32: Reg = X86::EAX; size = 4; break;
13331   case MVT::i64:
13332     assert(Subtarget->is64Bit() && "Node not type legal!");
13333     Reg = X86::RAX; size = 8;
13334     break;
13335   }
13336   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13337                                     Op.getOperand(2), SDValue());
13338   SDValue Ops[] = { cpIn.getValue(0),
13339                     Op.getOperand(1),
13340                     Op.getOperand(3),
13341                     DAG.getTargetConstant(size, MVT::i8),
13342                     cpIn.getValue(1) };
13343   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13344   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13345   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13346                                            Ops, array_lengthof(Ops), T, MMO);
13347   SDValue cpOut =
13348     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13349   return cpOut;
13350 }
13351
13352 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13353                                      SelectionDAG &DAG) {
13354   assert(Subtarget->is64Bit() && "Result not type legalized?");
13355   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13356   SDValue TheChain = Op.getOperand(0);
13357   SDLoc dl(Op);
13358   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13359   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13360   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13361                                    rax.getValue(2));
13362   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13363                             DAG.getConstant(32, MVT::i8));
13364   SDValue Ops[] = {
13365     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13366     rdx.getValue(1)
13367   };
13368   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13369 }
13370
13371 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13372                             SelectionDAG &DAG) {
13373   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13374   MVT DstVT = Op.getSimpleValueType();
13375   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13376          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13377   assert((DstVT == MVT::i64 ||
13378           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13379          "Unexpected custom BITCAST");
13380   // i64 <=> MMX conversions are Legal.
13381   if (SrcVT==MVT::i64 && DstVT.isVector())
13382     return Op;
13383   if (DstVT==MVT::i64 && SrcVT.isVector())
13384     return Op;
13385   // MMX <=> MMX conversions are Legal.
13386   if (SrcVT.isVector() && DstVT.isVector())
13387     return Op;
13388   // All other conversions need to be expanded.
13389   return SDValue();
13390 }
13391
13392 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13393   SDNode *Node = Op.getNode();
13394   SDLoc dl(Node);
13395   EVT T = Node->getValueType(0);
13396   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13397                               DAG.getConstant(0, T), Node->getOperand(2));
13398   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13399                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13400                        Node->getOperand(0),
13401                        Node->getOperand(1), negOp,
13402                        cast<AtomicSDNode>(Node)->getSrcValue(),
13403                        cast<AtomicSDNode>(Node)->getAlignment(),
13404                        cast<AtomicSDNode>(Node)->getOrdering(),
13405                        cast<AtomicSDNode>(Node)->getSynchScope());
13406 }
13407
13408 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13409   SDNode *Node = Op.getNode();
13410   SDLoc dl(Node);
13411   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13412
13413   // Convert seq_cst store -> xchg
13414   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13415   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13416   //        (The only way to get a 16-byte store is cmpxchg16b)
13417   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13418   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13419       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13420     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13421                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13422                                  Node->getOperand(0),
13423                                  Node->getOperand(1), Node->getOperand(2),
13424                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13425                                  cast<AtomicSDNode>(Node)->getOrdering(),
13426                                  cast<AtomicSDNode>(Node)->getSynchScope());
13427     return Swap.getValue(1);
13428   }
13429   // Other atomic stores have a simple pattern.
13430   return Op;
13431 }
13432
13433 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13434   EVT VT = Op.getNode()->getValueType(0);
13435
13436   // Let legalize expand this if it isn't a legal type yet.
13437   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13438     return SDValue();
13439
13440   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13441
13442   unsigned Opc;
13443   bool ExtraOp = false;
13444   switch (Op.getOpcode()) {
13445   default: llvm_unreachable("Invalid code");
13446   case ISD::ADDC: Opc = X86ISD::ADD; break;
13447   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13448   case ISD::SUBC: Opc = X86ISD::SUB; break;
13449   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13450   }
13451
13452   if (!ExtraOp)
13453     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13454                        Op.getOperand(1));
13455   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13456                      Op.getOperand(1), Op.getOperand(2));
13457 }
13458
13459 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13460                             SelectionDAG &DAG) {
13461   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13462
13463   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13464   // which returns the values as { float, float } (in XMM0) or
13465   // { double, double } (which is returned in XMM0, XMM1).
13466   SDLoc dl(Op);
13467   SDValue Arg = Op.getOperand(0);
13468   EVT ArgVT = Arg.getValueType();
13469   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13470
13471   TargetLowering::ArgListTy Args;
13472   TargetLowering::ArgListEntry Entry;
13473
13474   Entry.Node = Arg;
13475   Entry.Ty = ArgTy;
13476   Entry.isSExt = false;
13477   Entry.isZExt = false;
13478   Args.push_back(Entry);
13479
13480   bool isF64 = ArgVT == MVT::f64;
13481   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13482   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13483   // the results are returned via SRet in memory.
13484   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13485   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13486   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13487
13488   Type *RetTy = isF64
13489     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13490     : (Type*)VectorType::get(ArgTy, 4);
13491   TargetLowering::
13492     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13493                          false, false, false, false, 0,
13494                          CallingConv::C, /*isTaillCall=*/false,
13495                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13496                          Callee, Args, DAG, dl);
13497   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13498
13499   if (isF64)
13500     // Returned in xmm0 and xmm1.
13501     return CallResult.first;
13502
13503   // Returned in bits 0:31 and 32:64 xmm0.
13504   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13505                                CallResult.first, DAG.getIntPtrConstant(0));
13506   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13507                                CallResult.first, DAG.getIntPtrConstant(1));
13508   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13509   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13510 }
13511
13512 /// LowerOperation - Provide custom lowering hooks for some operations.
13513 ///
13514 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13515   switch (Op.getOpcode()) {
13516   default: llvm_unreachable("Should not custom lower this!");
13517   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13518   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13519   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13520   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13521   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13522   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13523   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13524   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13525   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13526   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13527   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13528   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13529   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13530   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13531   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13532   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13533   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13534   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13535   case ISD::SHL_PARTS:
13536   case ISD::SRA_PARTS:
13537   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13538   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13539   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13540   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13541   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13542   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13543   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13544   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13545   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13546   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13547   case ISD::FABS:               return LowerFABS(Op, DAG);
13548   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13549   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13550   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13551   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13552   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13553   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13554   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13555   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13556   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13557   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13558   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13559   case ISD::INTRINSIC_VOID:
13560   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13561   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13562   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13563   case ISD::FRAME_TO_ARGS_OFFSET:
13564                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13565   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13566   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13567   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13568   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13569   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13570   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13571   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13572   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13573   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13574   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13575   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13576   case ISD::SRA:
13577   case ISD::SRL:
13578   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13579   case ISD::SADDO:
13580   case ISD::UADDO:
13581   case ISD::SSUBO:
13582   case ISD::USUBO:
13583   case ISD::SMULO:
13584   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13585   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13586   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13587   case ISD::ADDC:
13588   case ISD::ADDE:
13589   case ISD::SUBC:
13590   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13591   case ISD::ADD:                return LowerADD(Op, DAG);
13592   case ISD::SUB:                return LowerSUB(Op, DAG);
13593   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13594   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13595   }
13596 }
13597
13598 static void ReplaceATOMIC_LOAD(SDNode *Node,
13599                                   SmallVectorImpl<SDValue> &Results,
13600                                   SelectionDAG &DAG) {
13601   SDLoc dl(Node);
13602   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13603
13604   // Convert wide load -> cmpxchg8b/cmpxchg16b
13605   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13606   //        (The only way to get a 16-byte load is cmpxchg16b)
13607   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13608   SDValue Zero = DAG.getConstant(0, VT);
13609   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13610                                Node->getOperand(0),
13611                                Node->getOperand(1), Zero, Zero,
13612                                cast<AtomicSDNode>(Node)->getMemOperand(),
13613                                cast<AtomicSDNode>(Node)->getOrdering(),
13614                                cast<AtomicSDNode>(Node)->getSynchScope());
13615   Results.push_back(Swap.getValue(0));
13616   Results.push_back(Swap.getValue(1));
13617 }
13618
13619 static void
13620 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13621                         SelectionDAG &DAG, unsigned NewOp) {
13622   SDLoc dl(Node);
13623   assert (Node->getValueType(0) == MVT::i64 &&
13624           "Only know how to expand i64 atomics");
13625
13626   SDValue Chain = Node->getOperand(0);
13627   SDValue In1 = Node->getOperand(1);
13628   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13629                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13630   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13631                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13632   SDValue Ops[] = { Chain, In1, In2L, In2H };
13633   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13634   SDValue Result =
13635     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13636                             cast<MemSDNode>(Node)->getMemOperand());
13637   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13638   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13639   Results.push_back(Result.getValue(2));
13640 }
13641
13642 /// ReplaceNodeResults - Replace a node with an illegal result type
13643 /// with a new node built out of custom code.
13644 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13645                                            SmallVectorImpl<SDValue>&Results,
13646                                            SelectionDAG &DAG) const {
13647   SDLoc dl(N);
13648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13649   switch (N->getOpcode()) {
13650   default:
13651     llvm_unreachable("Do not know how to custom type legalize this operation!");
13652   case ISD::SIGN_EXTEND_INREG:
13653   case ISD::ADDC:
13654   case ISD::ADDE:
13655   case ISD::SUBC:
13656   case ISD::SUBE:
13657     // We don't want to expand or promote these.
13658     return;
13659   case ISD::FP_TO_SINT:
13660   case ISD::FP_TO_UINT: {
13661     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13662
13663     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13664       return;
13665
13666     std::pair<SDValue,SDValue> Vals =
13667         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13668     SDValue FIST = Vals.first, StackSlot = Vals.second;
13669     if (FIST.getNode() != 0) {
13670       EVT VT = N->getValueType(0);
13671       // Return a load from the stack slot.
13672       if (StackSlot.getNode() != 0)
13673         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13674                                       MachinePointerInfo(),
13675                                       false, false, false, 0));
13676       else
13677         Results.push_back(FIST);
13678     }
13679     return;
13680   }
13681   case ISD::UINT_TO_FP: {
13682     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13683     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13684         N->getValueType(0) != MVT::v2f32)
13685       return;
13686     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13687                                  N->getOperand(0));
13688     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13689                                      MVT::f64);
13690     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13691     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13692                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13693     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13694     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13695     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13696     return;
13697   }
13698   case ISD::FP_ROUND: {
13699     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13700         return;
13701     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13702     Results.push_back(V);
13703     return;
13704   }
13705   case ISD::READCYCLECOUNTER: {
13706     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13707     SDValue TheChain = N->getOperand(0);
13708     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13709     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13710                                      rd.getValue(1));
13711     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13712                                      eax.getValue(2));
13713     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13714     SDValue Ops[] = { eax, edx };
13715     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13716                                   array_lengthof(Ops)));
13717     Results.push_back(edx.getValue(1));
13718     return;
13719   }
13720   case ISD::ATOMIC_CMP_SWAP: {
13721     EVT T = N->getValueType(0);
13722     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13723     bool Regs64bit = T == MVT::i128;
13724     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13725     SDValue cpInL, cpInH;
13726     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13727                         DAG.getConstant(0, HalfT));
13728     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13729                         DAG.getConstant(1, HalfT));
13730     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13731                              Regs64bit ? X86::RAX : X86::EAX,
13732                              cpInL, SDValue());
13733     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13734                              Regs64bit ? X86::RDX : X86::EDX,
13735                              cpInH, cpInL.getValue(1));
13736     SDValue swapInL, swapInH;
13737     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13738                           DAG.getConstant(0, HalfT));
13739     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13740                           DAG.getConstant(1, HalfT));
13741     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13742                                Regs64bit ? X86::RBX : X86::EBX,
13743                                swapInL, cpInH.getValue(1));
13744     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13745                                Regs64bit ? X86::RCX : X86::ECX,
13746                                swapInH, swapInL.getValue(1));
13747     SDValue Ops[] = { swapInH.getValue(0),
13748                       N->getOperand(1),
13749                       swapInH.getValue(1) };
13750     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13751     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13752     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13753                                   X86ISD::LCMPXCHG8_DAG;
13754     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13755                                              Ops, array_lengthof(Ops), T, MMO);
13756     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13757                                         Regs64bit ? X86::RAX : X86::EAX,
13758                                         HalfT, Result.getValue(1));
13759     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13760                                         Regs64bit ? X86::RDX : X86::EDX,
13761                                         HalfT, cpOutL.getValue(2));
13762     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13763     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13764     Results.push_back(cpOutH.getValue(1));
13765     return;
13766   }
13767   case ISD::ATOMIC_LOAD_ADD:
13768   case ISD::ATOMIC_LOAD_AND:
13769   case ISD::ATOMIC_LOAD_NAND:
13770   case ISD::ATOMIC_LOAD_OR:
13771   case ISD::ATOMIC_LOAD_SUB:
13772   case ISD::ATOMIC_LOAD_XOR:
13773   case ISD::ATOMIC_LOAD_MAX:
13774   case ISD::ATOMIC_LOAD_MIN:
13775   case ISD::ATOMIC_LOAD_UMAX:
13776   case ISD::ATOMIC_LOAD_UMIN:
13777   case ISD::ATOMIC_SWAP: {
13778     unsigned Opc;
13779     switch (N->getOpcode()) {
13780     default: llvm_unreachable("Unexpected opcode");
13781     case ISD::ATOMIC_LOAD_ADD:
13782       Opc = X86ISD::ATOMADD64_DAG;
13783       break;
13784     case ISD::ATOMIC_LOAD_AND:
13785       Opc = X86ISD::ATOMAND64_DAG;
13786       break;
13787     case ISD::ATOMIC_LOAD_NAND:
13788       Opc = X86ISD::ATOMNAND64_DAG;
13789       break;
13790     case ISD::ATOMIC_LOAD_OR:
13791       Opc = X86ISD::ATOMOR64_DAG;
13792       break;
13793     case ISD::ATOMIC_LOAD_SUB:
13794       Opc = X86ISD::ATOMSUB64_DAG;
13795       break;
13796     case ISD::ATOMIC_LOAD_XOR:
13797       Opc = X86ISD::ATOMXOR64_DAG;
13798       break;
13799     case ISD::ATOMIC_LOAD_MAX:
13800       Opc = X86ISD::ATOMMAX64_DAG;
13801       break;
13802     case ISD::ATOMIC_LOAD_MIN:
13803       Opc = X86ISD::ATOMMIN64_DAG;
13804       break;
13805     case ISD::ATOMIC_LOAD_UMAX:
13806       Opc = X86ISD::ATOMUMAX64_DAG;
13807       break;
13808     case ISD::ATOMIC_LOAD_UMIN:
13809       Opc = X86ISD::ATOMUMIN64_DAG;
13810       break;
13811     case ISD::ATOMIC_SWAP:
13812       Opc = X86ISD::ATOMSWAP64_DAG;
13813       break;
13814     }
13815     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13816     return;
13817   }
13818   case ISD::ATOMIC_LOAD:
13819     ReplaceATOMIC_LOAD(N, Results, DAG);
13820   }
13821 }
13822
13823 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13824   switch (Opcode) {
13825   default: return NULL;
13826   case X86ISD::BSF:                return "X86ISD::BSF";
13827   case X86ISD::BSR:                return "X86ISD::BSR";
13828   case X86ISD::SHLD:               return "X86ISD::SHLD";
13829   case X86ISD::SHRD:               return "X86ISD::SHRD";
13830   case X86ISD::FAND:               return "X86ISD::FAND";
13831   case X86ISD::FANDN:              return "X86ISD::FANDN";
13832   case X86ISD::FOR:                return "X86ISD::FOR";
13833   case X86ISD::FXOR:               return "X86ISD::FXOR";
13834   case X86ISD::FSRL:               return "X86ISD::FSRL";
13835   case X86ISD::FILD:               return "X86ISD::FILD";
13836   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13837   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13838   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13839   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13840   case X86ISD::FLD:                return "X86ISD::FLD";
13841   case X86ISD::FST:                return "X86ISD::FST";
13842   case X86ISD::CALL:               return "X86ISD::CALL";
13843   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13844   case X86ISD::BT:                 return "X86ISD::BT";
13845   case X86ISD::CMP:                return "X86ISD::CMP";
13846   case X86ISD::COMI:               return "X86ISD::COMI";
13847   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13848   case X86ISD::CMPM:               return "X86ISD::CMPM";
13849   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
13850   case X86ISD::SETCC:              return "X86ISD::SETCC";
13851   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13852   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
13853   case X86ISD::CMOV:               return "X86ISD::CMOV";
13854   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13855   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13856   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13857   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13858   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13859   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13860   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13861   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13862   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13863   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13864   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13865   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13866   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13867   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13868   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13869   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13870   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13871   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13872   case X86ISD::HADD:               return "X86ISD::HADD";
13873   case X86ISD::HSUB:               return "X86ISD::HSUB";
13874   case X86ISD::FHADD:              return "X86ISD::FHADD";
13875   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13876   case X86ISD::UMAX:               return "X86ISD::UMAX";
13877   case X86ISD::UMIN:               return "X86ISD::UMIN";
13878   case X86ISD::SMAX:               return "X86ISD::SMAX";
13879   case X86ISD::SMIN:               return "X86ISD::SMIN";
13880   case X86ISD::FMAX:               return "X86ISD::FMAX";
13881   case X86ISD::FMIN:               return "X86ISD::FMIN";
13882   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13883   case X86ISD::FMINC:              return "X86ISD::FMINC";
13884   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13885   case X86ISD::FRCP:               return "X86ISD::FRCP";
13886   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13887   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13888   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13889   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13890   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13891   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13892   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13893   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13894   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13895   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13896   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13897   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13898   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13899   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13900   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13901   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13902   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13903   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13904   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13905   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13906   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13907   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13908   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
13909   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
13910   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
13911   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13912   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13913   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13914   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13915   case X86ISD::VSHL:               return "X86ISD::VSHL";
13916   case X86ISD::VSRL:               return "X86ISD::VSRL";
13917   case X86ISD::VSRA:               return "X86ISD::VSRA";
13918   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13919   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13920   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13921   case X86ISD::CMPP:               return "X86ISD::CMPP";
13922   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13923   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13924   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
13925   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
13926   case X86ISD::ADD:                return "X86ISD::ADD";
13927   case X86ISD::SUB:                return "X86ISD::SUB";
13928   case X86ISD::ADC:                return "X86ISD::ADC";
13929   case X86ISD::SBB:                return "X86ISD::SBB";
13930   case X86ISD::SMUL:               return "X86ISD::SMUL";
13931   case X86ISD::UMUL:               return "X86ISD::UMUL";
13932   case X86ISD::INC:                return "X86ISD::INC";
13933   case X86ISD::DEC:                return "X86ISD::DEC";
13934   case X86ISD::OR:                 return "X86ISD::OR";
13935   case X86ISD::XOR:                return "X86ISD::XOR";
13936   case X86ISD::AND:                return "X86ISD::AND";
13937   case X86ISD::BLSI:               return "X86ISD::BLSI";
13938   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13939   case X86ISD::BLSR:               return "X86ISD::BLSR";
13940   case X86ISD::BZHI:               return "X86ISD::BZHI";
13941   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
13942   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13943   case X86ISD::PTEST:              return "X86ISD::PTEST";
13944   case X86ISD::TESTP:              return "X86ISD::TESTP";
13945   case X86ISD::TESTM:              return "X86ISD::TESTM";
13946   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
13947   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13948   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13949   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13950   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13951   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13952   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13953   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13954   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13955   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13956   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13957   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13958   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13959   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13960   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13961   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13962   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13963   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13964   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13965   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
13966   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13967   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13968   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13969   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
13970   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13971   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13972   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13973   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13974   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13975   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13976   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13977   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13978   case X86ISD::SAHF:               return "X86ISD::SAHF";
13979   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13980   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13981   case X86ISD::FMADD:              return "X86ISD::FMADD";
13982   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13983   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13984   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13985   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13986   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13987   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13988   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13989   case X86ISD::XTEST:              return "X86ISD::XTEST";
13990   }
13991 }
13992
13993 // isLegalAddressingMode - Return true if the addressing mode represented
13994 // by AM is legal for this target, for a load/store of the specified type.
13995 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13996                                               Type *Ty) const {
13997   // X86 supports extremely general addressing modes.
13998   CodeModel::Model M = getTargetMachine().getCodeModel();
13999   Reloc::Model R = getTargetMachine().getRelocationModel();
14000
14001   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14002   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14003     return false;
14004
14005   if (AM.BaseGV) {
14006     unsigned GVFlags =
14007       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14008
14009     // If a reference to this global requires an extra load, we can't fold it.
14010     if (isGlobalStubReference(GVFlags))
14011       return false;
14012
14013     // If BaseGV requires a register for the PIC base, we cannot also have a
14014     // BaseReg specified.
14015     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14016       return false;
14017
14018     // If lower 4G is not available, then we must use rip-relative addressing.
14019     if ((M != CodeModel::Small || R != Reloc::Static) &&
14020         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14021       return false;
14022   }
14023
14024   switch (AM.Scale) {
14025   case 0:
14026   case 1:
14027   case 2:
14028   case 4:
14029   case 8:
14030     // These scales always work.
14031     break;
14032   case 3:
14033   case 5:
14034   case 9:
14035     // These scales are formed with basereg+scalereg.  Only accept if there is
14036     // no basereg yet.
14037     if (AM.HasBaseReg)
14038       return false;
14039     break;
14040   default:  // Other stuff never works.
14041     return false;
14042   }
14043
14044   return true;
14045 }
14046
14047 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14048   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14049     return false;
14050   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14051   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14052   return NumBits1 > NumBits2;
14053 }
14054
14055 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14056   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14057     return false;
14058
14059   if (!isTypeLegal(EVT::getEVT(Ty1)))
14060     return false;
14061
14062   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14063
14064   // Assuming the caller doesn't have a zeroext or signext return parameter,
14065   // truncation all the way down to i1 is valid.
14066   return true;
14067 }
14068
14069 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14070   return isInt<32>(Imm);
14071 }
14072
14073 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14074   // Can also use sub to handle negated immediates.
14075   return isInt<32>(Imm);
14076 }
14077
14078 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14079   if (!VT1.isInteger() || !VT2.isInteger())
14080     return false;
14081   unsigned NumBits1 = VT1.getSizeInBits();
14082   unsigned NumBits2 = VT2.getSizeInBits();
14083   return NumBits1 > NumBits2;
14084 }
14085
14086 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14087   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14088   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14089 }
14090
14091 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14092   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14093   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14094 }
14095
14096 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14097   EVT VT1 = Val.getValueType();
14098   if (isZExtFree(VT1, VT2))
14099     return true;
14100
14101   if (Val.getOpcode() != ISD::LOAD)
14102     return false;
14103
14104   if (!VT1.isSimple() || !VT1.isInteger() ||
14105       !VT2.isSimple() || !VT2.isInteger())
14106     return false;
14107
14108   switch (VT1.getSimpleVT().SimpleTy) {
14109   default: break;
14110   case MVT::i8:
14111   case MVT::i16:
14112   case MVT::i32:
14113     // X86 has 8, 16, and 32-bit zero-extending loads.
14114     return true;
14115   }
14116
14117   return false;
14118 }
14119
14120 bool
14121 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14122   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14123     return false;
14124
14125   VT = VT.getScalarType();
14126
14127   if (!VT.isSimple())
14128     return false;
14129
14130   switch (VT.getSimpleVT().SimpleTy) {
14131   case MVT::f32:
14132   case MVT::f64:
14133     return true;
14134   default:
14135     break;
14136   }
14137
14138   return false;
14139 }
14140
14141 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14142   // i16 instructions are longer (0x66 prefix) and potentially slower.
14143   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14144 }
14145
14146 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14147 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14148 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14149 /// are assumed to be legal.
14150 bool
14151 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14152                                       EVT VT) const {
14153   if (!VT.isSimple())
14154     return false;
14155
14156   MVT SVT = VT.getSimpleVT();
14157
14158   // Very little shuffling can be done for 64-bit vectors right now.
14159   if (VT.getSizeInBits() == 64)
14160     return false;
14161
14162   // FIXME: pshufb, blends, shifts.
14163   return (SVT.getVectorNumElements() == 2 ||
14164           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14165           isMOVLMask(M, SVT) ||
14166           isSHUFPMask(M, SVT) ||
14167           isPSHUFDMask(M, SVT) ||
14168           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14169           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14170           isPALIGNRMask(M, SVT, Subtarget) ||
14171           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14172           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14173           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14174           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14175 }
14176
14177 bool
14178 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14179                                           EVT VT) const {
14180   if (!VT.isSimple())
14181     return false;
14182
14183   MVT SVT = VT.getSimpleVT();
14184   unsigned NumElts = SVT.getVectorNumElements();
14185   // FIXME: This collection of masks seems suspect.
14186   if (NumElts == 2)
14187     return true;
14188   if (NumElts == 4 && SVT.is128BitVector()) {
14189     return (isMOVLMask(Mask, SVT)  ||
14190             isCommutedMOVLMask(Mask, SVT, true) ||
14191             isSHUFPMask(Mask, SVT) ||
14192             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14193   }
14194   return false;
14195 }
14196
14197 //===----------------------------------------------------------------------===//
14198 //                           X86 Scheduler Hooks
14199 //===----------------------------------------------------------------------===//
14200
14201 /// Utility function to emit xbegin specifying the start of an RTM region.
14202 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14203                                      const TargetInstrInfo *TII) {
14204   DebugLoc DL = MI->getDebugLoc();
14205
14206   const BasicBlock *BB = MBB->getBasicBlock();
14207   MachineFunction::iterator I = MBB;
14208   ++I;
14209
14210   // For the v = xbegin(), we generate
14211   //
14212   // thisMBB:
14213   //  xbegin sinkMBB
14214   //
14215   // mainMBB:
14216   //  eax = -1
14217   //
14218   // sinkMBB:
14219   //  v = eax
14220
14221   MachineBasicBlock *thisMBB = MBB;
14222   MachineFunction *MF = MBB->getParent();
14223   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14224   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14225   MF->insert(I, mainMBB);
14226   MF->insert(I, sinkMBB);
14227
14228   // Transfer the remainder of BB and its successor edges to sinkMBB.
14229   sinkMBB->splice(sinkMBB->begin(), MBB,
14230                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14231   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14232
14233   // thisMBB:
14234   //  xbegin sinkMBB
14235   //  # fallthrough to mainMBB
14236   //  # abortion to sinkMBB
14237   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14238   thisMBB->addSuccessor(mainMBB);
14239   thisMBB->addSuccessor(sinkMBB);
14240
14241   // mainMBB:
14242   //  EAX = -1
14243   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14244   mainMBB->addSuccessor(sinkMBB);
14245
14246   // sinkMBB:
14247   // EAX is live into the sinkMBB
14248   sinkMBB->addLiveIn(X86::EAX);
14249   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14250           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14251     .addReg(X86::EAX);
14252
14253   MI->eraseFromParent();
14254   return sinkMBB;
14255 }
14256
14257 // Get CMPXCHG opcode for the specified data type.
14258 static unsigned getCmpXChgOpcode(EVT VT) {
14259   switch (VT.getSimpleVT().SimpleTy) {
14260   case MVT::i8:  return X86::LCMPXCHG8;
14261   case MVT::i16: return X86::LCMPXCHG16;
14262   case MVT::i32: return X86::LCMPXCHG32;
14263   case MVT::i64: return X86::LCMPXCHG64;
14264   default:
14265     break;
14266   }
14267   llvm_unreachable("Invalid operand size!");
14268 }
14269
14270 // Get LOAD opcode for the specified data type.
14271 static unsigned getLoadOpcode(EVT VT) {
14272   switch (VT.getSimpleVT().SimpleTy) {
14273   case MVT::i8:  return X86::MOV8rm;
14274   case MVT::i16: return X86::MOV16rm;
14275   case MVT::i32: return X86::MOV32rm;
14276   case MVT::i64: return X86::MOV64rm;
14277   default:
14278     break;
14279   }
14280   llvm_unreachable("Invalid operand size!");
14281 }
14282
14283 // Get opcode of the non-atomic one from the specified atomic instruction.
14284 static unsigned getNonAtomicOpcode(unsigned Opc) {
14285   switch (Opc) {
14286   case X86::ATOMAND8:  return X86::AND8rr;
14287   case X86::ATOMAND16: return X86::AND16rr;
14288   case X86::ATOMAND32: return X86::AND32rr;
14289   case X86::ATOMAND64: return X86::AND64rr;
14290   case X86::ATOMOR8:   return X86::OR8rr;
14291   case X86::ATOMOR16:  return X86::OR16rr;
14292   case X86::ATOMOR32:  return X86::OR32rr;
14293   case X86::ATOMOR64:  return X86::OR64rr;
14294   case X86::ATOMXOR8:  return X86::XOR8rr;
14295   case X86::ATOMXOR16: return X86::XOR16rr;
14296   case X86::ATOMXOR32: return X86::XOR32rr;
14297   case X86::ATOMXOR64: return X86::XOR64rr;
14298   }
14299   llvm_unreachable("Unhandled atomic-load-op opcode!");
14300 }
14301
14302 // Get opcode of the non-atomic one from the specified atomic instruction with
14303 // extra opcode.
14304 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14305                                                unsigned &ExtraOpc) {
14306   switch (Opc) {
14307   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14308   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14309   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14310   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14311   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14312   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14313   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14314   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14315   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14316   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14317   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14318   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14319   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14320   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14321   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14322   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14323   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14324   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14325   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14326   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14327   }
14328   llvm_unreachable("Unhandled atomic-load-op opcode!");
14329 }
14330
14331 // Get opcode of the non-atomic one from the specified atomic instruction for
14332 // 64-bit data type on 32-bit target.
14333 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14334   switch (Opc) {
14335   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14336   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14337   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14338   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14339   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14340   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14341   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14342   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14343   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14344   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14345   }
14346   llvm_unreachable("Unhandled atomic-load-op opcode!");
14347 }
14348
14349 // Get opcode of the non-atomic one from the specified atomic instruction for
14350 // 64-bit data type on 32-bit target with extra opcode.
14351 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14352                                                    unsigned &HiOpc,
14353                                                    unsigned &ExtraOpc) {
14354   switch (Opc) {
14355   case X86::ATOMNAND6432:
14356     ExtraOpc = X86::NOT32r;
14357     HiOpc = X86::AND32rr;
14358     return X86::AND32rr;
14359   }
14360   llvm_unreachable("Unhandled atomic-load-op opcode!");
14361 }
14362
14363 // Get pseudo CMOV opcode from the specified data type.
14364 static unsigned getPseudoCMOVOpc(EVT VT) {
14365   switch (VT.getSimpleVT().SimpleTy) {
14366   case MVT::i8:  return X86::CMOV_GR8;
14367   case MVT::i16: return X86::CMOV_GR16;
14368   case MVT::i32: return X86::CMOV_GR32;
14369   default:
14370     break;
14371   }
14372   llvm_unreachable("Unknown CMOV opcode!");
14373 }
14374
14375 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14376 // They will be translated into a spin-loop or compare-exchange loop from
14377 //
14378 //    ...
14379 //    dst = atomic-fetch-op MI.addr, MI.val
14380 //    ...
14381 //
14382 // to
14383 //
14384 //    ...
14385 //    t1 = LOAD MI.addr
14386 // loop:
14387 //    t4 = phi(t1, t3 / loop)
14388 //    t2 = OP MI.val, t4
14389 //    EAX = t4
14390 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14391 //    t3 = EAX
14392 //    JNE loop
14393 // sink:
14394 //    dst = t3
14395 //    ...
14396 MachineBasicBlock *
14397 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14398                                        MachineBasicBlock *MBB) const {
14399   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14400   DebugLoc DL = MI->getDebugLoc();
14401
14402   MachineFunction *MF = MBB->getParent();
14403   MachineRegisterInfo &MRI = MF->getRegInfo();
14404
14405   const BasicBlock *BB = MBB->getBasicBlock();
14406   MachineFunction::iterator I = MBB;
14407   ++I;
14408
14409   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14410          "Unexpected number of operands");
14411
14412   assert(MI->hasOneMemOperand() &&
14413          "Expected atomic-load-op to have one memoperand");
14414
14415   // Memory Reference
14416   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14417   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14418
14419   unsigned DstReg, SrcReg;
14420   unsigned MemOpndSlot;
14421
14422   unsigned CurOp = 0;
14423
14424   DstReg = MI->getOperand(CurOp++).getReg();
14425   MemOpndSlot = CurOp;
14426   CurOp += X86::AddrNumOperands;
14427   SrcReg = MI->getOperand(CurOp++).getReg();
14428
14429   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14430   MVT::SimpleValueType VT = *RC->vt_begin();
14431   unsigned t1 = MRI.createVirtualRegister(RC);
14432   unsigned t2 = MRI.createVirtualRegister(RC);
14433   unsigned t3 = MRI.createVirtualRegister(RC);
14434   unsigned t4 = MRI.createVirtualRegister(RC);
14435   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14436
14437   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14438   unsigned LOADOpc = getLoadOpcode(VT);
14439
14440   // For the atomic load-arith operator, we generate
14441   //
14442   //  thisMBB:
14443   //    t1 = LOAD [MI.addr]
14444   //  mainMBB:
14445   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14446   //    t1 = OP MI.val, EAX
14447   //    EAX = t4
14448   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14449   //    t3 = EAX
14450   //    JNE mainMBB
14451   //  sinkMBB:
14452   //    dst = t3
14453
14454   MachineBasicBlock *thisMBB = MBB;
14455   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14456   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14457   MF->insert(I, mainMBB);
14458   MF->insert(I, sinkMBB);
14459
14460   MachineInstrBuilder MIB;
14461
14462   // Transfer the remainder of BB and its successor edges to sinkMBB.
14463   sinkMBB->splice(sinkMBB->begin(), MBB,
14464                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14465   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14466
14467   // thisMBB:
14468   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14469   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14470     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14471     if (NewMO.isReg())
14472       NewMO.setIsKill(false);
14473     MIB.addOperand(NewMO);
14474   }
14475   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14476     unsigned flags = (*MMOI)->getFlags();
14477     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14478     MachineMemOperand *MMO =
14479       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14480                                (*MMOI)->getSize(),
14481                                (*MMOI)->getBaseAlignment(),
14482                                (*MMOI)->getTBAAInfo(),
14483                                (*MMOI)->getRanges());
14484     MIB.addMemOperand(MMO);
14485   }
14486
14487   thisMBB->addSuccessor(mainMBB);
14488
14489   // mainMBB:
14490   MachineBasicBlock *origMainMBB = mainMBB;
14491
14492   // Add a PHI.
14493   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14494                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14495
14496   unsigned Opc = MI->getOpcode();
14497   switch (Opc) {
14498   default:
14499     llvm_unreachable("Unhandled atomic-load-op opcode!");
14500   case X86::ATOMAND8:
14501   case X86::ATOMAND16:
14502   case X86::ATOMAND32:
14503   case X86::ATOMAND64:
14504   case X86::ATOMOR8:
14505   case X86::ATOMOR16:
14506   case X86::ATOMOR32:
14507   case X86::ATOMOR64:
14508   case X86::ATOMXOR8:
14509   case X86::ATOMXOR16:
14510   case X86::ATOMXOR32:
14511   case X86::ATOMXOR64: {
14512     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14513     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14514       .addReg(t4);
14515     break;
14516   }
14517   case X86::ATOMNAND8:
14518   case X86::ATOMNAND16:
14519   case X86::ATOMNAND32:
14520   case X86::ATOMNAND64: {
14521     unsigned Tmp = MRI.createVirtualRegister(RC);
14522     unsigned NOTOpc;
14523     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14524     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14525       .addReg(t4);
14526     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14527     break;
14528   }
14529   case X86::ATOMMAX8:
14530   case X86::ATOMMAX16:
14531   case X86::ATOMMAX32:
14532   case X86::ATOMMAX64:
14533   case X86::ATOMMIN8:
14534   case X86::ATOMMIN16:
14535   case X86::ATOMMIN32:
14536   case X86::ATOMMIN64:
14537   case X86::ATOMUMAX8:
14538   case X86::ATOMUMAX16:
14539   case X86::ATOMUMAX32:
14540   case X86::ATOMUMAX64:
14541   case X86::ATOMUMIN8:
14542   case X86::ATOMUMIN16:
14543   case X86::ATOMUMIN32:
14544   case X86::ATOMUMIN64: {
14545     unsigned CMPOpc;
14546     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14547
14548     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14549       .addReg(SrcReg)
14550       .addReg(t4);
14551
14552     if (Subtarget->hasCMov()) {
14553       if (VT != MVT::i8) {
14554         // Native support
14555         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14556           .addReg(SrcReg)
14557           .addReg(t4);
14558       } else {
14559         // Promote i8 to i32 to use CMOV32
14560         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14561         const TargetRegisterClass *RC32 =
14562           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14563         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14564         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14565         unsigned Tmp = MRI.createVirtualRegister(RC32);
14566
14567         unsigned Undef = MRI.createVirtualRegister(RC32);
14568         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14569
14570         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14571           .addReg(Undef)
14572           .addReg(SrcReg)
14573           .addImm(X86::sub_8bit);
14574         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14575           .addReg(Undef)
14576           .addReg(t4)
14577           .addImm(X86::sub_8bit);
14578
14579         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14580           .addReg(SrcReg32)
14581           .addReg(AccReg32);
14582
14583         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14584           .addReg(Tmp, 0, X86::sub_8bit);
14585       }
14586     } else {
14587       // Use pseudo select and lower them.
14588       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14589              "Invalid atomic-load-op transformation!");
14590       unsigned SelOpc = getPseudoCMOVOpc(VT);
14591       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14592       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14593       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14594               .addReg(SrcReg).addReg(t4)
14595               .addImm(CC);
14596       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14597       // Replace the original PHI node as mainMBB is changed after CMOV
14598       // lowering.
14599       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14600         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14601       Phi->eraseFromParent();
14602     }
14603     break;
14604   }
14605   }
14606
14607   // Copy PhyReg back from virtual register.
14608   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14609     .addReg(t4);
14610
14611   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14612   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14613     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14614     if (NewMO.isReg())
14615       NewMO.setIsKill(false);
14616     MIB.addOperand(NewMO);
14617   }
14618   MIB.addReg(t2);
14619   MIB.setMemRefs(MMOBegin, MMOEnd);
14620
14621   // Copy PhyReg back to virtual register.
14622   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14623     .addReg(PhyReg);
14624
14625   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14626
14627   mainMBB->addSuccessor(origMainMBB);
14628   mainMBB->addSuccessor(sinkMBB);
14629
14630   // sinkMBB:
14631   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14632           TII->get(TargetOpcode::COPY), DstReg)
14633     .addReg(t3);
14634
14635   MI->eraseFromParent();
14636   return sinkMBB;
14637 }
14638
14639 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14640 // instructions. They will be translated into a spin-loop or compare-exchange
14641 // loop from
14642 //
14643 //    ...
14644 //    dst = atomic-fetch-op MI.addr, MI.val
14645 //    ...
14646 //
14647 // to
14648 //
14649 //    ...
14650 //    t1L = LOAD [MI.addr + 0]
14651 //    t1H = LOAD [MI.addr + 4]
14652 // loop:
14653 //    t4L = phi(t1L, t3L / loop)
14654 //    t4H = phi(t1H, t3H / loop)
14655 //    t2L = OP MI.val.lo, t4L
14656 //    t2H = OP MI.val.hi, t4H
14657 //    EAX = t4L
14658 //    EDX = t4H
14659 //    EBX = t2L
14660 //    ECX = t2H
14661 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14662 //    t3L = EAX
14663 //    t3H = EDX
14664 //    JNE loop
14665 // sink:
14666 //    dstL = t3L
14667 //    dstH = t3H
14668 //    ...
14669 MachineBasicBlock *
14670 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14671                                            MachineBasicBlock *MBB) const {
14672   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14673   DebugLoc DL = MI->getDebugLoc();
14674
14675   MachineFunction *MF = MBB->getParent();
14676   MachineRegisterInfo &MRI = MF->getRegInfo();
14677
14678   const BasicBlock *BB = MBB->getBasicBlock();
14679   MachineFunction::iterator I = MBB;
14680   ++I;
14681
14682   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14683          "Unexpected number of operands");
14684
14685   assert(MI->hasOneMemOperand() &&
14686          "Expected atomic-load-op32 to have one memoperand");
14687
14688   // Memory Reference
14689   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14690   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14691
14692   unsigned DstLoReg, DstHiReg;
14693   unsigned SrcLoReg, SrcHiReg;
14694   unsigned MemOpndSlot;
14695
14696   unsigned CurOp = 0;
14697
14698   DstLoReg = MI->getOperand(CurOp++).getReg();
14699   DstHiReg = MI->getOperand(CurOp++).getReg();
14700   MemOpndSlot = CurOp;
14701   CurOp += X86::AddrNumOperands;
14702   SrcLoReg = MI->getOperand(CurOp++).getReg();
14703   SrcHiReg = MI->getOperand(CurOp++).getReg();
14704
14705   const TargetRegisterClass *RC = &X86::GR32RegClass;
14706   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14707
14708   unsigned t1L = MRI.createVirtualRegister(RC);
14709   unsigned t1H = MRI.createVirtualRegister(RC);
14710   unsigned t2L = MRI.createVirtualRegister(RC);
14711   unsigned t2H = MRI.createVirtualRegister(RC);
14712   unsigned t3L = MRI.createVirtualRegister(RC);
14713   unsigned t3H = MRI.createVirtualRegister(RC);
14714   unsigned t4L = MRI.createVirtualRegister(RC);
14715   unsigned t4H = MRI.createVirtualRegister(RC);
14716
14717   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14718   unsigned LOADOpc = X86::MOV32rm;
14719
14720   // For the atomic load-arith operator, we generate
14721   //
14722   //  thisMBB:
14723   //    t1L = LOAD [MI.addr + 0]
14724   //    t1H = LOAD [MI.addr + 4]
14725   //  mainMBB:
14726   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14727   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14728   //    t2L = OP MI.val.lo, t4L
14729   //    t2H = OP MI.val.hi, t4H
14730   //    EBX = t2L
14731   //    ECX = t2H
14732   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14733   //    t3L = EAX
14734   //    t3H = EDX
14735   //    JNE loop
14736   //  sinkMBB:
14737   //    dstL = t3L
14738   //    dstH = t3H
14739
14740   MachineBasicBlock *thisMBB = MBB;
14741   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14742   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14743   MF->insert(I, mainMBB);
14744   MF->insert(I, sinkMBB);
14745
14746   MachineInstrBuilder MIB;
14747
14748   // Transfer the remainder of BB and its successor edges to sinkMBB.
14749   sinkMBB->splice(sinkMBB->begin(), MBB,
14750                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14751   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14752
14753   // thisMBB:
14754   // Lo
14755   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14756   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14757     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14758     if (NewMO.isReg())
14759       NewMO.setIsKill(false);
14760     MIB.addOperand(NewMO);
14761   }
14762   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14763     unsigned flags = (*MMOI)->getFlags();
14764     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14765     MachineMemOperand *MMO =
14766       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14767                                (*MMOI)->getSize(),
14768                                (*MMOI)->getBaseAlignment(),
14769                                (*MMOI)->getTBAAInfo(),
14770                                (*MMOI)->getRanges());
14771     MIB.addMemOperand(MMO);
14772   };
14773   MachineInstr *LowMI = MIB;
14774
14775   // Hi
14776   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14777   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14778     if (i == X86::AddrDisp) {
14779       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14780     } else {
14781       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14782       if (NewMO.isReg())
14783         NewMO.setIsKill(false);
14784       MIB.addOperand(NewMO);
14785     }
14786   }
14787   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14788
14789   thisMBB->addSuccessor(mainMBB);
14790
14791   // mainMBB:
14792   MachineBasicBlock *origMainMBB = mainMBB;
14793
14794   // Add PHIs.
14795   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14796                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14797   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14798                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14799
14800   unsigned Opc = MI->getOpcode();
14801   switch (Opc) {
14802   default:
14803     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14804   case X86::ATOMAND6432:
14805   case X86::ATOMOR6432:
14806   case X86::ATOMXOR6432:
14807   case X86::ATOMADD6432:
14808   case X86::ATOMSUB6432: {
14809     unsigned HiOpc;
14810     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14811     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14812       .addReg(SrcLoReg);
14813     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14814       .addReg(SrcHiReg);
14815     break;
14816   }
14817   case X86::ATOMNAND6432: {
14818     unsigned HiOpc, NOTOpc;
14819     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14820     unsigned TmpL = MRI.createVirtualRegister(RC);
14821     unsigned TmpH = MRI.createVirtualRegister(RC);
14822     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14823       .addReg(t4L);
14824     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14825       .addReg(t4H);
14826     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14827     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14828     break;
14829   }
14830   case X86::ATOMMAX6432:
14831   case X86::ATOMMIN6432:
14832   case X86::ATOMUMAX6432:
14833   case X86::ATOMUMIN6432: {
14834     unsigned HiOpc;
14835     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14836     unsigned cL = MRI.createVirtualRegister(RC8);
14837     unsigned cH = MRI.createVirtualRegister(RC8);
14838     unsigned cL32 = MRI.createVirtualRegister(RC);
14839     unsigned cH32 = MRI.createVirtualRegister(RC);
14840     unsigned cc = MRI.createVirtualRegister(RC);
14841     // cl := cmp src_lo, lo
14842     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14843       .addReg(SrcLoReg).addReg(t4L);
14844     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14845     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14846     // ch := cmp src_hi, hi
14847     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14848       .addReg(SrcHiReg).addReg(t4H);
14849     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14850     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14851     // cc := if (src_hi == hi) ? cl : ch;
14852     if (Subtarget->hasCMov()) {
14853       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14854         .addReg(cH32).addReg(cL32);
14855     } else {
14856       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14857               .addReg(cH32).addReg(cL32)
14858               .addImm(X86::COND_E);
14859       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14860     }
14861     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14862     if (Subtarget->hasCMov()) {
14863       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14864         .addReg(SrcLoReg).addReg(t4L);
14865       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14866         .addReg(SrcHiReg).addReg(t4H);
14867     } else {
14868       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14869               .addReg(SrcLoReg).addReg(t4L)
14870               .addImm(X86::COND_NE);
14871       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14872       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14873       // 2nd CMOV lowering.
14874       mainMBB->addLiveIn(X86::EFLAGS);
14875       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14876               .addReg(SrcHiReg).addReg(t4H)
14877               .addImm(X86::COND_NE);
14878       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14879       // Replace the original PHI node as mainMBB is changed after CMOV
14880       // lowering.
14881       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14882         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14883       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14884         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14885       PhiL->eraseFromParent();
14886       PhiH->eraseFromParent();
14887     }
14888     break;
14889   }
14890   case X86::ATOMSWAP6432: {
14891     unsigned HiOpc;
14892     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14893     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14894     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14895     break;
14896   }
14897   }
14898
14899   // Copy EDX:EAX back from HiReg:LoReg
14900   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14901   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14902   // Copy ECX:EBX from t1H:t1L
14903   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14904   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14905
14906   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14907   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14908     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14909     if (NewMO.isReg())
14910       NewMO.setIsKill(false);
14911     MIB.addOperand(NewMO);
14912   }
14913   MIB.setMemRefs(MMOBegin, MMOEnd);
14914
14915   // Copy EDX:EAX back to t3H:t3L
14916   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14917   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14918
14919   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14920
14921   mainMBB->addSuccessor(origMainMBB);
14922   mainMBB->addSuccessor(sinkMBB);
14923
14924   // sinkMBB:
14925   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14926           TII->get(TargetOpcode::COPY), DstLoReg)
14927     .addReg(t3L);
14928   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14929           TII->get(TargetOpcode::COPY), DstHiReg)
14930     .addReg(t3H);
14931
14932   MI->eraseFromParent();
14933   return sinkMBB;
14934 }
14935
14936 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14937 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14938 // in the .td file.
14939 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14940                                        const TargetInstrInfo *TII) {
14941   unsigned Opc;
14942   switch (MI->getOpcode()) {
14943   default: llvm_unreachable("illegal opcode!");
14944   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14945   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14946   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14947   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14948   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14949   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14950   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14951   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14952   }
14953
14954   DebugLoc dl = MI->getDebugLoc();
14955   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14956
14957   unsigned NumArgs = MI->getNumOperands();
14958   for (unsigned i = 1; i < NumArgs; ++i) {
14959     MachineOperand &Op = MI->getOperand(i);
14960     if (!(Op.isReg() && Op.isImplicit()))
14961       MIB.addOperand(Op);
14962   }
14963   if (MI->hasOneMemOperand())
14964     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14965
14966   BuildMI(*BB, MI, dl,
14967     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14968     .addReg(X86::XMM0);
14969
14970   MI->eraseFromParent();
14971   return BB;
14972 }
14973
14974 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14975 // defs in an instruction pattern
14976 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14977                                        const TargetInstrInfo *TII) {
14978   unsigned Opc;
14979   switch (MI->getOpcode()) {
14980   default: llvm_unreachable("illegal opcode!");
14981   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14982   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14983   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14984   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14985   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14986   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14987   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14988   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14989   }
14990
14991   DebugLoc dl = MI->getDebugLoc();
14992   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14993
14994   unsigned NumArgs = MI->getNumOperands(); // remove the results
14995   for (unsigned i = 1; i < NumArgs; ++i) {
14996     MachineOperand &Op = MI->getOperand(i);
14997     if (!(Op.isReg() && Op.isImplicit()))
14998       MIB.addOperand(Op);
14999   }
15000   if (MI->hasOneMemOperand())
15001     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15002
15003   BuildMI(*BB, MI, dl,
15004     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15005     .addReg(X86::ECX);
15006
15007   MI->eraseFromParent();
15008   return BB;
15009 }
15010
15011 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15012                                        const TargetInstrInfo *TII,
15013                                        const X86Subtarget* Subtarget) {
15014   DebugLoc dl = MI->getDebugLoc();
15015
15016   // Address into RAX/EAX, other two args into ECX, EDX.
15017   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15018   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15019   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15020   for (int i = 0; i < X86::AddrNumOperands; ++i)
15021     MIB.addOperand(MI->getOperand(i));
15022
15023   unsigned ValOps = X86::AddrNumOperands;
15024   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15025     .addReg(MI->getOperand(ValOps).getReg());
15026   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15027     .addReg(MI->getOperand(ValOps+1).getReg());
15028
15029   // The instruction doesn't actually take any operands though.
15030   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15031
15032   MI->eraseFromParent(); // The pseudo is gone now.
15033   return BB;
15034 }
15035
15036 MachineBasicBlock *
15037 X86TargetLowering::EmitVAARG64WithCustomInserter(
15038                    MachineInstr *MI,
15039                    MachineBasicBlock *MBB) const {
15040   // Emit va_arg instruction on X86-64.
15041
15042   // Operands to this pseudo-instruction:
15043   // 0  ) Output        : destination address (reg)
15044   // 1-5) Input         : va_list address (addr, i64mem)
15045   // 6  ) ArgSize       : Size (in bytes) of vararg type
15046   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15047   // 8  ) Align         : Alignment of type
15048   // 9  ) EFLAGS (implicit-def)
15049
15050   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15051   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15052
15053   unsigned DestReg = MI->getOperand(0).getReg();
15054   MachineOperand &Base = MI->getOperand(1);
15055   MachineOperand &Scale = MI->getOperand(2);
15056   MachineOperand &Index = MI->getOperand(3);
15057   MachineOperand &Disp = MI->getOperand(4);
15058   MachineOperand &Segment = MI->getOperand(5);
15059   unsigned ArgSize = MI->getOperand(6).getImm();
15060   unsigned ArgMode = MI->getOperand(7).getImm();
15061   unsigned Align = MI->getOperand(8).getImm();
15062
15063   // Memory Reference
15064   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15065   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15066   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15067
15068   // Machine Information
15069   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15070   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15071   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15072   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15073   DebugLoc DL = MI->getDebugLoc();
15074
15075   // struct va_list {
15076   //   i32   gp_offset
15077   //   i32   fp_offset
15078   //   i64   overflow_area (address)
15079   //   i64   reg_save_area (address)
15080   // }
15081   // sizeof(va_list) = 24
15082   // alignment(va_list) = 8
15083
15084   unsigned TotalNumIntRegs = 6;
15085   unsigned TotalNumXMMRegs = 8;
15086   bool UseGPOffset = (ArgMode == 1);
15087   bool UseFPOffset = (ArgMode == 2);
15088   unsigned MaxOffset = TotalNumIntRegs * 8 +
15089                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15090
15091   /* Align ArgSize to a multiple of 8 */
15092   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15093   bool NeedsAlign = (Align > 8);
15094
15095   MachineBasicBlock *thisMBB = MBB;
15096   MachineBasicBlock *overflowMBB;
15097   MachineBasicBlock *offsetMBB;
15098   MachineBasicBlock *endMBB;
15099
15100   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15101   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15102   unsigned OffsetReg = 0;
15103
15104   if (!UseGPOffset && !UseFPOffset) {
15105     // If we only pull from the overflow region, we don't create a branch.
15106     // We don't need to alter control flow.
15107     OffsetDestReg = 0; // unused
15108     OverflowDestReg = DestReg;
15109
15110     offsetMBB = NULL;
15111     overflowMBB = thisMBB;
15112     endMBB = thisMBB;
15113   } else {
15114     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15115     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15116     // If not, pull from overflow_area. (branch to overflowMBB)
15117     //
15118     //       thisMBB
15119     //         |     .
15120     //         |        .
15121     //     offsetMBB   overflowMBB
15122     //         |        .
15123     //         |     .
15124     //        endMBB
15125
15126     // Registers for the PHI in endMBB
15127     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15128     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15129
15130     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15131     MachineFunction *MF = MBB->getParent();
15132     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15133     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15134     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15135
15136     MachineFunction::iterator MBBIter = MBB;
15137     ++MBBIter;
15138
15139     // Insert the new basic blocks
15140     MF->insert(MBBIter, offsetMBB);
15141     MF->insert(MBBIter, overflowMBB);
15142     MF->insert(MBBIter, endMBB);
15143
15144     // Transfer the remainder of MBB and its successor edges to endMBB.
15145     endMBB->splice(endMBB->begin(), thisMBB,
15146                     llvm::next(MachineBasicBlock::iterator(MI)),
15147                     thisMBB->end());
15148     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15149
15150     // Make offsetMBB and overflowMBB successors of thisMBB
15151     thisMBB->addSuccessor(offsetMBB);
15152     thisMBB->addSuccessor(overflowMBB);
15153
15154     // endMBB is a successor of both offsetMBB and overflowMBB
15155     offsetMBB->addSuccessor(endMBB);
15156     overflowMBB->addSuccessor(endMBB);
15157
15158     // Load the offset value into a register
15159     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15160     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15161       .addOperand(Base)
15162       .addOperand(Scale)
15163       .addOperand(Index)
15164       .addDisp(Disp, UseFPOffset ? 4 : 0)
15165       .addOperand(Segment)
15166       .setMemRefs(MMOBegin, MMOEnd);
15167
15168     // Check if there is enough room left to pull this argument.
15169     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15170       .addReg(OffsetReg)
15171       .addImm(MaxOffset + 8 - ArgSizeA8);
15172
15173     // Branch to "overflowMBB" if offset >= max
15174     // Fall through to "offsetMBB" otherwise
15175     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15176       .addMBB(overflowMBB);
15177   }
15178
15179   // In offsetMBB, emit code to use the reg_save_area.
15180   if (offsetMBB) {
15181     assert(OffsetReg != 0);
15182
15183     // Read the reg_save_area address.
15184     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15185     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15186       .addOperand(Base)
15187       .addOperand(Scale)
15188       .addOperand(Index)
15189       .addDisp(Disp, 16)
15190       .addOperand(Segment)
15191       .setMemRefs(MMOBegin, MMOEnd);
15192
15193     // Zero-extend the offset
15194     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15195       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15196         .addImm(0)
15197         .addReg(OffsetReg)
15198         .addImm(X86::sub_32bit);
15199
15200     // Add the offset to the reg_save_area to get the final address.
15201     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15202       .addReg(OffsetReg64)
15203       .addReg(RegSaveReg);
15204
15205     // Compute the offset for the next argument
15206     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15207     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15208       .addReg(OffsetReg)
15209       .addImm(UseFPOffset ? 16 : 8);
15210
15211     // Store it back into the va_list.
15212     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15213       .addOperand(Base)
15214       .addOperand(Scale)
15215       .addOperand(Index)
15216       .addDisp(Disp, UseFPOffset ? 4 : 0)
15217       .addOperand(Segment)
15218       .addReg(NextOffsetReg)
15219       .setMemRefs(MMOBegin, MMOEnd);
15220
15221     // Jump to endMBB
15222     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15223       .addMBB(endMBB);
15224   }
15225
15226   //
15227   // Emit code to use overflow area
15228   //
15229
15230   // Load the overflow_area address into a register.
15231   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15232   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15233     .addOperand(Base)
15234     .addOperand(Scale)
15235     .addOperand(Index)
15236     .addDisp(Disp, 8)
15237     .addOperand(Segment)
15238     .setMemRefs(MMOBegin, MMOEnd);
15239
15240   // If we need to align it, do so. Otherwise, just copy the address
15241   // to OverflowDestReg.
15242   if (NeedsAlign) {
15243     // Align the overflow address
15244     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15245     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15246
15247     // aligned_addr = (addr + (align-1)) & ~(align-1)
15248     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15249       .addReg(OverflowAddrReg)
15250       .addImm(Align-1);
15251
15252     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15253       .addReg(TmpReg)
15254       .addImm(~(uint64_t)(Align-1));
15255   } else {
15256     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15257       .addReg(OverflowAddrReg);
15258   }
15259
15260   // Compute the next overflow address after this argument.
15261   // (the overflow address should be kept 8-byte aligned)
15262   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15263   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15264     .addReg(OverflowDestReg)
15265     .addImm(ArgSizeA8);
15266
15267   // Store the new overflow address.
15268   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15269     .addOperand(Base)
15270     .addOperand(Scale)
15271     .addOperand(Index)
15272     .addDisp(Disp, 8)
15273     .addOperand(Segment)
15274     .addReg(NextAddrReg)
15275     .setMemRefs(MMOBegin, MMOEnd);
15276
15277   // If we branched, emit the PHI to the front of endMBB.
15278   if (offsetMBB) {
15279     BuildMI(*endMBB, endMBB->begin(), DL,
15280             TII->get(X86::PHI), DestReg)
15281       .addReg(OffsetDestReg).addMBB(offsetMBB)
15282       .addReg(OverflowDestReg).addMBB(overflowMBB);
15283   }
15284
15285   // Erase the pseudo instruction
15286   MI->eraseFromParent();
15287
15288   return endMBB;
15289 }
15290
15291 MachineBasicBlock *
15292 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15293                                                  MachineInstr *MI,
15294                                                  MachineBasicBlock *MBB) const {
15295   // Emit code to save XMM registers to the stack. The ABI says that the
15296   // number of registers to save is given in %al, so it's theoretically
15297   // possible to do an indirect jump trick to avoid saving all of them,
15298   // however this code takes a simpler approach and just executes all
15299   // of the stores if %al is non-zero. It's less code, and it's probably
15300   // easier on the hardware branch predictor, and stores aren't all that
15301   // expensive anyway.
15302
15303   // Create the new basic blocks. One block contains all the XMM stores,
15304   // and one block is the final destination regardless of whether any
15305   // stores were performed.
15306   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15307   MachineFunction *F = MBB->getParent();
15308   MachineFunction::iterator MBBIter = MBB;
15309   ++MBBIter;
15310   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15311   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15312   F->insert(MBBIter, XMMSaveMBB);
15313   F->insert(MBBIter, EndMBB);
15314
15315   // Transfer the remainder of MBB and its successor edges to EndMBB.
15316   EndMBB->splice(EndMBB->begin(), MBB,
15317                  llvm::next(MachineBasicBlock::iterator(MI)),
15318                  MBB->end());
15319   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15320
15321   // The original block will now fall through to the XMM save block.
15322   MBB->addSuccessor(XMMSaveMBB);
15323   // The XMMSaveMBB will fall through to the end block.
15324   XMMSaveMBB->addSuccessor(EndMBB);
15325
15326   // Now add the instructions.
15327   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15328   DebugLoc DL = MI->getDebugLoc();
15329
15330   unsigned CountReg = MI->getOperand(0).getReg();
15331   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15332   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15333
15334   if (!Subtarget->isTargetWin64()) {
15335     // If %al is 0, branch around the XMM save block.
15336     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15337     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15338     MBB->addSuccessor(EndMBB);
15339   }
15340
15341   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15342   // In the XMM save block, save all the XMM argument registers.
15343   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
15344     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15345     MachineMemOperand *MMO =
15346       F->getMachineMemOperand(
15347           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15348         MachineMemOperand::MOStore,
15349         /*Size=*/16, /*Align=*/16);
15350     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15351       .addFrameIndex(RegSaveFrameIndex)
15352       .addImm(/*Scale=*/1)
15353       .addReg(/*IndexReg=*/0)
15354       .addImm(/*Disp=*/Offset)
15355       .addReg(/*Segment=*/0)
15356       .addReg(MI->getOperand(i).getReg())
15357       .addMemOperand(MMO);
15358   }
15359
15360   MI->eraseFromParent();   // The pseudo instruction is gone now.
15361
15362   return EndMBB;
15363 }
15364
15365 // The EFLAGS operand of SelectItr might be missing a kill marker
15366 // because there were multiple uses of EFLAGS, and ISel didn't know
15367 // which to mark. Figure out whether SelectItr should have had a
15368 // kill marker, and set it if it should. Returns the correct kill
15369 // marker value.
15370 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15371                                      MachineBasicBlock* BB,
15372                                      const TargetRegisterInfo* TRI) {
15373   // Scan forward through BB for a use/def of EFLAGS.
15374   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
15375   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15376     const MachineInstr& mi = *miI;
15377     if (mi.readsRegister(X86::EFLAGS))
15378       return false;
15379     if (mi.definesRegister(X86::EFLAGS))
15380       break; // Should have kill-flag - update below.
15381   }
15382
15383   // If we hit the end of the block, check whether EFLAGS is live into a
15384   // successor.
15385   if (miI == BB->end()) {
15386     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15387                                           sEnd = BB->succ_end();
15388          sItr != sEnd; ++sItr) {
15389       MachineBasicBlock* succ = *sItr;
15390       if (succ->isLiveIn(X86::EFLAGS))
15391         return false;
15392     }
15393   }
15394
15395   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15396   // out. SelectMI should have a kill flag on EFLAGS.
15397   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15398   return true;
15399 }
15400
15401 MachineBasicBlock *
15402 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15403                                      MachineBasicBlock *BB) const {
15404   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15405   DebugLoc DL = MI->getDebugLoc();
15406
15407   // To "insert" a SELECT_CC instruction, we actually have to insert the
15408   // diamond control-flow pattern.  The incoming instruction knows the
15409   // destination vreg to set, the condition code register to branch on, the
15410   // true/false values to select between, and a branch opcode to use.
15411   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15412   MachineFunction::iterator It = BB;
15413   ++It;
15414
15415   //  thisMBB:
15416   //  ...
15417   //   TrueVal = ...
15418   //   cmpTY ccX, r1, r2
15419   //   bCC copy1MBB
15420   //   fallthrough --> copy0MBB
15421   MachineBasicBlock *thisMBB = BB;
15422   MachineFunction *F = BB->getParent();
15423   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15424   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15425   F->insert(It, copy0MBB);
15426   F->insert(It, sinkMBB);
15427
15428   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15429   // live into the sink and copy blocks.
15430   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15431   if (!MI->killsRegister(X86::EFLAGS) &&
15432       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15433     copy0MBB->addLiveIn(X86::EFLAGS);
15434     sinkMBB->addLiveIn(X86::EFLAGS);
15435   }
15436
15437   // Transfer the remainder of BB and its successor edges to sinkMBB.
15438   sinkMBB->splice(sinkMBB->begin(), BB,
15439                   llvm::next(MachineBasicBlock::iterator(MI)),
15440                   BB->end());
15441   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15442
15443   // Add the true and fallthrough blocks as its successors.
15444   BB->addSuccessor(copy0MBB);
15445   BB->addSuccessor(sinkMBB);
15446
15447   // Create the conditional branch instruction.
15448   unsigned Opc =
15449     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15450   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15451
15452   //  copy0MBB:
15453   //   %FalseValue = ...
15454   //   # fallthrough to sinkMBB
15455   copy0MBB->addSuccessor(sinkMBB);
15456
15457   //  sinkMBB:
15458   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15459   //  ...
15460   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15461           TII->get(X86::PHI), MI->getOperand(0).getReg())
15462     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15463     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15464
15465   MI->eraseFromParent();   // The pseudo instruction is gone now.
15466   return sinkMBB;
15467 }
15468
15469 MachineBasicBlock *
15470 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15471                                         bool Is64Bit) const {
15472   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15473   DebugLoc DL = MI->getDebugLoc();
15474   MachineFunction *MF = BB->getParent();
15475   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15476
15477   assert(getTargetMachine().Options.EnableSegmentedStacks);
15478
15479   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15480   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15481
15482   // BB:
15483   //  ... [Till the alloca]
15484   // If stacklet is not large enough, jump to mallocMBB
15485   //
15486   // bumpMBB:
15487   //  Allocate by subtracting from RSP
15488   //  Jump to continueMBB
15489   //
15490   // mallocMBB:
15491   //  Allocate by call to runtime
15492   //
15493   // continueMBB:
15494   //  ...
15495   //  [rest of original BB]
15496   //
15497
15498   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15499   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15500   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15501
15502   MachineRegisterInfo &MRI = MF->getRegInfo();
15503   const TargetRegisterClass *AddrRegClass =
15504     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15505
15506   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15507     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15508     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15509     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15510     sizeVReg = MI->getOperand(1).getReg(),
15511     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15512
15513   MachineFunction::iterator MBBIter = BB;
15514   ++MBBIter;
15515
15516   MF->insert(MBBIter, bumpMBB);
15517   MF->insert(MBBIter, mallocMBB);
15518   MF->insert(MBBIter, continueMBB);
15519
15520   continueMBB->splice(continueMBB->begin(), BB, llvm::next
15521                       (MachineBasicBlock::iterator(MI)), BB->end());
15522   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15523
15524   // Add code to the main basic block to check if the stack limit has been hit,
15525   // and if so, jump to mallocMBB otherwise to bumpMBB.
15526   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15527   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15528     .addReg(tmpSPVReg).addReg(sizeVReg);
15529   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15530     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15531     .addReg(SPLimitVReg);
15532   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15533
15534   // bumpMBB simply decreases the stack pointer, since we know the current
15535   // stacklet has enough space.
15536   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15537     .addReg(SPLimitVReg);
15538   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15539     .addReg(SPLimitVReg);
15540   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15541
15542   // Calls into a routine in libgcc to allocate more space from the heap.
15543   const uint32_t *RegMask =
15544     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15545   if (Is64Bit) {
15546     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15547       .addReg(sizeVReg);
15548     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15549       .addExternalSymbol("__morestack_allocate_stack_space")
15550       .addRegMask(RegMask)
15551       .addReg(X86::RDI, RegState::Implicit)
15552       .addReg(X86::RAX, RegState::ImplicitDefine);
15553   } else {
15554     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15555       .addImm(12);
15556     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15557     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15558       .addExternalSymbol("__morestack_allocate_stack_space")
15559       .addRegMask(RegMask)
15560       .addReg(X86::EAX, RegState::ImplicitDefine);
15561   }
15562
15563   if (!Is64Bit)
15564     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15565       .addImm(16);
15566
15567   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15568     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15569   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15570
15571   // Set up the CFG correctly.
15572   BB->addSuccessor(bumpMBB);
15573   BB->addSuccessor(mallocMBB);
15574   mallocMBB->addSuccessor(continueMBB);
15575   bumpMBB->addSuccessor(continueMBB);
15576
15577   // Take care of the PHI nodes.
15578   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15579           MI->getOperand(0).getReg())
15580     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15581     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15582
15583   // Delete the original pseudo instruction.
15584   MI->eraseFromParent();
15585
15586   // And we're done.
15587   return continueMBB;
15588 }
15589
15590 MachineBasicBlock *
15591 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15592                                           MachineBasicBlock *BB) const {
15593   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15594   DebugLoc DL = MI->getDebugLoc();
15595
15596   assert(!Subtarget->isTargetMacho());
15597
15598   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15599   // non-trivial part is impdef of ESP.
15600
15601   if (Subtarget->isTargetWin64()) {
15602     if (Subtarget->isTargetCygMing()) {
15603       // ___chkstk(Mingw64):
15604       // Clobbers R10, R11, RAX and EFLAGS.
15605       // Updates RSP.
15606       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15607         .addExternalSymbol("___chkstk")
15608         .addReg(X86::RAX, RegState::Implicit)
15609         .addReg(X86::RSP, RegState::Implicit)
15610         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15611         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15612         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15613     } else {
15614       // __chkstk(MSVCRT): does not update stack pointer.
15615       // Clobbers R10, R11 and EFLAGS.
15616       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15617         .addExternalSymbol("__chkstk")
15618         .addReg(X86::RAX, RegState::Implicit)
15619         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15620       // RAX has the offset to be subtracted from RSP.
15621       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15622         .addReg(X86::RSP)
15623         .addReg(X86::RAX);
15624     }
15625   } else {
15626     const char *StackProbeSymbol =
15627       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15628
15629     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15630       .addExternalSymbol(StackProbeSymbol)
15631       .addReg(X86::EAX, RegState::Implicit)
15632       .addReg(X86::ESP, RegState::Implicit)
15633       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15634       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15635       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15636   }
15637
15638   MI->eraseFromParent();   // The pseudo instruction is gone now.
15639   return BB;
15640 }
15641
15642 MachineBasicBlock *
15643 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15644                                       MachineBasicBlock *BB) const {
15645   // This is pretty easy.  We're taking the value that we received from
15646   // our load from the relocation, sticking it in either RDI (x86-64)
15647   // or EAX and doing an indirect call.  The return value will then
15648   // be in the normal return register.
15649   const X86InstrInfo *TII
15650     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15651   DebugLoc DL = MI->getDebugLoc();
15652   MachineFunction *F = BB->getParent();
15653
15654   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15655   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15656
15657   // Get a register mask for the lowered call.
15658   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15659   // proper register mask.
15660   const uint32_t *RegMask =
15661     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15662   if (Subtarget->is64Bit()) {
15663     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15664                                       TII->get(X86::MOV64rm), X86::RDI)
15665     .addReg(X86::RIP)
15666     .addImm(0).addReg(0)
15667     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15668                       MI->getOperand(3).getTargetFlags())
15669     .addReg(0);
15670     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15671     addDirectMem(MIB, X86::RDI);
15672     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15673   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15674     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15675                                       TII->get(X86::MOV32rm), X86::EAX)
15676     .addReg(0)
15677     .addImm(0).addReg(0)
15678     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15679                       MI->getOperand(3).getTargetFlags())
15680     .addReg(0);
15681     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15682     addDirectMem(MIB, X86::EAX);
15683     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15684   } else {
15685     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15686                                       TII->get(X86::MOV32rm), X86::EAX)
15687     .addReg(TII->getGlobalBaseReg(F))
15688     .addImm(0).addReg(0)
15689     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15690                       MI->getOperand(3).getTargetFlags())
15691     .addReg(0);
15692     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15693     addDirectMem(MIB, X86::EAX);
15694     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15695   }
15696
15697   MI->eraseFromParent(); // The pseudo instruction is gone now.
15698   return BB;
15699 }
15700
15701 MachineBasicBlock *
15702 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15703                                     MachineBasicBlock *MBB) const {
15704   DebugLoc DL = MI->getDebugLoc();
15705   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15706
15707   MachineFunction *MF = MBB->getParent();
15708   MachineRegisterInfo &MRI = MF->getRegInfo();
15709
15710   const BasicBlock *BB = MBB->getBasicBlock();
15711   MachineFunction::iterator I = MBB;
15712   ++I;
15713
15714   // Memory Reference
15715   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15716   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15717
15718   unsigned DstReg;
15719   unsigned MemOpndSlot = 0;
15720
15721   unsigned CurOp = 0;
15722
15723   DstReg = MI->getOperand(CurOp++).getReg();
15724   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15725   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15726   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15727   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15728
15729   MemOpndSlot = CurOp;
15730
15731   MVT PVT = getPointerTy();
15732   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15733          "Invalid Pointer Size!");
15734
15735   // For v = setjmp(buf), we generate
15736   //
15737   // thisMBB:
15738   //  buf[LabelOffset] = restoreMBB
15739   //  SjLjSetup restoreMBB
15740   //
15741   // mainMBB:
15742   //  v_main = 0
15743   //
15744   // sinkMBB:
15745   //  v = phi(main, restore)
15746   //
15747   // restoreMBB:
15748   //  v_restore = 1
15749
15750   MachineBasicBlock *thisMBB = MBB;
15751   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15752   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15753   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15754   MF->insert(I, mainMBB);
15755   MF->insert(I, sinkMBB);
15756   MF->push_back(restoreMBB);
15757
15758   MachineInstrBuilder MIB;
15759
15760   // Transfer the remainder of BB and its successor edges to sinkMBB.
15761   sinkMBB->splice(sinkMBB->begin(), MBB,
15762                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15763   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15764
15765   // thisMBB:
15766   unsigned PtrStoreOpc = 0;
15767   unsigned LabelReg = 0;
15768   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15769   Reloc::Model RM = getTargetMachine().getRelocationModel();
15770   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15771                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15772
15773   // Prepare IP either in reg or imm.
15774   if (!UseImmLabel) {
15775     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15776     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15777     LabelReg = MRI.createVirtualRegister(PtrRC);
15778     if (Subtarget->is64Bit()) {
15779       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15780               .addReg(X86::RIP)
15781               .addImm(0)
15782               .addReg(0)
15783               .addMBB(restoreMBB)
15784               .addReg(0);
15785     } else {
15786       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15787       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15788               .addReg(XII->getGlobalBaseReg(MF))
15789               .addImm(0)
15790               .addReg(0)
15791               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15792               .addReg(0);
15793     }
15794   } else
15795     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15796   // Store IP
15797   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15798   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15799     if (i == X86::AddrDisp)
15800       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15801     else
15802       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15803   }
15804   if (!UseImmLabel)
15805     MIB.addReg(LabelReg);
15806   else
15807     MIB.addMBB(restoreMBB);
15808   MIB.setMemRefs(MMOBegin, MMOEnd);
15809   // Setup
15810   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15811           .addMBB(restoreMBB);
15812
15813   const X86RegisterInfo *RegInfo =
15814     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15815   MIB.addRegMask(RegInfo->getNoPreservedMask());
15816   thisMBB->addSuccessor(mainMBB);
15817   thisMBB->addSuccessor(restoreMBB);
15818
15819   // mainMBB:
15820   //  EAX = 0
15821   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15822   mainMBB->addSuccessor(sinkMBB);
15823
15824   // sinkMBB:
15825   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15826           TII->get(X86::PHI), DstReg)
15827     .addReg(mainDstReg).addMBB(mainMBB)
15828     .addReg(restoreDstReg).addMBB(restoreMBB);
15829
15830   // restoreMBB:
15831   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15832   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15833   restoreMBB->addSuccessor(sinkMBB);
15834
15835   MI->eraseFromParent();
15836   return sinkMBB;
15837 }
15838
15839 MachineBasicBlock *
15840 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15841                                      MachineBasicBlock *MBB) const {
15842   DebugLoc DL = MI->getDebugLoc();
15843   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15844
15845   MachineFunction *MF = MBB->getParent();
15846   MachineRegisterInfo &MRI = MF->getRegInfo();
15847
15848   // Memory Reference
15849   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15850   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15851
15852   MVT PVT = getPointerTy();
15853   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15854          "Invalid Pointer Size!");
15855
15856   const TargetRegisterClass *RC =
15857     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15858   unsigned Tmp = MRI.createVirtualRegister(RC);
15859   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15860   const X86RegisterInfo *RegInfo =
15861     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15862   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15863   unsigned SP = RegInfo->getStackRegister();
15864
15865   MachineInstrBuilder MIB;
15866
15867   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15868   const int64_t SPOffset = 2 * PVT.getStoreSize();
15869
15870   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15871   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15872
15873   // Reload FP
15874   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15875   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15876     MIB.addOperand(MI->getOperand(i));
15877   MIB.setMemRefs(MMOBegin, MMOEnd);
15878   // Reload IP
15879   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15880   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15881     if (i == X86::AddrDisp)
15882       MIB.addDisp(MI->getOperand(i), LabelOffset);
15883     else
15884       MIB.addOperand(MI->getOperand(i));
15885   }
15886   MIB.setMemRefs(MMOBegin, MMOEnd);
15887   // Reload SP
15888   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15889   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15890     if (i == X86::AddrDisp)
15891       MIB.addDisp(MI->getOperand(i), SPOffset);
15892     else
15893       MIB.addOperand(MI->getOperand(i));
15894   }
15895   MIB.setMemRefs(MMOBegin, MMOEnd);
15896   // Jump
15897   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15898
15899   MI->eraseFromParent();
15900   return MBB;
15901 }
15902
15903 MachineBasicBlock *
15904 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15905                                                MachineBasicBlock *BB) const {
15906   switch (MI->getOpcode()) {
15907   default: llvm_unreachable("Unexpected instr type to insert");
15908   case X86::TAILJMPd64:
15909   case X86::TAILJMPr64:
15910   case X86::TAILJMPm64:
15911     llvm_unreachable("TAILJMP64 would not be touched here.");
15912   case X86::TCRETURNdi64:
15913   case X86::TCRETURNri64:
15914   case X86::TCRETURNmi64:
15915     return BB;
15916   case X86::WIN_ALLOCA:
15917     return EmitLoweredWinAlloca(MI, BB);
15918   case X86::SEG_ALLOCA_32:
15919     return EmitLoweredSegAlloca(MI, BB, false);
15920   case X86::SEG_ALLOCA_64:
15921     return EmitLoweredSegAlloca(MI, BB, true);
15922   case X86::TLSCall_32:
15923   case X86::TLSCall_64:
15924     return EmitLoweredTLSCall(MI, BB);
15925   case X86::CMOV_GR8:
15926   case X86::CMOV_FR32:
15927   case X86::CMOV_FR64:
15928   case X86::CMOV_V4F32:
15929   case X86::CMOV_V2F64:
15930   case X86::CMOV_V2I64:
15931   case X86::CMOV_V8F32:
15932   case X86::CMOV_V4F64:
15933   case X86::CMOV_V4I64:
15934   case X86::CMOV_V16F32:
15935   case X86::CMOV_V8F64:
15936   case X86::CMOV_V8I64:
15937   case X86::CMOV_GR16:
15938   case X86::CMOV_GR32:
15939   case X86::CMOV_RFP32:
15940   case X86::CMOV_RFP64:
15941   case X86::CMOV_RFP80:
15942     return EmitLoweredSelect(MI, BB);
15943
15944   case X86::FP32_TO_INT16_IN_MEM:
15945   case X86::FP32_TO_INT32_IN_MEM:
15946   case X86::FP32_TO_INT64_IN_MEM:
15947   case X86::FP64_TO_INT16_IN_MEM:
15948   case X86::FP64_TO_INT32_IN_MEM:
15949   case X86::FP64_TO_INT64_IN_MEM:
15950   case X86::FP80_TO_INT16_IN_MEM:
15951   case X86::FP80_TO_INT32_IN_MEM:
15952   case X86::FP80_TO_INT64_IN_MEM: {
15953     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15954     DebugLoc DL = MI->getDebugLoc();
15955
15956     // Change the floating point control register to use "round towards zero"
15957     // mode when truncating to an integer value.
15958     MachineFunction *F = BB->getParent();
15959     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15960     addFrameReference(BuildMI(*BB, MI, DL,
15961                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15962
15963     // Load the old value of the high byte of the control word...
15964     unsigned OldCW =
15965       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15966     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15967                       CWFrameIdx);
15968
15969     // Set the high part to be round to zero...
15970     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15971       .addImm(0xC7F);
15972
15973     // Reload the modified control word now...
15974     addFrameReference(BuildMI(*BB, MI, DL,
15975                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15976
15977     // Restore the memory image of control word to original value
15978     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15979       .addReg(OldCW);
15980
15981     // Get the X86 opcode to use.
15982     unsigned Opc;
15983     switch (MI->getOpcode()) {
15984     default: llvm_unreachable("illegal opcode!");
15985     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15986     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15987     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15988     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15989     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15990     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15991     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15992     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15993     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15994     }
15995
15996     X86AddressMode AM;
15997     MachineOperand &Op = MI->getOperand(0);
15998     if (Op.isReg()) {
15999       AM.BaseType = X86AddressMode::RegBase;
16000       AM.Base.Reg = Op.getReg();
16001     } else {
16002       AM.BaseType = X86AddressMode::FrameIndexBase;
16003       AM.Base.FrameIndex = Op.getIndex();
16004     }
16005     Op = MI->getOperand(1);
16006     if (Op.isImm())
16007       AM.Scale = Op.getImm();
16008     Op = MI->getOperand(2);
16009     if (Op.isImm())
16010       AM.IndexReg = Op.getImm();
16011     Op = MI->getOperand(3);
16012     if (Op.isGlobal()) {
16013       AM.GV = Op.getGlobal();
16014     } else {
16015       AM.Disp = Op.getImm();
16016     }
16017     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16018                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16019
16020     // Reload the original control word now.
16021     addFrameReference(BuildMI(*BB, MI, DL,
16022                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16023
16024     MI->eraseFromParent();   // The pseudo instruction is gone now.
16025     return BB;
16026   }
16027     // String/text processing lowering.
16028   case X86::PCMPISTRM128REG:
16029   case X86::VPCMPISTRM128REG:
16030   case X86::PCMPISTRM128MEM:
16031   case X86::VPCMPISTRM128MEM:
16032   case X86::PCMPESTRM128REG:
16033   case X86::VPCMPESTRM128REG:
16034   case X86::PCMPESTRM128MEM:
16035   case X86::VPCMPESTRM128MEM:
16036     assert(Subtarget->hasSSE42() &&
16037            "Target must have SSE4.2 or AVX features enabled");
16038     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16039
16040   // String/text processing lowering.
16041   case X86::PCMPISTRIREG:
16042   case X86::VPCMPISTRIREG:
16043   case X86::PCMPISTRIMEM:
16044   case X86::VPCMPISTRIMEM:
16045   case X86::PCMPESTRIREG:
16046   case X86::VPCMPESTRIREG:
16047   case X86::PCMPESTRIMEM:
16048   case X86::VPCMPESTRIMEM:
16049     assert(Subtarget->hasSSE42() &&
16050            "Target must have SSE4.2 or AVX features enabled");
16051     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16052
16053   // Thread synchronization.
16054   case X86::MONITOR:
16055     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16056
16057   // xbegin
16058   case X86::XBEGIN:
16059     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16060
16061   // Atomic Lowering.
16062   case X86::ATOMAND8:
16063   case X86::ATOMAND16:
16064   case X86::ATOMAND32:
16065   case X86::ATOMAND64:
16066     // Fall through
16067   case X86::ATOMOR8:
16068   case X86::ATOMOR16:
16069   case X86::ATOMOR32:
16070   case X86::ATOMOR64:
16071     // Fall through
16072   case X86::ATOMXOR16:
16073   case X86::ATOMXOR8:
16074   case X86::ATOMXOR32:
16075   case X86::ATOMXOR64:
16076     // Fall through
16077   case X86::ATOMNAND8:
16078   case X86::ATOMNAND16:
16079   case X86::ATOMNAND32:
16080   case X86::ATOMNAND64:
16081     // Fall through
16082   case X86::ATOMMAX8:
16083   case X86::ATOMMAX16:
16084   case X86::ATOMMAX32:
16085   case X86::ATOMMAX64:
16086     // Fall through
16087   case X86::ATOMMIN8:
16088   case X86::ATOMMIN16:
16089   case X86::ATOMMIN32:
16090   case X86::ATOMMIN64:
16091     // Fall through
16092   case X86::ATOMUMAX8:
16093   case X86::ATOMUMAX16:
16094   case X86::ATOMUMAX32:
16095   case X86::ATOMUMAX64:
16096     // Fall through
16097   case X86::ATOMUMIN8:
16098   case X86::ATOMUMIN16:
16099   case X86::ATOMUMIN32:
16100   case X86::ATOMUMIN64:
16101     return EmitAtomicLoadArith(MI, BB);
16102
16103   // This group does 64-bit operations on a 32-bit host.
16104   case X86::ATOMAND6432:
16105   case X86::ATOMOR6432:
16106   case X86::ATOMXOR6432:
16107   case X86::ATOMNAND6432:
16108   case X86::ATOMADD6432:
16109   case X86::ATOMSUB6432:
16110   case X86::ATOMMAX6432:
16111   case X86::ATOMMIN6432:
16112   case X86::ATOMUMAX6432:
16113   case X86::ATOMUMIN6432:
16114   case X86::ATOMSWAP6432:
16115     return EmitAtomicLoadArith6432(MI, BB);
16116
16117   case X86::VASTART_SAVE_XMM_REGS:
16118     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16119
16120   case X86::VAARG_64:
16121     return EmitVAARG64WithCustomInserter(MI, BB);
16122
16123   case X86::EH_SjLj_SetJmp32:
16124   case X86::EH_SjLj_SetJmp64:
16125     return emitEHSjLjSetJmp(MI, BB);
16126
16127   case X86::EH_SjLj_LongJmp32:
16128   case X86::EH_SjLj_LongJmp64:
16129     return emitEHSjLjLongJmp(MI, BB);
16130
16131   case TargetOpcode::STACKMAP:
16132   case TargetOpcode::PATCHPOINT:
16133     return emitPatchPoint(MI, BB);
16134   }
16135 }
16136
16137 //===----------------------------------------------------------------------===//
16138 //                           X86 Optimization Hooks
16139 //===----------------------------------------------------------------------===//
16140
16141 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16142                                                        APInt &KnownZero,
16143                                                        APInt &KnownOne,
16144                                                        const SelectionDAG &DAG,
16145                                                        unsigned Depth) const {
16146   unsigned BitWidth = KnownZero.getBitWidth();
16147   unsigned Opc = Op.getOpcode();
16148   assert((Opc >= ISD::BUILTIN_OP_END ||
16149           Opc == ISD::INTRINSIC_WO_CHAIN ||
16150           Opc == ISD::INTRINSIC_W_CHAIN ||
16151           Opc == ISD::INTRINSIC_VOID) &&
16152          "Should use MaskedValueIsZero if you don't know whether Op"
16153          " is a target node!");
16154
16155   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16156   switch (Opc) {
16157   default: break;
16158   case X86ISD::ADD:
16159   case X86ISD::SUB:
16160   case X86ISD::ADC:
16161   case X86ISD::SBB:
16162   case X86ISD::SMUL:
16163   case X86ISD::UMUL:
16164   case X86ISD::INC:
16165   case X86ISD::DEC:
16166   case X86ISD::OR:
16167   case X86ISD::XOR:
16168   case X86ISD::AND:
16169     // These nodes' second result is a boolean.
16170     if (Op.getResNo() == 0)
16171       break;
16172     // Fallthrough
16173   case X86ISD::SETCC:
16174     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16175     break;
16176   case ISD::INTRINSIC_WO_CHAIN: {
16177     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16178     unsigned NumLoBits = 0;
16179     switch (IntId) {
16180     default: break;
16181     case Intrinsic::x86_sse_movmsk_ps:
16182     case Intrinsic::x86_avx_movmsk_ps_256:
16183     case Intrinsic::x86_sse2_movmsk_pd:
16184     case Intrinsic::x86_avx_movmsk_pd_256:
16185     case Intrinsic::x86_mmx_pmovmskb:
16186     case Intrinsic::x86_sse2_pmovmskb_128:
16187     case Intrinsic::x86_avx2_pmovmskb: {
16188       // High bits of movmskp{s|d}, pmovmskb are known zero.
16189       switch (IntId) {
16190         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16191         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16192         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16193         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16194         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16195         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16196         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16197         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16198       }
16199       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16200       break;
16201     }
16202     }
16203     break;
16204   }
16205   }
16206 }
16207
16208 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16209                                                          unsigned Depth) const {
16210   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16211   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16212     return Op.getValueType().getScalarType().getSizeInBits();
16213
16214   // Fallback case.
16215   return 1;
16216 }
16217
16218 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16219 /// node is a GlobalAddress + offset.
16220 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16221                                        const GlobalValue* &GA,
16222                                        int64_t &Offset) const {
16223   if (N->getOpcode() == X86ISD::Wrapper) {
16224     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16225       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16226       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16227       return true;
16228     }
16229   }
16230   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16231 }
16232
16233 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16234 /// same as extracting the high 128-bit part of 256-bit vector and then
16235 /// inserting the result into the low part of a new 256-bit vector
16236 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16237   EVT VT = SVOp->getValueType(0);
16238   unsigned NumElems = VT.getVectorNumElements();
16239
16240   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16241   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16242     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16243         SVOp->getMaskElt(j) >= 0)
16244       return false;
16245
16246   return true;
16247 }
16248
16249 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16250 /// same as extracting the low 128-bit part of 256-bit vector and then
16251 /// inserting the result into the high part of a new 256-bit vector
16252 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16253   EVT VT = SVOp->getValueType(0);
16254   unsigned NumElems = VT.getVectorNumElements();
16255
16256   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16257   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16258     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16259         SVOp->getMaskElt(j) >= 0)
16260       return false;
16261
16262   return true;
16263 }
16264
16265 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16266 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16267                                         TargetLowering::DAGCombinerInfo &DCI,
16268                                         const X86Subtarget* Subtarget) {
16269   SDLoc dl(N);
16270   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16271   SDValue V1 = SVOp->getOperand(0);
16272   SDValue V2 = SVOp->getOperand(1);
16273   EVT VT = SVOp->getValueType(0);
16274   unsigned NumElems = VT.getVectorNumElements();
16275
16276   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16277       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16278     //
16279     //                   0,0,0,...
16280     //                      |
16281     //    V      UNDEF    BUILD_VECTOR    UNDEF
16282     //     \      /           \           /
16283     //  CONCAT_VECTOR         CONCAT_VECTOR
16284     //         \                  /
16285     //          \                /
16286     //          RESULT: V + zero extended
16287     //
16288     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16289         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16290         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16291       return SDValue();
16292
16293     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16294       return SDValue();
16295
16296     // To match the shuffle mask, the first half of the mask should
16297     // be exactly the first vector, and all the rest a splat with the
16298     // first element of the second one.
16299     for (unsigned i = 0; i != NumElems/2; ++i)
16300       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16301           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16302         return SDValue();
16303
16304     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16305     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16306       if (Ld->hasNUsesOfValue(1, 0)) {
16307         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16308         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16309         SDValue ResNode =
16310           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16311                                   array_lengthof(Ops),
16312                                   Ld->getMemoryVT(),
16313                                   Ld->getPointerInfo(),
16314                                   Ld->getAlignment(),
16315                                   false/*isVolatile*/, true/*ReadMem*/,
16316                                   false/*WriteMem*/);
16317
16318         // Make sure the newly-created LOAD is in the same position as Ld in
16319         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16320         // and update uses of Ld's output chain to use the TokenFactor.
16321         if (Ld->hasAnyUseOfValue(1)) {
16322           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16323                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16324           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16325           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16326                                  SDValue(ResNode.getNode(), 1));
16327         }
16328
16329         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16330       }
16331     }
16332
16333     // Emit a zeroed vector and insert the desired subvector on its
16334     // first half.
16335     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16336     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16337     return DCI.CombineTo(N, InsV);
16338   }
16339
16340   //===--------------------------------------------------------------------===//
16341   // Combine some shuffles into subvector extracts and inserts:
16342   //
16343
16344   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16345   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16346     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16347     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16348     return DCI.CombineTo(N, InsV);
16349   }
16350
16351   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16352   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16353     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16354     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16355     return DCI.CombineTo(N, InsV);
16356   }
16357
16358   return SDValue();
16359 }
16360
16361 /// PerformShuffleCombine - Performs several different shuffle combines.
16362 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16363                                      TargetLowering::DAGCombinerInfo &DCI,
16364                                      const X86Subtarget *Subtarget) {
16365   SDLoc dl(N);
16366   EVT VT = N->getValueType(0);
16367
16368   // Don't create instructions with illegal types after legalize types has run.
16369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16370   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16371     return SDValue();
16372
16373   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16374   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16375       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16376     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16377
16378   // Only handle 128 wide vector from here on.
16379   if (!VT.is128BitVector())
16380     return SDValue();
16381
16382   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16383   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16384   // consecutive, non-overlapping, and in the right order.
16385   SmallVector<SDValue, 16> Elts;
16386   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16387     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16388
16389   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16390 }
16391
16392 /// PerformTruncateCombine - Converts truncate operation to
16393 /// a sequence of vector shuffle operations.
16394 /// It is possible when we truncate 256-bit vector to 128-bit vector
16395 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16396                                       TargetLowering::DAGCombinerInfo &DCI,
16397                                       const X86Subtarget *Subtarget)  {
16398   return SDValue();
16399 }
16400
16401 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16402 /// specific shuffle of a load can be folded into a single element load.
16403 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16404 /// shuffles have been customed lowered so we need to handle those here.
16405 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16406                                          TargetLowering::DAGCombinerInfo &DCI) {
16407   if (DCI.isBeforeLegalizeOps())
16408     return SDValue();
16409
16410   SDValue InVec = N->getOperand(0);
16411   SDValue EltNo = N->getOperand(1);
16412
16413   if (!isa<ConstantSDNode>(EltNo))
16414     return SDValue();
16415
16416   EVT VT = InVec.getValueType();
16417
16418   bool HasShuffleIntoBitcast = false;
16419   if (InVec.getOpcode() == ISD::BITCAST) {
16420     // Don't duplicate a load with other uses.
16421     if (!InVec.hasOneUse())
16422       return SDValue();
16423     EVT BCVT = InVec.getOperand(0).getValueType();
16424     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16425       return SDValue();
16426     InVec = InVec.getOperand(0);
16427     HasShuffleIntoBitcast = true;
16428   }
16429
16430   if (!isTargetShuffle(InVec.getOpcode()))
16431     return SDValue();
16432
16433   // Don't duplicate a load with other uses.
16434   if (!InVec.hasOneUse())
16435     return SDValue();
16436
16437   SmallVector<int, 16> ShuffleMask;
16438   bool UnaryShuffle;
16439   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16440                             UnaryShuffle))
16441     return SDValue();
16442
16443   // Select the input vector, guarding against out of range extract vector.
16444   unsigned NumElems = VT.getVectorNumElements();
16445   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16446   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16447   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16448                                          : InVec.getOperand(1);
16449
16450   // If inputs to shuffle are the same for both ops, then allow 2 uses
16451   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16452
16453   if (LdNode.getOpcode() == ISD::BITCAST) {
16454     // Don't duplicate a load with other uses.
16455     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16456       return SDValue();
16457
16458     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16459     LdNode = LdNode.getOperand(0);
16460   }
16461
16462   if (!ISD::isNormalLoad(LdNode.getNode()))
16463     return SDValue();
16464
16465   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16466
16467   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16468     return SDValue();
16469
16470   if (HasShuffleIntoBitcast) {
16471     // If there's a bitcast before the shuffle, check if the load type and
16472     // alignment is valid.
16473     unsigned Align = LN0->getAlignment();
16474     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16475     unsigned NewAlign = TLI.getDataLayout()->
16476       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16477
16478     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16479       return SDValue();
16480   }
16481
16482   // All checks match so transform back to vector_shuffle so that DAG combiner
16483   // can finish the job
16484   SDLoc dl(N);
16485
16486   // Create shuffle node taking into account the case that its a unary shuffle
16487   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16488   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16489                                  InVec.getOperand(0), Shuffle,
16490                                  &ShuffleMask[0]);
16491   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16492   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16493                      EltNo);
16494 }
16495
16496 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16497 /// generation and convert it from being a bunch of shuffles and extracts
16498 /// to a simple store and scalar loads to extract the elements.
16499 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16500                                          TargetLowering::DAGCombinerInfo &DCI) {
16501   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16502   if (NewOp.getNode())
16503     return NewOp;
16504
16505   SDValue InputVector = N->getOperand(0);
16506
16507   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16508   // from mmx to v2i32 has a single usage.
16509   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16510       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16511       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16512     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16513                        N->getValueType(0),
16514                        InputVector.getNode()->getOperand(0));
16515
16516   // Only operate on vectors of 4 elements, where the alternative shuffling
16517   // gets to be more expensive.
16518   if (InputVector.getValueType() != MVT::v4i32)
16519     return SDValue();
16520
16521   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16522   // single use which is a sign-extend or zero-extend, and all elements are
16523   // used.
16524   SmallVector<SDNode *, 4> Uses;
16525   unsigned ExtractedElements = 0;
16526   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16527        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16528     if (UI.getUse().getResNo() != InputVector.getResNo())
16529       return SDValue();
16530
16531     SDNode *Extract = *UI;
16532     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16533       return SDValue();
16534
16535     if (Extract->getValueType(0) != MVT::i32)
16536       return SDValue();
16537     if (!Extract->hasOneUse())
16538       return SDValue();
16539     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16540         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16541       return SDValue();
16542     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16543       return SDValue();
16544
16545     // Record which element was extracted.
16546     ExtractedElements |=
16547       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16548
16549     Uses.push_back(Extract);
16550   }
16551
16552   // If not all the elements were used, this may not be worthwhile.
16553   if (ExtractedElements != 15)
16554     return SDValue();
16555
16556   // Ok, we've now decided to do the transformation.
16557   SDLoc dl(InputVector);
16558
16559   // Store the value to a temporary stack slot.
16560   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16561   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16562                             MachinePointerInfo(), false, false, 0);
16563
16564   // Replace each use (extract) with a load of the appropriate element.
16565   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16566        UE = Uses.end(); UI != UE; ++UI) {
16567     SDNode *Extract = *UI;
16568
16569     // cOMpute the element's address.
16570     SDValue Idx = Extract->getOperand(1);
16571     unsigned EltSize =
16572         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16573     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16574     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16575     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16576
16577     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16578                                      StackPtr, OffsetVal);
16579
16580     // Load the scalar.
16581     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16582                                      ScalarAddr, MachinePointerInfo(),
16583                                      false, false, false, 0);
16584
16585     // Replace the exact with the load.
16586     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16587   }
16588
16589   // The replacement was made in place; don't return anything.
16590   return SDValue();
16591 }
16592
16593 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16594 static std::pair<unsigned, bool>
16595 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16596                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16597   if (!VT.isVector())
16598     return std::make_pair(0, false);
16599
16600   bool NeedSplit = false;
16601   switch (VT.getSimpleVT().SimpleTy) {
16602   default: return std::make_pair(0, false);
16603   case MVT::v32i8:
16604   case MVT::v16i16:
16605   case MVT::v8i32:
16606     if (!Subtarget->hasAVX2())
16607       NeedSplit = true;
16608     if (!Subtarget->hasAVX())
16609       return std::make_pair(0, false);
16610     break;
16611   case MVT::v16i8:
16612   case MVT::v8i16:
16613   case MVT::v4i32:
16614     if (!Subtarget->hasSSE2())
16615       return std::make_pair(0, false);
16616   }
16617
16618   // SSE2 has only a small subset of the operations.
16619   bool hasUnsigned = Subtarget->hasSSE41() ||
16620                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16621   bool hasSigned = Subtarget->hasSSE41() ||
16622                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16623
16624   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16625
16626   unsigned Opc = 0;
16627   // Check for x CC y ? x : y.
16628   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16629       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16630     switch (CC) {
16631     default: break;
16632     case ISD::SETULT:
16633     case ISD::SETULE:
16634       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16635     case ISD::SETUGT:
16636     case ISD::SETUGE:
16637       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16638     case ISD::SETLT:
16639     case ISD::SETLE:
16640       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16641     case ISD::SETGT:
16642     case ISD::SETGE:
16643       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16644     }
16645   // Check for x CC y ? y : x -- a min/max with reversed arms.
16646   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16647              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16648     switch (CC) {
16649     default: break;
16650     case ISD::SETULT:
16651     case ISD::SETULE:
16652       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16653     case ISD::SETUGT:
16654     case ISD::SETUGE:
16655       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16656     case ISD::SETLT:
16657     case ISD::SETLE:
16658       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16659     case ISD::SETGT:
16660     case ISD::SETGE:
16661       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16662     }
16663   }
16664
16665   return std::make_pair(Opc, NeedSplit);
16666 }
16667
16668 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16669 /// nodes.
16670 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16671                                     TargetLowering::DAGCombinerInfo &DCI,
16672                                     const X86Subtarget *Subtarget) {
16673   SDLoc DL(N);
16674   SDValue Cond = N->getOperand(0);
16675   // Get the LHS/RHS of the select.
16676   SDValue LHS = N->getOperand(1);
16677   SDValue RHS = N->getOperand(2);
16678   EVT VT = LHS.getValueType();
16679   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16680
16681   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16682   // instructions match the semantics of the common C idiom x<y?x:y but not
16683   // x<=y?x:y, because of how they handle negative zero (which can be
16684   // ignored in unsafe-math mode).
16685   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16686       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
16687       (Subtarget->hasSSE2() ||
16688        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16689     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16690
16691     unsigned Opcode = 0;
16692     // Check for x CC y ? x : y.
16693     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16694         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16695       switch (CC) {
16696       default: break;
16697       case ISD::SETULT:
16698         // Converting this to a min would handle NaNs incorrectly, and swapping
16699         // the operands would cause it to handle comparisons between positive
16700         // and negative zero incorrectly.
16701         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16702           if (!DAG.getTarget().Options.UnsafeFPMath &&
16703               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16704             break;
16705           std::swap(LHS, RHS);
16706         }
16707         Opcode = X86ISD::FMIN;
16708         break;
16709       case ISD::SETOLE:
16710         // Converting this to a min would handle comparisons between positive
16711         // and negative zero incorrectly.
16712         if (!DAG.getTarget().Options.UnsafeFPMath &&
16713             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16714           break;
16715         Opcode = X86ISD::FMIN;
16716         break;
16717       case ISD::SETULE:
16718         // Converting this to a min would handle both negative zeros and NaNs
16719         // incorrectly, but we can swap the operands to fix both.
16720         std::swap(LHS, RHS);
16721       case ISD::SETOLT:
16722       case ISD::SETLT:
16723       case ISD::SETLE:
16724         Opcode = X86ISD::FMIN;
16725         break;
16726
16727       case ISD::SETOGE:
16728         // Converting this to a max would handle comparisons between positive
16729         // and negative zero incorrectly.
16730         if (!DAG.getTarget().Options.UnsafeFPMath &&
16731             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16732           break;
16733         Opcode = X86ISD::FMAX;
16734         break;
16735       case ISD::SETUGT:
16736         // Converting this to a max would handle NaNs incorrectly, and swapping
16737         // the operands would cause it to handle comparisons between positive
16738         // and negative zero incorrectly.
16739         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16740           if (!DAG.getTarget().Options.UnsafeFPMath &&
16741               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16742             break;
16743           std::swap(LHS, RHS);
16744         }
16745         Opcode = X86ISD::FMAX;
16746         break;
16747       case ISD::SETUGE:
16748         // Converting this to a max would handle both negative zeros and NaNs
16749         // incorrectly, but we can swap the operands to fix both.
16750         std::swap(LHS, RHS);
16751       case ISD::SETOGT:
16752       case ISD::SETGT:
16753       case ISD::SETGE:
16754         Opcode = X86ISD::FMAX;
16755         break;
16756       }
16757     // Check for x CC y ? y : x -- a min/max with reversed arms.
16758     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16759                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16760       switch (CC) {
16761       default: break;
16762       case ISD::SETOGE:
16763         // Converting this to a min would handle comparisons between positive
16764         // and negative zero incorrectly, and swapping the operands would
16765         // cause it to handle NaNs incorrectly.
16766         if (!DAG.getTarget().Options.UnsafeFPMath &&
16767             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16768           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16769             break;
16770           std::swap(LHS, RHS);
16771         }
16772         Opcode = X86ISD::FMIN;
16773         break;
16774       case ISD::SETUGT:
16775         // Converting this to a min would handle NaNs incorrectly.
16776         if (!DAG.getTarget().Options.UnsafeFPMath &&
16777             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16778           break;
16779         Opcode = X86ISD::FMIN;
16780         break;
16781       case ISD::SETUGE:
16782         // Converting this to a min would handle both negative zeros and NaNs
16783         // incorrectly, but we can swap the operands to fix both.
16784         std::swap(LHS, RHS);
16785       case ISD::SETOGT:
16786       case ISD::SETGT:
16787       case ISD::SETGE:
16788         Opcode = X86ISD::FMIN;
16789         break;
16790
16791       case ISD::SETULT:
16792         // Converting this to a max would handle NaNs incorrectly.
16793         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16794           break;
16795         Opcode = X86ISD::FMAX;
16796         break;
16797       case ISD::SETOLE:
16798         // Converting this to a max would handle comparisons between positive
16799         // and negative zero incorrectly, and swapping the operands would
16800         // cause it to handle NaNs incorrectly.
16801         if (!DAG.getTarget().Options.UnsafeFPMath &&
16802             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16803           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16804             break;
16805           std::swap(LHS, RHS);
16806         }
16807         Opcode = X86ISD::FMAX;
16808         break;
16809       case ISD::SETULE:
16810         // Converting this to a max would handle both negative zeros and NaNs
16811         // incorrectly, but we can swap the operands to fix both.
16812         std::swap(LHS, RHS);
16813       case ISD::SETOLT:
16814       case ISD::SETLT:
16815       case ISD::SETLE:
16816         Opcode = X86ISD::FMAX;
16817         break;
16818       }
16819     }
16820
16821     if (Opcode)
16822       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16823   }
16824
16825   EVT CondVT = Cond.getValueType();
16826   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
16827       CondVT.getVectorElementType() == MVT::i1) {
16828     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
16829     // lowering on AVX-512. In this case we convert it to
16830     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
16831     // The same situation for all 128 and 256-bit vectors of i8 and i16
16832     EVT OpVT = LHS.getValueType();
16833     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
16834         (OpVT.getVectorElementType() == MVT::i8 ||
16835          OpVT.getVectorElementType() == MVT::i16)) {
16836       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
16837       DCI.AddToWorklist(Cond.getNode());
16838       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
16839     }
16840   }
16841   // If this is a select between two integer constants, try to do some
16842   // optimizations.
16843   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16844     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16845       // Don't do this for crazy integer types.
16846       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16847         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16848         // so that TrueC (the true value) is larger than FalseC.
16849         bool NeedsCondInvert = false;
16850
16851         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16852             // Efficiently invertible.
16853             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16854              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16855               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16856           NeedsCondInvert = true;
16857           std::swap(TrueC, FalseC);
16858         }
16859
16860         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16861         if (FalseC->getAPIntValue() == 0 &&
16862             TrueC->getAPIntValue().isPowerOf2()) {
16863           if (NeedsCondInvert) // Invert the condition if needed.
16864             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16865                                DAG.getConstant(1, Cond.getValueType()));
16866
16867           // Zero extend the condition if needed.
16868           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16869
16870           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16871           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16872                              DAG.getConstant(ShAmt, MVT::i8));
16873         }
16874
16875         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16876         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16877           if (NeedsCondInvert) // Invert the condition if needed.
16878             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16879                                DAG.getConstant(1, Cond.getValueType()));
16880
16881           // Zero extend the condition if needed.
16882           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16883                              FalseC->getValueType(0), Cond);
16884           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16885                              SDValue(FalseC, 0));
16886         }
16887
16888         // Optimize cases that will turn into an LEA instruction.  This requires
16889         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16890         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16891           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16892           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16893
16894           bool isFastMultiplier = false;
16895           if (Diff < 10) {
16896             switch ((unsigned char)Diff) {
16897               default: break;
16898               case 1:  // result = add base, cond
16899               case 2:  // result = lea base(    , cond*2)
16900               case 3:  // result = lea base(cond, cond*2)
16901               case 4:  // result = lea base(    , cond*4)
16902               case 5:  // result = lea base(cond, cond*4)
16903               case 8:  // result = lea base(    , cond*8)
16904               case 9:  // result = lea base(cond, cond*8)
16905                 isFastMultiplier = true;
16906                 break;
16907             }
16908           }
16909
16910           if (isFastMultiplier) {
16911             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16912             if (NeedsCondInvert) // Invert the condition if needed.
16913               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16914                                  DAG.getConstant(1, Cond.getValueType()));
16915
16916             // Zero extend the condition if needed.
16917             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16918                                Cond);
16919             // Scale the condition by the difference.
16920             if (Diff != 1)
16921               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16922                                  DAG.getConstant(Diff, Cond.getValueType()));
16923
16924             // Add the base if non-zero.
16925             if (FalseC->getAPIntValue() != 0)
16926               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16927                                  SDValue(FalseC, 0));
16928             return Cond;
16929           }
16930         }
16931       }
16932   }
16933
16934   // Canonicalize max and min:
16935   // (x > y) ? x : y -> (x >= y) ? x : y
16936   // (x < y) ? x : y -> (x <= y) ? x : y
16937   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16938   // the need for an extra compare
16939   // against zero. e.g.
16940   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16941   // subl   %esi, %edi
16942   // testl  %edi, %edi
16943   // movl   $0, %eax
16944   // cmovgl %edi, %eax
16945   // =>
16946   // xorl   %eax, %eax
16947   // subl   %esi, $edi
16948   // cmovsl %eax, %edi
16949   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16950       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16951       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16952     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16953     switch (CC) {
16954     default: break;
16955     case ISD::SETLT:
16956     case ISD::SETGT: {
16957       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16958       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16959                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16960       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16961     }
16962     }
16963   }
16964
16965   // Early exit check
16966   if (!TLI.isTypeLegal(VT))
16967     return SDValue();
16968
16969   // Match VSELECTs into subs with unsigned saturation.
16970   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16971       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16972       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16973        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16974     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16975
16976     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16977     // left side invert the predicate to simplify logic below.
16978     SDValue Other;
16979     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16980       Other = RHS;
16981       CC = ISD::getSetCCInverse(CC, true);
16982     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16983       Other = LHS;
16984     }
16985
16986     if (Other.getNode() && Other->getNumOperands() == 2 &&
16987         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16988       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16989       SDValue CondRHS = Cond->getOperand(1);
16990
16991       // Look for a general sub with unsigned saturation first.
16992       // x >= y ? x-y : 0 --> subus x, y
16993       // x >  y ? x-y : 0 --> subus x, y
16994       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16995           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16996         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16997
16998       // If the RHS is a constant we have to reverse the const canonicalization.
16999       // x > C-1 ? x+-C : 0 --> subus x, C
17000       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17001           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17002         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17003         if (CondRHS.getConstantOperandVal(0) == -A-1)
17004           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17005                              DAG.getConstant(-A, VT));
17006       }
17007
17008       // Another special case: If C was a sign bit, the sub has been
17009       // canonicalized into a xor.
17010       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17011       //        it's safe to decanonicalize the xor?
17012       // x s< 0 ? x^C : 0 --> subus x, C
17013       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17014           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17015           isSplatVector(OpRHS.getNode())) {
17016         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17017         if (A.isSignBit())
17018           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17019       }
17020     }
17021   }
17022
17023   // Try to match a min/max vector operation.
17024   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17025     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17026     unsigned Opc = ret.first;
17027     bool NeedSplit = ret.second;
17028
17029     if (Opc && NeedSplit) {
17030       unsigned NumElems = VT.getVectorNumElements();
17031       // Extract the LHS vectors
17032       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17033       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17034
17035       // Extract the RHS vectors
17036       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17037       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17038
17039       // Create min/max for each subvector
17040       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17041       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17042
17043       // Merge the result
17044       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17045     } else if (Opc)
17046       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17047   }
17048
17049   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17050   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17051       // Check if SETCC has already been promoted
17052       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17053       // Check that condition value type matches vselect operand type
17054       CondVT == VT) { 
17055
17056     assert(Cond.getValueType().isVector() &&
17057            "vector select expects a vector selector!");
17058
17059     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17060     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17061
17062     if (!TValIsAllOnes && !FValIsAllZeros) {
17063       // Try invert the condition if true value is not all 1s and false value
17064       // is not all 0s.
17065       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17066       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17067
17068       if (TValIsAllZeros || FValIsAllOnes) {
17069         SDValue CC = Cond.getOperand(2);
17070         ISD::CondCode NewCC =
17071           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17072                                Cond.getOperand(0).getValueType().isInteger());
17073         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17074         std::swap(LHS, RHS);
17075         TValIsAllOnes = FValIsAllOnes;
17076         FValIsAllZeros = TValIsAllZeros;
17077       }
17078     }
17079
17080     if (TValIsAllOnes || FValIsAllZeros) {
17081       SDValue Ret;
17082
17083       if (TValIsAllOnes && FValIsAllZeros)
17084         Ret = Cond;
17085       else if (TValIsAllOnes)
17086         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17087                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17088       else if (FValIsAllZeros)
17089         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17090                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17091
17092       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17093     }
17094   }
17095
17096   // If we know that this node is legal then we know that it is going to be
17097   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17098   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17099   // to simplify previous instructions.
17100   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17101       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17102     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17103
17104     // Don't optimize vector selects that map to mask-registers.
17105     if (BitWidth == 1)
17106       return SDValue();
17107
17108     // Check all uses of that condition operand to check whether it will be
17109     // consumed by non-BLEND instructions, which may depend on all bits are set
17110     // properly.
17111     for (SDNode::use_iterator I = Cond->use_begin(),
17112                               E = Cond->use_end(); I != E; ++I)
17113       if (I->getOpcode() != ISD::VSELECT)
17114         // TODO: Add other opcodes eventually lowered into BLEND.
17115         return SDValue();
17116
17117     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17118     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17119
17120     APInt KnownZero, KnownOne;
17121     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17122                                           DCI.isBeforeLegalizeOps());
17123     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17124         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17125       DCI.CommitTargetLoweringOpt(TLO);
17126   }
17127
17128   return SDValue();
17129 }
17130
17131 // Check whether a boolean test is testing a boolean value generated by
17132 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17133 // code.
17134 //
17135 // Simplify the following patterns:
17136 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17137 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17138 // to (Op EFLAGS Cond)
17139 //
17140 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17141 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17142 // to (Op EFLAGS !Cond)
17143 //
17144 // where Op could be BRCOND or CMOV.
17145 //
17146 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17147   // Quit if not CMP and SUB with its value result used.
17148   if (Cmp.getOpcode() != X86ISD::CMP &&
17149       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17150       return SDValue();
17151
17152   // Quit if not used as a boolean value.
17153   if (CC != X86::COND_E && CC != X86::COND_NE)
17154     return SDValue();
17155
17156   // Check CMP operands. One of them should be 0 or 1 and the other should be
17157   // an SetCC or extended from it.
17158   SDValue Op1 = Cmp.getOperand(0);
17159   SDValue Op2 = Cmp.getOperand(1);
17160
17161   SDValue SetCC;
17162   const ConstantSDNode* C = 0;
17163   bool needOppositeCond = (CC == X86::COND_E);
17164   bool checkAgainstTrue = false; // Is it a comparison against 1?
17165
17166   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17167     SetCC = Op2;
17168   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17169     SetCC = Op1;
17170   else // Quit if all operands are not constants.
17171     return SDValue();
17172
17173   if (C->getZExtValue() == 1) {
17174     needOppositeCond = !needOppositeCond;
17175     checkAgainstTrue = true;
17176   } else if (C->getZExtValue() != 0)
17177     // Quit if the constant is neither 0 or 1.
17178     return SDValue();
17179
17180   bool truncatedToBoolWithAnd = false;
17181   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17182   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17183          SetCC.getOpcode() == ISD::TRUNCATE ||
17184          SetCC.getOpcode() == ISD::AND) {
17185     if (SetCC.getOpcode() == ISD::AND) {
17186       int OpIdx = -1;
17187       ConstantSDNode *CS;
17188       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17189           CS->getZExtValue() == 1)
17190         OpIdx = 1;
17191       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17192           CS->getZExtValue() == 1)
17193         OpIdx = 0;
17194       if (OpIdx == -1)
17195         break;
17196       SetCC = SetCC.getOperand(OpIdx);
17197       truncatedToBoolWithAnd = true;
17198     } else
17199       SetCC = SetCC.getOperand(0);
17200   }
17201
17202   switch (SetCC.getOpcode()) {
17203   case X86ISD::SETCC_CARRY:
17204     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17205     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17206     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17207     // truncated to i1 using 'and'.
17208     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17209       break;
17210     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17211            "Invalid use of SETCC_CARRY!");
17212     // FALL THROUGH
17213   case X86ISD::SETCC:
17214     // Set the condition code or opposite one if necessary.
17215     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17216     if (needOppositeCond)
17217       CC = X86::GetOppositeBranchCondition(CC);
17218     return SetCC.getOperand(1);
17219   case X86ISD::CMOV: {
17220     // Check whether false/true value has canonical one, i.e. 0 or 1.
17221     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17222     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17223     // Quit if true value is not a constant.
17224     if (!TVal)
17225       return SDValue();
17226     // Quit if false value is not a constant.
17227     if (!FVal) {
17228       SDValue Op = SetCC.getOperand(0);
17229       // Skip 'zext' or 'trunc' node.
17230       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17231           Op.getOpcode() == ISD::TRUNCATE)
17232         Op = Op.getOperand(0);
17233       // A special case for rdrand/rdseed, where 0 is set if false cond is
17234       // found.
17235       if ((Op.getOpcode() != X86ISD::RDRAND &&
17236            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17237         return SDValue();
17238     }
17239     // Quit if false value is not the constant 0 or 1.
17240     bool FValIsFalse = true;
17241     if (FVal && FVal->getZExtValue() != 0) {
17242       if (FVal->getZExtValue() != 1)
17243         return SDValue();
17244       // If FVal is 1, opposite cond is needed.
17245       needOppositeCond = !needOppositeCond;
17246       FValIsFalse = false;
17247     }
17248     // Quit if TVal is not the constant opposite of FVal.
17249     if (FValIsFalse && TVal->getZExtValue() != 1)
17250       return SDValue();
17251     if (!FValIsFalse && TVal->getZExtValue() != 0)
17252       return SDValue();
17253     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17254     if (needOppositeCond)
17255       CC = X86::GetOppositeBranchCondition(CC);
17256     return SetCC.getOperand(3);
17257   }
17258   }
17259
17260   return SDValue();
17261 }
17262
17263 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17264 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17265                                   TargetLowering::DAGCombinerInfo &DCI,
17266                                   const X86Subtarget *Subtarget) {
17267   SDLoc DL(N);
17268
17269   // If the flag operand isn't dead, don't touch this CMOV.
17270   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17271     return SDValue();
17272
17273   SDValue FalseOp = N->getOperand(0);
17274   SDValue TrueOp = N->getOperand(1);
17275   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17276   SDValue Cond = N->getOperand(3);
17277
17278   if (CC == X86::COND_E || CC == X86::COND_NE) {
17279     switch (Cond.getOpcode()) {
17280     default: break;
17281     case X86ISD::BSR:
17282     case X86ISD::BSF:
17283       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17284       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17285         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17286     }
17287   }
17288
17289   SDValue Flags;
17290
17291   Flags = checkBoolTestSetCCCombine(Cond, CC);
17292   if (Flags.getNode() &&
17293       // Extra check as FCMOV only supports a subset of X86 cond.
17294       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17295     SDValue Ops[] = { FalseOp, TrueOp,
17296                       DAG.getConstant(CC, MVT::i8), Flags };
17297     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17298                        Ops, array_lengthof(Ops));
17299   }
17300
17301   // If this is a select between two integer constants, try to do some
17302   // optimizations.  Note that the operands are ordered the opposite of SELECT
17303   // operands.
17304   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17305     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17306       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17307       // larger than FalseC (the false value).
17308       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17309         CC = X86::GetOppositeBranchCondition(CC);
17310         std::swap(TrueC, FalseC);
17311         std::swap(TrueOp, FalseOp);
17312       }
17313
17314       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17315       // This is efficient for any integer data type (including i8/i16) and
17316       // shift amount.
17317       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17318         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17319                            DAG.getConstant(CC, MVT::i8), Cond);
17320
17321         // Zero extend the condition if needed.
17322         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17323
17324         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17325         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17326                            DAG.getConstant(ShAmt, MVT::i8));
17327         if (N->getNumValues() == 2)  // Dead flag value?
17328           return DCI.CombineTo(N, Cond, SDValue());
17329         return Cond;
17330       }
17331
17332       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17333       // for any integer data type, including i8/i16.
17334       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17335         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17336                            DAG.getConstant(CC, MVT::i8), Cond);
17337
17338         // Zero extend the condition if needed.
17339         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17340                            FalseC->getValueType(0), Cond);
17341         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17342                            SDValue(FalseC, 0));
17343
17344         if (N->getNumValues() == 2)  // Dead flag value?
17345           return DCI.CombineTo(N, Cond, SDValue());
17346         return Cond;
17347       }
17348
17349       // Optimize cases that will turn into an LEA instruction.  This requires
17350       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17351       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17352         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17353         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17354
17355         bool isFastMultiplier = false;
17356         if (Diff < 10) {
17357           switch ((unsigned char)Diff) {
17358           default: break;
17359           case 1:  // result = add base, cond
17360           case 2:  // result = lea base(    , cond*2)
17361           case 3:  // result = lea base(cond, cond*2)
17362           case 4:  // result = lea base(    , cond*4)
17363           case 5:  // result = lea base(cond, cond*4)
17364           case 8:  // result = lea base(    , cond*8)
17365           case 9:  // result = lea base(cond, cond*8)
17366             isFastMultiplier = true;
17367             break;
17368           }
17369         }
17370
17371         if (isFastMultiplier) {
17372           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17373           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17374                              DAG.getConstant(CC, MVT::i8), Cond);
17375           // Zero extend the condition if needed.
17376           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17377                              Cond);
17378           // Scale the condition by the difference.
17379           if (Diff != 1)
17380             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17381                                DAG.getConstant(Diff, Cond.getValueType()));
17382
17383           // Add the base if non-zero.
17384           if (FalseC->getAPIntValue() != 0)
17385             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17386                                SDValue(FalseC, 0));
17387           if (N->getNumValues() == 2)  // Dead flag value?
17388             return DCI.CombineTo(N, Cond, SDValue());
17389           return Cond;
17390         }
17391       }
17392     }
17393   }
17394
17395   // Handle these cases:
17396   //   (select (x != c), e, c) -> select (x != c), e, x),
17397   //   (select (x == c), c, e) -> select (x == c), x, e)
17398   // where the c is an integer constant, and the "select" is the combination
17399   // of CMOV and CMP.
17400   //
17401   // The rationale for this change is that the conditional-move from a constant
17402   // needs two instructions, however, conditional-move from a register needs
17403   // only one instruction.
17404   //
17405   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17406   //  some instruction-combining opportunities. This opt needs to be
17407   //  postponed as late as possible.
17408   //
17409   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17410     // the DCI.xxxx conditions are provided to postpone the optimization as
17411     // late as possible.
17412
17413     ConstantSDNode *CmpAgainst = 0;
17414     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17415         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17416         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17417
17418       if (CC == X86::COND_NE &&
17419           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17420         CC = X86::GetOppositeBranchCondition(CC);
17421         std::swap(TrueOp, FalseOp);
17422       }
17423
17424       if (CC == X86::COND_E &&
17425           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17426         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17427                           DAG.getConstant(CC, MVT::i8), Cond };
17428         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17429                            array_lengthof(Ops));
17430       }
17431     }
17432   }
17433
17434   return SDValue();
17435 }
17436
17437 /// PerformMulCombine - Optimize a single multiply with constant into two
17438 /// in order to implement it with two cheaper instructions, e.g.
17439 /// LEA + SHL, LEA + LEA.
17440 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17441                                  TargetLowering::DAGCombinerInfo &DCI) {
17442   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17443     return SDValue();
17444
17445   EVT VT = N->getValueType(0);
17446   if (VT != MVT::i64)
17447     return SDValue();
17448
17449   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17450   if (!C)
17451     return SDValue();
17452   uint64_t MulAmt = C->getZExtValue();
17453   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17454     return SDValue();
17455
17456   uint64_t MulAmt1 = 0;
17457   uint64_t MulAmt2 = 0;
17458   if ((MulAmt % 9) == 0) {
17459     MulAmt1 = 9;
17460     MulAmt2 = MulAmt / 9;
17461   } else if ((MulAmt % 5) == 0) {
17462     MulAmt1 = 5;
17463     MulAmt2 = MulAmt / 5;
17464   } else if ((MulAmt % 3) == 0) {
17465     MulAmt1 = 3;
17466     MulAmt2 = MulAmt / 3;
17467   }
17468   if (MulAmt2 &&
17469       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17470     SDLoc DL(N);
17471
17472     if (isPowerOf2_64(MulAmt2) &&
17473         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17474       // If second multiplifer is pow2, issue it first. We want the multiply by
17475       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17476       // is an add.
17477       std::swap(MulAmt1, MulAmt2);
17478
17479     SDValue NewMul;
17480     if (isPowerOf2_64(MulAmt1))
17481       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17482                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17483     else
17484       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17485                            DAG.getConstant(MulAmt1, VT));
17486
17487     if (isPowerOf2_64(MulAmt2))
17488       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17489                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17490     else
17491       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17492                            DAG.getConstant(MulAmt2, VT));
17493
17494     // Do not add new nodes to DAG combiner worklist.
17495     DCI.CombineTo(N, NewMul, false);
17496   }
17497   return SDValue();
17498 }
17499
17500 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17501   SDValue N0 = N->getOperand(0);
17502   SDValue N1 = N->getOperand(1);
17503   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17504   EVT VT = N0.getValueType();
17505
17506   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17507   // since the result of setcc_c is all zero's or all ones.
17508   if (VT.isInteger() && !VT.isVector() &&
17509       N1C && N0.getOpcode() == ISD::AND &&
17510       N0.getOperand(1).getOpcode() == ISD::Constant) {
17511     SDValue N00 = N0.getOperand(0);
17512     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17513         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17514           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17515          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17516       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17517       APInt ShAmt = N1C->getAPIntValue();
17518       Mask = Mask.shl(ShAmt);
17519       if (Mask != 0)
17520         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17521                            N00, DAG.getConstant(Mask, VT));
17522     }
17523   }
17524
17525   // Hardware support for vector shifts is sparse which makes us scalarize the
17526   // vector operations in many cases. Also, on sandybridge ADD is faster than
17527   // shl.
17528   // (shl V, 1) -> add V,V
17529   if (isSplatVector(N1.getNode())) {
17530     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17531     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17532     // We shift all of the values by one. In many cases we do not have
17533     // hardware support for this operation. This is better expressed as an ADD
17534     // of two values.
17535     if (N1C && (1 == N1C->getZExtValue())) {
17536       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17537     }
17538   }
17539
17540   return SDValue();
17541 }
17542
17543 /// \brief Returns a vector of 0s if the node in input is a vector logical
17544 /// shift by a constant amount which is known to be bigger than or equal
17545 /// to the vector element size in bits.
17546 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17547                                       const X86Subtarget *Subtarget) {
17548   EVT VT = N->getValueType(0);
17549
17550   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17551       (!Subtarget->hasInt256() ||
17552        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17553     return SDValue();
17554
17555   SDValue Amt = N->getOperand(1);
17556   SDLoc DL(N);
17557   if (isSplatVector(Amt.getNode())) {
17558     SDValue SclrAmt = Amt->getOperand(0);
17559     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17560       APInt ShiftAmt = C->getAPIntValue();
17561       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17562
17563       // SSE2/AVX2 logical shifts always return a vector of 0s
17564       // if the shift amount is bigger than or equal to
17565       // the element size. The constant shift amount will be
17566       // encoded as a 8-bit immediate.
17567       if (ShiftAmt.trunc(8).uge(MaxAmount))
17568         return getZeroVector(VT, Subtarget, DAG, DL);
17569     }
17570   }
17571
17572   return SDValue();
17573 }
17574
17575 /// PerformShiftCombine - Combine shifts.
17576 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17577                                    TargetLowering::DAGCombinerInfo &DCI,
17578                                    const X86Subtarget *Subtarget) {
17579   if (N->getOpcode() == ISD::SHL) {
17580     SDValue V = PerformSHLCombine(N, DAG);
17581     if (V.getNode()) return V;
17582   }
17583
17584   if (N->getOpcode() != ISD::SRA) {
17585     // Try to fold this logical shift into a zero vector.
17586     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17587     if (V.getNode()) return V;
17588   }
17589
17590   return SDValue();
17591 }
17592
17593 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
17594 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17595 // and friends.  Likewise for OR -> CMPNEQSS.
17596 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17597                             TargetLowering::DAGCombinerInfo &DCI,
17598                             const X86Subtarget *Subtarget) {
17599   unsigned opcode;
17600
17601   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17602   // we're requiring SSE2 for both.
17603   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17604     SDValue N0 = N->getOperand(0);
17605     SDValue N1 = N->getOperand(1);
17606     SDValue CMP0 = N0->getOperand(1);
17607     SDValue CMP1 = N1->getOperand(1);
17608     SDLoc DL(N);
17609
17610     // The SETCCs should both refer to the same CMP.
17611     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
17612       return SDValue();
17613
17614     SDValue CMP00 = CMP0->getOperand(0);
17615     SDValue CMP01 = CMP0->getOperand(1);
17616     EVT     VT    = CMP00.getValueType();
17617
17618     if (VT == MVT::f32 || VT == MVT::f64) {
17619       bool ExpectingFlags = false;
17620       // Check for any users that want flags:
17621       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
17622            !ExpectingFlags && UI != UE; ++UI)
17623         switch (UI->getOpcode()) {
17624         default:
17625         case ISD::BR_CC:
17626         case ISD::BRCOND:
17627         case ISD::SELECT:
17628           ExpectingFlags = true;
17629           break;
17630         case ISD::CopyToReg:
17631         case ISD::SIGN_EXTEND:
17632         case ISD::ZERO_EXTEND:
17633         case ISD::ANY_EXTEND:
17634           break;
17635         }
17636
17637       if (!ExpectingFlags) {
17638         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
17639         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
17640
17641         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
17642           X86::CondCode tmp = cc0;
17643           cc0 = cc1;
17644           cc1 = tmp;
17645         }
17646
17647         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
17648             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17649           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17650           // FIXME: need symbolic constants for these magic numbers.
17651           // See X86ATTInstPrinter.cpp:printSSECC().
17652           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17653           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00, CMP01,
17654                                               DAG.getConstant(x86cc, MVT::i8));
17655           MVT IntVT = (is64BitFP ? MVT::i64 : MVT::i32); 
17656           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
17657                                               OnesOrZeroesF);
17658           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
17659                                       DAG.getConstant(1, IntVT));
17660           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17661           return OneBitOfTruth;
17662         }
17663       }
17664     }
17665   }
17666   return SDValue();
17667 }
17668
17669 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17670 /// so it can be folded inside ANDNP.
17671 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17672   EVT VT = N->getValueType(0);
17673
17674   // Match direct AllOnes for 128 and 256-bit vectors
17675   if (ISD::isBuildVectorAllOnes(N))
17676     return true;
17677
17678   // Look through a bit convert.
17679   if (N->getOpcode() == ISD::BITCAST)
17680     N = N->getOperand(0).getNode();
17681
17682   // Sometimes the operand may come from a insert_subvector building a 256-bit
17683   // allones vector
17684   if (VT.is256BitVector() &&
17685       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17686     SDValue V1 = N->getOperand(0);
17687     SDValue V2 = N->getOperand(1);
17688
17689     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17690         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17691         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17692         ISD::isBuildVectorAllOnes(V2.getNode()))
17693       return true;
17694   }
17695
17696   return false;
17697 }
17698
17699 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17700 // register. In most cases we actually compare or select YMM-sized registers
17701 // and mixing the two types creates horrible code. This method optimizes
17702 // some of the transition sequences.
17703 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17704                                  TargetLowering::DAGCombinerInfo &DCI,
17705                                  const X86Subtarget *Subtarget) {
17706   EVT VT = N->getValueType(0);
17707   if (!VT.is256BitVector())
17708     return SDValue();
17709
17710   assert((N->getOpcode() == ISD::ANY_EXTEND ||
17711           N->getOpcode() == ISD::ZERO_EXTEND ||
17712           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17713
17714   SDValue Narrow = N->getOperand(0);
17715   EVT NarrowVT = Narrow->getValueType(0);
17716   if (!NarrowVT.is128BitVector())
17717     return SDValue();
17718
17719   if (Narrow->getOpcode() != ISD::XOR &&
17720       Narrow->getOpcode() != ISD::AND &&
17721       Narrow->getOpcode() != ISD::OR)
17722     return SDValue();
17723
17724   SDValue N0  = Narrow->getOperand(0);
17725   SDValue N1  = Narrow->getOperand(1);
17726   SDLoc DL(Narrow);
17727
17728   // The Left side has to be a trunc.
17729   if (N0.getOpcode() != ISD::TRUNCATE)
17730     return SDValue();
17731
17732   // The type of the truncated inputs.
17733   EVT WideVT = N0->getOperand(0)->getValueType(0);
17734   if (WideVT != VT)
17735     return SDValue();
17736
17737   // The right side has to be a 'trunc' or a constant vector.
17738   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17739   bool RHSConst = (isSplatVector(N1.getNode()) &&
17740                    isa<ConstantSDNode>(N1->getOperand(0)));
17741   if (!RHSTrunc && !RHSConst)
17742     return SDValue();
17743
17744   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17745
17746   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17747     return SDValue();
17748
17749   // Set N0 and N1 to hold the inputs to the new wide operation.
17750   N0 = N0->getOperand(0);
17751   if (RHSConst) {
17752     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17753                      N1->getOperand(0));
17754     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17755     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17756   } else if (RHSTrunc) {
17757     N1 = N1->getOperand(0);
17758   }
17759
17760   // Generate the wide operation.
17761   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17762   unsigned Opcode = N->getOpcode();
17763   switch (Opcode) {
17764   case ISD::ANY_EXTEND:
17765     return Op;
17766   case ISD::ZERO_EXTEND: {
17767     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17768     APInt Mask = APInt::getAllOnesValue(InBits);
17769     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17770     return DAG.getNode(ISD::AND, DL, VT,
17771                        Op, DAG.getConstant(Mask, VT));
17772   }
17773   case ISD::SIGN_EXTEND:
17774     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17775                        Op, DAG.getValueType(NarrowVT));
17776   default:
17777     llvm_unreachable("Unexpected opcode");
17778   }
17779 }
17780
17781 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17782                                  TargetLowering::DAGCombinerInfo &DCI,
17783                                  const X86Subtarget *Subtarget) {
17784   EVT VT = N->getValueType(0);
17785   if (DCI.isBeforeLegalizeOps())
17786     return SDValue();
17787
17788   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17789   if (R.getNode())
17790     return R;
17791
17792   // Create BLSI, BLSR, and BZHI instructions
17793   // BLSI is X & (-X)
17794   // BLSR is X & (X-1)
17795   // BZHI is X & ((1 << Y) - 1)
17796   // BEXTR is ((X >> imm) & (2**size-1))
17797   if (VT == MVT::i32 || VT == MVT::i64) {
17798     SDValue N0 = N->getOperand(0);
17799     SDValue N1 = N->getOperand(1);
17800     SDLoc DL(N);
17801
17802     if (Subtarget->hasBMI()) {
17803       // Check LHS for neg
17804       if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17805           isZero(N0.getOperand(0)))
17806         return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17807
17808       // Check RHS for neg
17809       if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17810           isZero(N1.getOperand(0)))
17811         return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17812
17813       // Check LHS for X-1
17814       if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17815           isAllOnes(N0.getOperand(1)))
17816         return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17817
17818       // Check RHS for X-1
17819       if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17820           isAllOnes(N1.getOperand(1)))
17821         return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17822     }
17823
17824     if (Subtarget->hasBMI2()) {
17825       // Check for (and (add (shl 1, Y), -1), X)
17826       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
17827         SDValue N00 = N0.getOperand(0);
17828         if (N00.getOpcode() == ISD::SHL) {
17829           SDValue N001 = N00.getOperand(1);
17830           assert(N001.getValueType() == MVT::i8 && "unexpected type");
17831           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
17832           if (C && C->getZExtValue() == 1)
17833             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
17834         }
17835       }
17836
17837       // Check for (and X, (add (shl 1, Y), -1))
17838       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
17839         SDValue N10 = N1.getOperand(0);
17840         if (N10.getOpcode() == ISD::SHL) {
17841           SDValue N101 = N10.getOperand(1);
17842           assert(N101.getValueType() == MVT::i8 && "unexpected type");
17843           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
17844           if (C && C->getZExtValue() == 1)
17845             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
17846         }
17847       }
17848     }
17849
17850     // Check for BEXTR.
17851     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
17852         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
17853       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
17854       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17855       if (MaskNode && ShiftNode) {
17856         uint64_t Mask = MaskNode->getZExtValue();
17857         uint64_t Shift = ShiftNode->getZExtValue();
17858         if (isMask_64(Mask)) {
17859           uint64_t MaskSize = CountPopulation_64(Mask);
17860           if (Shift + MaskSize <= VT.getSizeInBits())
17861             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
17862                                DAG.getConstant(Shift | (MaskSize << 8), VT));
17863         }
17864       }
17865     } // BEXTR
17866
17867     return SDValue();
17868   }
17869
17870   // Want to form ANDNP nodes:
17871   // 1) In the hopes of then easily combining them with OR and AND nodes
17872   //    to form PBLEND/PSIGN.
17873   // 2) To match ANDN packed intrinsics
17874   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17875     return SDValue();
17876
17877   SDValue N0 = N->getOperand(0);
17878   SDValue N1 = N->getOperand(1);
17879   SDLoc DL(N);
17880
17881   // Check LHS for vnot
17882   if (N0.getOpcode() == ISD::XOR &&
17883       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17884       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17885     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17886
17887   // Check RHS for vnot
17888   if (N1.getOpcode() == ISD::XOR &&
17889       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17890       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17891     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17892
17893   return SDValue();
17894 }
17895
17896 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17897                                 TargetLowering::DAGCombinerInfo &DCI,
17898                                 const X86Subtarget *Subtarget) {
17899   EVT VT = N->getValueType(0);
17900   if (DCI.isBeforeLegalizeOps())
17901     return SDValue();
17902
17903   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17904   if (R.getNode())
17905     return R;
17906
17907   SDValue N0 = N->getOperand(0);
17908   SDValue N1 = N->getOperand(1);
17909
17910   // look for psign/blend
17911   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17912     if (!Subtarget->hasSSSE3() ||
17913         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17914       return SDValue();
17915
17916     // Canonicalize pandn to RHS
17917     if (N0.getOpcode() == X86ISD::ANDNP)
17918       std::swap(N0, N1);
17919     // or (and (m, y), (pandn m, x))
17920     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17921       SDValue Mask = N1.getOperand(0);
17922       SDValue X    = N1.getOperand(1);
17923       SDValue Y;
17924       if (N0.getOperand(0) == Mask)
17925         Y = N0.getOperand(1);
17926       if (N0.getOperand(1) == Mask)
17927         Y = N0.getOperand(0);
17928
17929       // Check to see if the mask appeared in both the AND and ANDNP and
17930       if (!Y.getNode())
17931         return SDValue();
17932
17933       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17934       // Look through mask bitcast.
17935       if (Mask.getOpcode() == ISD::BITCAST)
17936         Mask = Mask.getOperand(0);
17937       if (X.getOpcode() == ISD::BITCAST)
17938         X = X.getOperand(0);
17939       if (Y.getOpcode() == ISD::BITCAST)
17940         Y = Y.getOperand(0);
17941
17942       EVT MaskVT = Mask.getValueType();
17943
17944       // Validate that the Mask operand is a vector sra node.
17945       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17946       // there is no psrai.b
17947       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17948       unsigned SraAmt = ~0;
17949       if (Mask.getOpcode() == ISD::SRA) {
17950         SDValue Amt = Mask.getOperand(1);
17951         if (isSplatVector(Amt.getNode())) {
17952           SDValue SclrAmt = Amt->getOperand(0);
17953           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17954             SraAmt = C->getZExtValue();
17955         }
17956       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17957         SDValue SraC = Mask.getOperand(1);
17958         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
17959       }
17960       if ((SraAmt + 1) != EltBits)
17961         return SDValue();
17962
17963       SDLoc DL(N);
17964
17965       // Now we know we at least have a plendvb with the mask val.  See if
17966       // we can form a psignb/w/d.
17967       // psign = x.type == y.type == mask.type && y = sub(0, x);
17968       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17969           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17970           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17971         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17972                "Unsupported VT for PSIGN");
17973         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17974         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17975       }
17976       // PBLENDVB only available on SSE 4.1
17977       if (!Subtarget->hasSSE41())
17978         return SDValue();
17979
17980       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17981
17982       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17983       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17984       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17985       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17986       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17987     }
17988   }
17989
17990   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17991     return SDValue();
17992
17993   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17994   MachineFunction &MF = DAG.getMachineFunction();
17995   bool OptForSize = MF.getFunction()->getAttributes().
17996     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
17997
17998   // SHLD/SHRD instructions have lower register pressure, but on some
17999   // platforms they have higher latency than the equivalent
18000   // series of shifts/or that would otherwise be generated.
18001   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18002   // have higher latencies and we are not optimizing for size.
18003   if (!OptForSize && Subtarget->isSHLDSlow())
18004     return SDValue();
18005
18006   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18007     std::swap(N0, N1);
18008   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18009     return SDValue();
18010   if (!N0.hasOneUse() || !N1.hasOneUse())
18011     return SDValue();
18012
18013   SDValue ShAmt0 = N0.getOperand(1);
18014   if (ShAmt0.getValueType() != MVT::i8)
18015     return SDValue();
18016   SDValue ShAmt1 = N1.getOperand(1);
18017   if (ShAmt1.getValueType() != MVT::i8)
18018     return SDValue();
18019   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18020     ShAmt0 = ShAmt0.getOperand(0);
18021   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18022     ShAmt1 = ShAmt1.getOperand(0);
18023
18024   SDLoc DL(N);
18025   unsigned Opc = X86ISD::SHLD;
18026   SDValue Op0 = N0.getOperand(0);
18027   SDValue Op1 = N1.getOperand(0);
18028   if (ShAmt0.getOpcode() == ISD::SUB) {
18029     Opc = X86ISD::SHRD;
18030     std::swap(Op0, Op1);
18031     std::swap(ShAmt0, ShAmt1);
18032   }
18033
18034   unsigned Bits = VT.getSizeInBits();
18035   if (ShAmt1.getOpcode() == ISD::SUB) {
18036     SDValue Sum = ShAmt1.getOperand(0);
18037     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18038       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18039       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18040         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18041       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18042         return DAG.getNode(Opc, DL, VT,
18043                            Op0, Op1,
18044                            DAG.getNode(ISD::TRUNCATE, DL,
18045                                        MVT::i8, ShAmt0));
18046     }
18047   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18048     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18049     if (ShAmt0C &&
18050         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18051       return DAG.getNode(Opc, DL, VT,
18052                          N0.getOperand(0), N1.getOperand(0),
18053                          DAG.getNode(ISD::TRUNCATE, DL,
18054                                        MVT::i8, ShAmt0));
18055   }
18056
18057   return SDValue();
18058 }
18059
18060 // Generate NEG and CMOV for integer abs.
18061 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18062   EVT VT = N->getValueType(0);
18063
18064   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18065   // 8-bit integer abs to NEG and CMOV.
18066   if (VT.isInteger() && VT.getSizeInBits() == 8)
18067     return SDValue();
18068
18069   SDValue N0 = N->getOperand(0);
18070   SDValue N1 = N->getOperand(1);
18071   SDLoc DL(N);
18072
18073   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18074   // and change it to SUB and CMOV.
18075   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18076       N0.getOpcode() == ISD::ADD &&
18077       N0.getOperand(1) == N1 &&
18078       N1.getOpcode() == ISD::SRA &&
18079       N1.getOperand(0) == N0.getOperand(0))
18080     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18081       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18082         // Generate SUB & CMOV.
18083         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18084                                   DAG.getConstant(0, VT), N0.getOperand(0));
18085
18086         SDValue Ops[] = { N0.getOperand(0), Neg,
18087                           DAG.getConstant(X86::COND_GE, MVT::i8),
18088                           SDValue(Neg.getNode(), 1) };
18089         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18090                            Ops, array_lengthof(Ops));
18091       }
18092   return SDValue();
18093 }
18094
18095 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18096 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18097                                  TargetLowering::DAGCombinerInfo &DCI,
18098                                  const X86Subtarget *Subtarget) {
18099   EVT VT = N->getValueType(0);
18100   if (DCI.isBeforeLegalizeOps())
18101     return SDValue();
18102
18103   if (Subtarget->hasCMov()) {
18104     SDValue RV = performIntegerAbsCombine(N, DAG);
18105     if (RV.getNode())
18106       return RV;
18107   }
18108
18109   // Try forming BMI if it is available.
18110   if (!Subtarget->hasBMI())
18111     return SDValue();
18112
18113   if (VT != MVT::i32 && VT != MVT::i64)
18114     return SDValue();
18115
18116   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
18117
18118   // Create BLSMSK instructions by finding X ^ (X-1)
18119   SDValue N0 = N->getOperand(0);
18120   SDValue N1 = N->getOperand(1);
18121   SDLoc DL(N);
18122
18123   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
18124       isAllOnes(N0.getOperand(1)))
18125     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
18126
18127   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
18128       isAllOnes(N1.getOperand(1)))
18129     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
18130
18131   return SDValue();
18132 }
18133
18134 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18135 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18136                                   TargetLowering::DAGCombinerInfo &DCI,
18137                                   const X86Subtarget *Subtarget) {
18138   LoadSDNode *Ld = cast<LoadSDNode>(N);
18139   EVT RegVT = Ld->getValueType(0);
18140   EVT MemVT = Ld->getMemoryVT();
18141   SDLoc dl(Ld);
18142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18143   unsigned RegSz = RegVT.getSizeInBits();
18144
18145   // On Sandybridge unaligned 256bit loads are inefficient.
18146   ISD::LoadExtType Ext = Ld->getExtensionType();
18147   unsigned Alignment = Ld->getAlignment();
18148   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18149   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18150       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18151     unsigned NumElems = RegVT.getVectorNumElements();
18152     if (NumElems < 2)
18153       return SDValue();
18154
18155     SDValue Ptr = Ld->getBasePtr();
18156     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18157
18158     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18159                                   NumElems/2);
18160     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18161                                 Ld->getPointerInfo(), Ld->isVolatile(),
18162                                 Ld->isNonTemporal(), Ld->isInvariant(),
18163                                 Alignment);
18164     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18165     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18166                                 Ld->getPointerInfo(), Ld->isVolatile(),
18167                                 Ld->isNonTemporal(), Ld->isInvariant(),
18168                                 std::min(16U, Alignment));
18169     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18170                              Load1.getValue(1),
18171                              Load2.getValue(1));
18172
18173     SDValue NewVec = DAG.getUNDEF(RegVT);
18174     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18175     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18176     return DCI.CombineTo(N, NewVec, TF, true);
18177   }
18178
18179   // If this is a vector EXT Load then attempt to optimize it using a
18180   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18181   // expansion is still better than scalar code.
18182   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18183   // emit a shuffle and a arithmetic shift.
18184   // TODO: It is possible to support ZExt by zeroing the undef values
18185   // during the shuffle phase or after the shuffle.
18186   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18187       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18188     assert(MemVT != RegVT && "Cannot extend to the same type");
18189     assert(MemVT.isVector() && "Must load a vector from memory");
18190
18191     unsigned NumElems = RegVT.getVectorNumElements();
18192     unsigned MemSz = MemVT.getSizeInBits();
18193     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18194
18195     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18196       return SDValue();
18197
18198     // All sizes must be a power of two.
18199     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18200       return SDValue();
18201
18202     // Attempt to load the original value using scalar loads.
18203     // Find the largest scalar type that divides the total loaded size.
18204     MVT SclrLoadTy = MVT::i8;
18205     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18206          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18207       MVT Tp = (MVT::SimpleValueType)tp;
18208       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18209         SclrLoadTy = Tp;
18210       }
18211     }
18212
18213     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18214     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18215         (64 <= MemSz))
18216       SclrLoadTy = MVT::f64;
18217
18218     // Calculate the number of scalar loads that we need to perform
18219     // in order to load our vector from memory.
18220     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18221     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18222       return SDValue();
18223
18224     unsigned loadRegZize = RegSz;
18225     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18226       loadRegZize /= 2;
18227
18228     // Represent our vector as a sequence of elements which are the
18229     // largest scalar that we can load.
18230     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18231       loadRegZize/SclrLoadTy.getSizeInBits());
18232
18233     // Represent the data using the same element type that is stored in
18234     // memory. In practice, we ''widen'' MemVT.
18235     EVT WideVecVT =
18236           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18237                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18238
18239     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18240       "Invalid vector type");
18241
18242     // We can't shuffle using an illegal type.
18243     if (!TLI.isTypeLegal(WideVecVT))
18244       return SDValue();
18245
18246     SmallVector<SDValue, 8> Chains;
18247     SDValue Ptr = Ld->getBasePtr();
18248     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18249                                         TLI.getPointerTy());
18250     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18251
18252     for (unsigned i = 0; i < NumLoads; ++i) {
18253       // Perform a single load.
18254       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18255                                        Ptr, Ld->getPointerInfo(),
18256                                        Ld->isVolatile(), Ld->isNonTemporal(),
18257                                        Ld->isInvariant(), Ld->getAlignment());
18258       Chains.push_back(ScalarLoad.getValue(1));
18259       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18260       // another round of DAGCombining.
18261       if (i == 0)
18262         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18263       else
18264         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18265                           ScalarLoad, DAG.getIntPtrConstant(i));
18266
18267       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18268     }
18269
18270     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18271                                Chains.size());
18272
18273     // Bitcast the loaded value to a vector of the original element type, in
18274     // the size of the target vector type.
18275     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18276     unsigned SizeRatio = RegSz/MemSz;
18277
18278     if (Ext == ISD::SEXTLOAD) {
18279       // If we have SSE4.1 we can directly emit a VSEXT node.
18280       if (Subtarget->hasSSE41()) {
18281         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18282         return DCI.CombineTo(N, Sext, TF, true);
18283       }
18284
18285       // Otherwise we'll shuffle the small elements in the high bits of the
18286       // larger type and perform an arithmetic shift. If the shift is not legal
18287       // it's better to scalarize.
18288       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18289         return SDValue();
18290
18291       // Redistribute the loaded elements into the different locations.
18292       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18293       for (unsigned i = 0; i != NumElems; ++i)
18294         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18295
18296       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18297                                            DAG.getUNDEF(WideVecVT),
18298                                            &ShuffleVec[0]);
18299
18300       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18301
18302       // Build the arithmetic shift.
18303       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18304                      MemVT.getVectorElementType().getSizeInBits();
18305       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18306                           DAG.getConstant(Amt, RegVT));
18307
18308       return DCI.CombineTo(N, Shuff, TF, true);
18309     }
18310
18311     // Redistribute the loaded elements into the different locations.
18312     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18313     for (unsigned i = 0; i != NumElems; ++i)
18314       ShuffleVec[i*SizeRatio] = i;
18315
18316     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18317                                          DAG.getUNDEF(WideVecVT),
18318                                          &ShuffleVec[0]);
18319
18320     // Bitcast to the requested type.
18321     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18322     // Replace the original load with the new sequence
18323     // and return the new chain.
18324     return DCI.CombineTo(N, Shuff, TF, true);
18325   }
18326
18327   return SDValue();
18328 }
18329
18330 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18331 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18332                                    const X86Subtarget *Subtarget) {
18333   StoreSDNode *St = cast<StoreSDNode>(N);
18334   EVT VT = St->getValue().getValueType();
18335   EVT StVT = St->getMemoryVT();
18336   SDLoc dl(St);
18337   SDValue StoredVal = St->getOperand(1);
18338   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18339
18340   // If we are saving a concatenation of two XMM registers, perform two stores.
18341   // On Sandy Bridge, 256-bit memory operations are executed by two
18342   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18343   // memory  operation.
18344   unsigned Alignment = St->getAlignment();
18345   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18346   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18347       StVT == VT && !IsAligned) {
18348     unsigned NumElems = VT.getVectorNumElements();
18349     if (NumElems < 2)
18350       return SDValue();
18351
18352     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18353     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18354
18355     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18356     SDValue Ptr0 = St->getBasePtr();
18357     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18358
18359     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18360                                 St->getPointerInfo(), St->isVolatile(),
18361                                 St->isNonTemporal(), Alignment);
18362     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18363                                 St->getPointerInfo(), St->isVolatile(),
18364                                 St->isNonTemporal(),
18365                                 std::min(16U, Alignment));
18366     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18367   }
18368
18369   // Optimize trunc store (of multiple scalars) to shuffle and store.
18370   // First, pack all of the elements in one place. Next, store to memory
18371   // in fewer chunks.
18372   if (St->isTruncatingStore() && VT.isVector()) {
18373     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18374     unsigned NumElems = VT.getVectorNumElements();
18375     assert(StVT != VT && "Cannot truncate to the same type");
18376     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18377     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18378
18379     // From, To sizes and ElemCount must be pow of two
18380     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18381     // We are going to use the original vector elt for storing.
18382     // Accumulated smaller vector elements must be a multiple of the store size.
18383     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18384
18385     unsigned SizeRatio  = FromSz / ToSz;
18386
18387     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18388
18389     // Create a type on which we perform the shuffle
18390     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18391             StVT.getScalarType(), NumElems*SizeRatio);
18392
18393     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18394
18395     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18396     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18397     for (unsigned i = 0; i != NumElems; ++i)
18398       ShuffleVec[i] = i * SizeRatio;
18399
18400     // Can't shuffle using an illegal type.
18401     if (!TLI.isTypeLegal(WideVecVT))
18402       return SDValue();
18403
18404     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18405                                          DAG.getUNDEF(WideVecVT),
18406                                          &ShuffleVec[0]);
18407     // At this point all of the data is stored at the bottom of the
18408     // register. We now need to save it to mem.
18409
18410     // Find the largest store unit
18411     MVT StoreType = MVT::i8;
18412     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18413          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18414       MVT Tp = (MVT::SimpleValueType)tp;
18415       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18416         StoreType = Tp;
18417     }
18418
18419     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18420     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18421         (64 <= NumElems * ToSz))
18422       StoreType = MVT::f64;
18423
18424     // Bitcast the original vector into a vector of store-size units
18425     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18426             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18427     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18428     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18429     SmallVector<SDValue, 8> Chains;
18430     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18431                                         TLI.getPointerTy());
18432     SDValue Ptr = St->getBasePtr();
18433
18434     // Perform one or more big stores into memory.
18435     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18436       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18437                                    StoreType, ShuffWide,
18438                                    DAG.getIntPtrConstant(i));
18439       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18440                                 St->getPointerInfo(), St->isVolatile(),
18441                                 St->isNonTemporal(), St->getAlignment());
18442       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18443       Chains.push_back(Ch);
18444     }
18445
18446     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18447                                Chains.size());
18448   }
18449
18450   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18451   // the FP state in cases where an emms may be missing.
18452   // A preferable solution to the general problem is to figure out the right
18453   // places to insert EMMS.  This qualifies as a quick hack.
18454
18455   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18456   if (VT.getSizeInBits() != 64)
18457     return SDValue();
18458
18459   const Function *F = DAG.getMachineFunction().getFunction();
18460   bool NoImplicitFloatOps = F->getAttributes().
18461     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18462   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18463                      && Subtarget->hasSSE2();
18464   if ((VT.isVector() ||
18465        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18466       isa<LoadSDNode>(St->getValue()) &&
18467       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18468       St->getChain().hasOneUse() && !St->isVolatile()) {
18469     SDNode* LdVal = St->getValue().getNode();
18470     LoadSDNode *Ld = 0;
18471     int TokenFactorIndex = -1;
18472     SmallVector<SDValue, 8> Ops;
18473     SDNode* ChainVal = St->getChain().getNode();
18474     // Must be a store of a load.  We currently handle two cases:  the load
18475     // is a direct child, and it's under an intervening TokenFactor.  It is
18476     // possible to dig deeper under nested TokenFactors.
18477     if (ChainVal == LdVal)
18478       Ld = cast<LoadSDNode>(St->getChain());
18479     else if (St->getValue().hasOneUse() &&
18480              ChainVal->getOpcode() == ISD::TokenFactor) {
18481       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18482         if (ChainVal->getOperand(i).getNode() == LdVal) {
18483           TokenFactorIndex = i;
18484           Ld = cast<LoadSDNode>(St->getValue());
18485         } else
18486           Ops.push_back(ChainVal->getOperand(i));
18487       }
18488     }
18489
18490     if (!Ld || !ISD::isNormalLoad(Ld))
18491       return SDValue();
18492
18493     // If this is not the MMX case, i.e. we are just turning i64 load/store
18494     // into f64 load/store, avoid the transformation if there are multiple
18495     // uses of the loaded value.
18496     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18497       return SDValue();
18498
18499     SDLoc LdDL(Ld);
18500     SDLoc StDL(N);
18501     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18502     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18503     // pair instead.
18504     if (Subtarget->is64Bit() || F64IsLegal) {
18505       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18506       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18507                                   Ld->getPointerInfo(), Ld->isVolatile(),
18508                                   Ld->isNonTemporal(), Ld->isInvariant(),
18509                                   Ld->getAlignment());
18510       SDValue NewChain = NewLd.getValue(1);
18511       if (TokenFactorIndex != -1) {
18512         Ops.push_back(NewChain);
18513         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18514                                Ops.size());
18515       }
18516       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18517                           St->getPointerInfo(),
18518                           St->isVolatile(), St->isNonTemporal(),
18519                           St->getAlignment());
18520     }
18521
18522     // Otherwise, lower to two pairs of 32-bit loads / stores.
18523     SDValue LoAddr = Ld->getBasePtr();
18524     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18525                                  DAG.getConstant(4, MVT::i32));
18526
18527     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18528                                Ld->getPointerInfo(),
18529                                Ld->isVolatile(), Ld->isNonTemporal(),
18530                                Ld->isInvariant(), Ld->getAlignment());
18531     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18532                                Ld->getPointerInfo().getWithOffset(4),
18533                                Ld->isVolatile(), Ld->isNonTemporal(),
18534                                Ld->isInvariant(),
18535                                MinAlign(Ld->getAlignment(), 4));
18536
18537     SDValue NewChain = LoLd.getValue(1);
18538     if (TokenFactorIndex != -1) {
18539       Ops.push_back(LoLd);
18540       Ops.push_back(HiLd);
18541       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18542                              Ops.size());
18543     }
18544
18545     LoAddr = St->getBasePtr();
18546     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18547                          DAG.getConstant(4, MVT::i32));
18548
18549     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18550                                 St->getPointerInfo(),
18551                                 St->isVolatile(), St->isNonTemporal(),
18552                                 St->getAlignment());
18553     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18554                                 St->getPointerInfo().getWithOffset(4),
18555                                 St->isVolatile(),
18556                                 St->isNonTemporal(),
18557                                 MinAlign(St->getAlignment(), 4));
18558     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18559   }
18560   return SDValue();
18561 }
18562
18563 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18564 /// and return the operands for the horizontal operation in LHS and RHS.  A
18565 /// horizontal operation performs the binary operation on successive elements
18566 /// of its first operand, then on successive elements of its second operand,
18567 /// returning the resulting values in a vector.  For example, if
18568 ///   A = < float a0, float a1, float a2, float a3 >
18569 /// and
18570 ///   B = < float b0, float b1, float b2, float b3 >
18571 /// then the result of doing a horizontal operation on A and B is
18572 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18573 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18574 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18575 /// set to A, RHS to B, and the routine returns 'true'.
18576 /// Note that the binary operation should have the property that if one of the
18577 /// operands is UNDEF then the result is UNDEF.
18578 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18579   // Look for the following pattern: if
18580   //   A = < float a0, float a1, float a2, float a3 >
18581   //   B = < float b0, float b1, float b2, float b3 >
18582   // and
18583   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18584   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18585   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18586   // which is A horizontal-op B.
18587
18588   // At least one of the operands should be a vector shuffle.
18589   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18590       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18591     return false;
18592
18593   MVT VT = LHS.getSimpleValueType();
18594
18595   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18596          "Unsupported vector type for horizontal add/sub");
18597
18598   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18599   // operate independently on 128-bit lanes.
18600   unsigned NumElts = VT.getVectorNumElements();
18601   unsigned NumLanes = VT.getSizeInBits()/128;
18602   unsigned NumLaneElts = NumElts / NumLanes;
18603   assert((NumLaneElts % 2 == 0) &&
18604          "Vector type should have an even number of elements in each lane");
18605   unsigned HalfLaneElts = NumLaneElts/2;
18606
18607   // View LHS in the form
18608   //   LHS = VECTOR_SHUFFLE A, B, LMask
18609   // If LHS is not a shuffle then pretend it is the shuffle
18610   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18611   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18612   // type VT.
18613   SDValue A, B;
18614   SmallVector<int, 16> LMask(NumElts);
18615   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18616     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18617       A = LHS.getOperand(0);
18618     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18619       B = LHS.getOperand(1);
18620     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18621     std::copy(Mask.begin(), Mask.end(), LMask.begin());
18622   } else {
18623     if (LHS.getOpcode() != ISD::UNDEF)
18624       A = LHS;
18625     for (unsigned i = 0; i != NumElts; ++i)
18626       LMask[i] = i;
18627   }
18628
18629   // Likewise, view RHS in the form
18630   //   RHS = VECTOR_SHUFFLE C, D, RMask
18631   SDValue C, D;
18632   SmallVector<int, 16> RMask(NumElts);
18633   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18634     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
18635       C = RHS.getOperand(0);
18636     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
18637       D = RHS.getOperand(1);
18638     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
18639     std::copy(Mask.begin(), Mask.end(), RMask.begin());
18640   } else {
18641     if (RHS.getOpcode() != ISD::UNDEF)
18642       C = RHS;
18643     for (unsigned i = 0; i != NumElts; ++i)
18644       RMask[i] = i;
18645   }
18646
18647   // Check that the shuffles are both shuffling the same vectors.
18648   if (!(A == C && B == D) && !(A == D && B == C))
18649     return false;
18650
18651   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
18652   if (!A.getNode() && !B.getNode())
18653     return false;
18654
18655   // If A and B occur in reverse order in RHS, then "swap" them (which means
18656   // rewriting the mask).
18657   if (A != C)
18658     CommuteVectorShuffleMask(RMask, NumElts);
18659
18660   // At this point LHS and RHS are equivalent to
18661   //   LHS = VECTOR_SHUFFLE A, B, LMask
18662   //   RHS = VECTOR_SHUFFLE A, B, RMask
18663   // Check that the masks correspond to performing a horizontal operation.
18664   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
18665     for (unsigned i = 0; i != NumLaneElts; ++i) {
18666       int LIdx = LMask[i+l], RIdx = RMask[i+l];
18667
18668       // Ignore any UNDEF components.
18669       if (LIdx < 0 || RIdx < 0 ||
18670           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
18671           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
18672         continue;
18673
18674       // Check that successive elements are being operated on.  If not, this is
18675       // not a horizontal operation.
18676       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
18677       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
18678       if (!(LIdx == Index && RIdx == Index + 1) &&
18679           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
18680         return false;
18681     }
18682   }
18683
18684   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
18685   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
18686   return true;
18687 }
18688
18689 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
18690 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
18691                                   const X86Subtarget *Subtarget) {
18692   EVT VT = N->getValueType(0);
18693   SDValue LHS = N->getOperand(0);
18694   SDValue RHS = N->getOperand(1);
18695
18696   // Try to synthesize horizontal adds from adds of shuffles.
18697   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18698        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18699       isHorizontalBinOp(LHS, RHS, true))
18700     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
18701   return SDValue();
18702 }
18703
18704 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
18705 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
18706                                   const X86Subtarget *Subtarget) {
18707   EVT VT = N->getValueType(0);
18708   SDValue LHS = N->getOperand(0);
18709   SDValue RHS = N->getOperand(1);
18710
18711   // Try to synthesize horizontal subs from subs of shuffles.
18712   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18713        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18714       isHorizontalBinOp(LHS, RHS, false))
18715     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18716   return SDValue();
18717 }
18718
18719 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18720 /// X86ISD::FXOR nodes.
18721 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18722   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18723   // F[X]OR(0.0, x) -> x
18724   // F[X]OR(x, 0.0) -> x
18725   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18726     if (C->getValueAPF().isPosZero())
18727       return N->getOperand(1);
18728   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18729     if (C->getValueAPF().isPosZero())
18730       return N->getOperand(0);
18731   return SDValue();
18732 }
18733
18734 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18735 /// X86ISD::FMAX nodes.
18736 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18737   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18738
18739   // Only perform optimizations if UnsafeMath is used.
18740   if (!DAG.getTarget().Options.UnsafeFPMath)
18741     return SDValue();
18742
18743   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18744   // into FMINC and FMAXC, which are Commutative operations.
18745   unsigned NewOp = 0;
18746   switch (N->getOpcode()) {
18747     default: llvm_unreachable("unknown opcode");
18748     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
18749     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
18750   }
18751
18752   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18753                      N->getOperand(0), N->getOperand(1));
18754 }
18755
18756 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18757 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18758   // FAND(0.0, x) -> 0.0
18759   // FAND(x, 0.0) -> 0.0
18760   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18761     if (C->getValueAPF().isPosZero())
18762       return N->getOperand(0);
18763   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18764     if (C->getValueAPF().isPosZero())
18765       return N->getOperand(1);
18766   return SDValue();
18767 }
18768
18769 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18770 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18771   // FANDN(x, 0.0) -> 0.0
18772   // FANDN(0.0, x) -> x
18773   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18774     if (C->getValueAPF().isPosZero())
18775       return N->getOperand(1);
18776   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18777     if (C->getValueAPF().isPosZero())
18778       return N->getOperand(1);
18779   return SDValue();
18780 }
18781
18782 static SDValue PerformBTCombine(SDNode *N,
18783                                 SelectionDAG &DAG,
18784                                 TargetLowering::DAGCombinerInfo &DCI) {
18785   // BT ignores high bits in the bit index operand.
18786   SDValue Op1 = N->getOperand(1);
18787   if (Op1.hasOneUse()) {
18788     unsigned BitWidth = Op1.getValueSizeInBits();
18789     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18790     APInt KnownZero, KnownOne;
18791     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18792                                           !DCI.isBeforeLegalizeOps());
18793     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18794     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18795         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18796       DCI.CommitTargetLoweringOpt(TLO);
18797   }
18798   return SDValue();
18799 }
18800
18801 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18802   SDValue Op = N->getOperand(0);
18803   if (Op.getOpcode() == ISD::BITCAST)
18804     Op = Op.getOperand(0);
18805   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18806   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18807       VT.getVectorElementType().getSizeInBits() ==
18808       OpVT.getVectorElementType().getSizeInBits()) {
18809     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18810   }
18811   return SDValue();
18812 }
18813
18814 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18815                                                const X86Subtarget *Subtarget) {
18816   EVT VT = N->getValueType(0);
18817   if (!VT.isVector())
18818     return SDValue();
18819
18820   SDValue N0 = N->getOperand(0);
18821   SDValue N1 = N->getOperand(1);
18822   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18823   SDLoc dl(N);
18824
18825   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18826   // both SSE and AVX2 since there is no sign-extended shift right
18827   // operation on a vector with 64-bit elements.
18828   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18829   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18830   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18831       N0.getOpcode() == ISD::SIGN_EXTEND)) {
18832     SDValue N00 = N0.getOperand(0);
18833
18834     // EXTLOAD has a better solution on AVX2,
18835     // it may be replaced with X86ISD::VSEXT node.
18836     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18837       if (!ISD::isNormalLoad(N00.getNode()))
18838         return SDValue();
18839
18840     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18841         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18842                                   N00, N1);
18843       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18844     }
18845   }
18846   return SDValue();
18847 }
18848
18849 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18850                                   TargetLowering::DAGCombinerInfo &DCI,
18851                                   const X86Subtarget *Subtarget) {
18852   if (!DCI.isBeforeLegalizeOps())
18853     return SDValue();
18854
18855   if (!Subtarget->hasFp256())
18856     return SDValue();
18857
18858   EVT VT = N->getValueType(0);
18859   if (VT.isVector() && VT.getSizeInBits() == 256) {
18860     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18861     if (R.getNode())
18862       return R;
18863   }
18864
18865   return SDValue();
18866 }
18867
18868 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18869                                  const X86Subtarget* Subtarget) {
18870   SDLoc dl(N);
18871   EVT VT = N->getValueType(0);
18872
18873   // Let legalize expand this if it isn't a legal type yet.
18874   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18875     return SDValue();
18876
18877   EVT ScalarVT = VT.getScalarType();
18878   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18879       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18880     return SDValue();
18881
18882   SDValue A = N->getOperand(0);
18883   SDValue B = N->getOperand(1);
18884   SDValue C = N->getOperand(2);
18885
18886   bool NegA = (A.getOpcode() == ISD::FNEG);
18887   bool NegB = (B.getOpcode() == ISD::FNEG);
18888   bool NegC = (C.getOpcode() == ISD::FNEG);
18889
18890   // Negative multiplication when NegA xor NegB
18891   bool NegMul = (NegA != NegB);
18892   if (NegA)
18893     A = A.getOperand(0);
18894   if (NegB)
18895     B = B.getOperand(0);
18896   if (NegC)
18897     C = C.getOperand(0);
18898
18899   unsigned Opcode;
18900   if (!NegMul)
18901     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18902   else
18903     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18904
18905   return DAG.getNode(Opcode, dl, VT, A, B, C);
18906 }
18907
18908 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18909                                   TargetLowering::DAGCombinerInfo &DCI,
18910                                   const X86Subtarget *Subtarget) {
18911   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18912   //           (and (i32 x86isd::setcc_carry), 1)
18913   // This eliminates the zext. This transformation is necessary because
18914   // ISD::SETCC is always legalized to i8.
18915   SDLoc dl(N);
18916   SDValue N0 = N->getOperand(0);
18917   EVT VT = N->getValueType(0);
18918
18919   if (N0.getOpcode() == ISD::AND &&
18920       N0.hasOneUse() &&
18921       N0.getOperand(0).hasOneUse()) {
18922     SDValue N00 = N0.getOperand(0);
18923     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18924       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18925       if (!C || C->getZExtValue() != 1)
18926         return SDValue();
18927       return DAG.getNode(ISD::AND, dl, VT,
18928                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18929                                      N00.getOperand(0), N00.getOperand(1)),
18930                          DAG.getConstant(1, VT));
18931     }
18932   }
18933
18934   if (VT.is256BitVector()) {
18935     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18936     if (R.getNode())
18937       return R;
18938   }
18939
18940   return SDValue();
18941 }
18942
18943 // Optimize x == -y --> x+y == 0
18944 //          x != -y --> x+y != 0
18945 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18946   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18947   SDValue LHS = N->getOperand(0);
18948   SDValue RHS = N->getOperand(1);
18949
18950   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18951     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18952       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18953         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18954                                    LHS.getValueType(), RHS, LHS.getOperand(1));
18955         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18956                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18957       }
18958   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18959     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18960       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18961         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18962                                    RHS.getValueType(), LHS, RHS.getOperand(1));
18963         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18964                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18965       }
18966   return SDValue();
18967 }
18968
18969 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18970 // as "sbb reg,reg", since it can be extended without zext and produces
18971 // an all-ones bit which is more useful than 0/1 in some cases.
18972 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18973   return DAG.getNode(ISD::AND, DL, MVT::i8,
18974                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18975                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18976                      DAG.getConstant(1, MVT::i8));
18977 }
18978
18979 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18980 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18981                                    TargetLowering::DAGCombinerInfo &DCI,
18982                                    const X86Subtarget *Subtarget) {
18983   SDLoc DL(N);
18984   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18985   SDValue EFLAGS = N->getOperand(1);
18986
18987   if (CC == X86::COND_A) {
18988     // Try to convert COND_A into COND_B in an attempt to facilitate
18989     // materializing "setb reg".
18990     //
18991     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18992     // cannot take an immediate as its first operand.
18993     //
18994     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18995         EFLAGS.getValueType().isInteger() &&
18996         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18997       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18998                                    EFLAGS.getNode()->getVTList(),
18999                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19000       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19001       return MaterializeSETB(DL, NewEFLAGS, DAG);
19002     }
19003   }
19004
19005   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19006   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19007   // cases.
19008   if (CC == X86::COND_B)
19009     return MaterializeSETB(DL, EFLAGS, DAG);
19010
19011   SDValue Flags;
19012
19013   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19014   if (Flags.getNode()) {
19015     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19016     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19017   }
19018
19019   return SDValue();
19020 }
19021
19022 // Optimize branch condition evaluation.
19023 //
19024 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19025                                     TargetLowering::DAGCombinerInfo &DCI,
19026                                     const X86Subtarget *Subtarget) {
19027   SDLoc DL(N);
19028   SDValue Chain = N->getOperand(0);
19029   SDValue Dest = N->getOperand(1);
19030   SDValue EFLAGS = N->getOperand(3);
19031   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19032
19033   SDValue Flags;
19034
19035   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19036   if (Flags.getNode()) {
19037     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19038     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19039                        Flags);
19040   }
19041
19042   return SDValue();
19043 }
19044
19045 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19046                                         const X86TargetLowering *XTLI) {
19047   SDValue Op0 = N->getOperand(0);
19048   EVT InVT = Op0->getValueType(0);
19049
19050   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19051   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19052     SDLoc dl(N);
19053     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19054     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19055     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19056   }
19057
19058   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19059   // a 32-bit target where SSE doesn't support i64->FP operations.
19060   if (Op0.getOpcode() == ISD::LOAD) {
19061     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19062     EVT VT = Ld->getValueType(0);
19063     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19064         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19065         !XTLI->getSubtarget()->is64Bit() &&
19066         VT == MVT::i64) {
19067       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19068                                           Ld->getChain(), Op0, DAG);
19069       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19070       return FILDChain;
19071     }
19072   }
19073   return SDValue();
19074 }
19075
19076 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19077 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19078                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19079   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19080   // the result is either zero or one (depending on the input carry bit).
19081   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19082   if (X86::isZeroNode(N->getOperand(0)) &&
19083       X86::isZeroNode(N->getOperand(1)) &&
19084       // We don't have a good way to replace an EFLAGS use, so only do this when
19085       // dead right now.
19086       SDValue(N, 1).use_empty()) {
19087     SDLoc DL(N);
19088     EVT VT = N->getValueType(0);
19089     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19090     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19091                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19092                                            DAG.getConstant(X86::COND_B,MVT::i8),
19093                                            N->getOperand(2)),
19094                                DAG.getConstant(1, VT));
19095     return DCI.CombineTo(N, Res1, CarryOut);
19096   }
19097
19098   return SDValue();
19099 }
19100
19101 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19102 //      (add Y, (setne X, 0)) -> sbb -1, Y
19103 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19104 //      (sub (setne X, 0), Y) -> adc -1, Y
19105 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19106   SDLoc DL(N);
19107
19108   // Look through ZExts.
19109   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19110   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19111     return SDValue();
19112
19113   SDValue SetCC = Ext.getOperand(0);
19114   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19115     return SDValue();
19116
19117   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19118   if (CC != X86::COND_E && CC != X86::COND_NE)
19119     return SDValue();
19120
19121   SDValue Cmp = SetCC.getOperand(1);
19122   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19123       !X86::isZeroNode(Cmp.getOperand(1)) ||
19124       !Cmp.getOperand(0).getValueType().isInteger())
19125     return SDValue();
19126
19127   SDValue CmpOp0 = Cmp.getOperand(0);
19128   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19129                                DAG.getConstant(1, CmpOp0.getValueType()));
19130
19131   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19132   if (CC == X86::COND_NE)
19133     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19134                        DL, OtherVal.getValueType(), OtherVal,
19135                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19136   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19137                      DL, OtherVal.getValueType(), OtherVal,
19138                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19139 }
19140
19141 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19142 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19143                                  const X86Subtarget *Subtarget) {
19144   EVT VT = N->getValueType(0);
19145   SDValue Op0 = N->getOperand(0);
19146   SDValue Op1 = N->getOperand(1);
19147
19148   // Try to synthesize horizontal adds from adds of shuffles.
19149   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19150        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19151       isHorizontalBinOp(Op0, Op1, true))
19152     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19153
19154   return OptimizeConditionalInDecrement(N, DAG);
19155 }
19156
19157 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19158                                  const X86Subtarget *Subtarget) {
19159   SDValue Op0 = N->getOperand(0);
19160   SDValue Op1 = N->getOperand(1);
19161
19162   // X86 can't encode an immediate LHS of a sub. See if we can push the
19163   // negation into a preceding instruction.
19164   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19165     // If the RHS of the sub is a XOR with one use and a constant, invert the
19166     // immediate. Then add one to the LHS of the sub so we can turn
19167     // X-Y -> X+~Y+1, saving one register.
19168     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19169         isa<ConstantSDNode>(Op1.getOperand(1))) {
19170       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19171       EVT VT = Op0.getValueType();
19172       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19173                                    Op1.getOperand(0),
19174                                    DAG.getConstant(~XorC, VT));
19175       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19176                          DAG.getConstant(C->getAPIntValue()+1, VT));
19177     }
19178   }
19179
19180   // Try to synthesize horizontal adds from adds of shuffles.
19181   EVT VT = N->getValueType(0);
19182   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19183        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19184       isHorizontalBinOp(Op0, Op1, true))
19185     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19186
19187   return OptimizeConditionalInDecrement(N, DAG);
19188 }
19189
19190 /// performVZEXTCombine - Performs build vector combines
19191 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19192                                         TargetLowering::DAGCombinerInfo &DCI,
19193                                         const X86Subtarget *Subtarget) {
19194   // (vzext (bitcast (vzext (x)) -> (vzext x)
19195   SDValue In = N->getOperand(0);
19196   while (In.getOpcode() == ISD::BITCAST)
19197     In = In.getOperand(0);
19198
19199   if (In.getOpcode() != X86ISD::VZEXT)
19200     return SDValue();
19201
19202   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19203                      In.getOperand(0));
19204 }
19205
19206 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19207                                              DAGCombinerInfo &DCI) const {
19208   SelectionDAG &DAG = DCI.DAG;
19209   switch (N->getOpcode()) {
19210   default: break;
19211   case ISD::EXTRACT_VECTOR_ELT:
19212     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19213   case ISD::VSELECT:
19214   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19215   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19216   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19217   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19218   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19219   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19220   case ISD::SHL:
19221   case ISD::SRA:
19222   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19223   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19224   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19225   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19226   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19227   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19228   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19229   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19230   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19231   case X86ISD::FXOR:
19232   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19233   case X86ISD::FMIN:
19234   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19235   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19236   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19237   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19238   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19239   case ISD::ANY_EXTEND:
19240   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19241   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19242   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19243   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19244   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
19245   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19246   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19247   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19248   case X86ISD::SHUFP:       // Handle all target specific shuffles
19249   case X86ISD::PALIGNR:
19250   case X86ISD::UNPCKH:
19251   case X86ISD::UNPCKL:
19252   case X86ISD::MOVHLPS:
19253   case X86ISD::MOVLHPS:
19254   case X86ISD::PSHUFD:
19255   case X86ISD::PSHUFHW:
19256   case X86ISD::PSHUFLW:
19257   case X86ISD::MOVSS:
19258   case X86ISD::MOVSD:
19259   case X86ISD::VPERMILP:
19260   case X86ISD::VPERM2X128:
19261   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19262   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19263   }
19264
19265   return SDValue();
19266 }
19267
19268 /// isTypeDesirableForOp - Return true if the target has native support for
19269 /// the specified value type and it is 'desirable' to use the type for the
19270 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19271 /// instruction encodings are longer and some i16 instructions are slow.
19272 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19273   if (!isTypeLegal(VT))
19274     return false;
19275   if (VT != MVT::i16)
19276     return true;
19277
19278   switch (Opc) {
19279   default:
19280     return true;
19281   case ISD::LOAD:
19282   case ISD::SIGN_EXTEND:
19283   case ISD::ZERO_EXTEND:
19284   case ISD::ANY_EXTEND:
19285   case ISD::SHL:
19286   case ISD::SRL:
19287   case ISD::SUB:
19288   case ISD::ADD:
19289   case ISD::MUL:
19290   case ISD::AND:
19291   case ISD::OR:
19292   case ISD::XOR:
19293     return false;
19294   }
19295 }
19296
19297 /// IsDesirableToPromoteOp - This method query the target whether it is
19298 /// beneficial for dag combiner to promote the specified node. If true, it
19299 /// should return the desired promotion type by reference.
19300 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19301   EVT VT = Op.getValueType();
19302   if (VT != MVT::i16)
19303     return false;
19304
19305   bool Promote = false;
19306   bool Commute = false;
19307   switch (Op.getOpcode()) {
19308   default: break;
19309   case ISD::LOAD: {
19310     LoadSDNode *LD = cast<LoadSDNode>(Op);
19311     // If the non-extending load has a single use and it's not live out, then it
19312     // might be folded.
19313     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19314                                                      Op.hasOneUse()*/) {
19315       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19316              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19317         // The only case where we'd want to promote LOAD (rather then it being
19318         // promoted as an operand is when it's only use is liveout.
19319         if (UI->getOpcode() != ISD::CopyToReg)
19320           return false;
19321       }
19322     }
19323     Promote = true;
19324     break;
19325   }
19326   case ISD::SIGN_EXTEND:
19327   case ISD::ZERO_EXTEND:
19328   case ISD::ANY_EXTEND:
19329     Promote = true;
19330     break;
19331   case ISD::SHL:
19332   case ISD::SRL: {
19333     SDValue N0 = Op.getOperand(0);
19334     // Look out for (store (shl (load), x)).
19335     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19336       return false;
19337     Promote = true;
19338     break;
19339   }
19340   case ISD::ADD:
19341   case ISD::MUL:
19342   case ISD::AND:
19343   case ISD::OR:
19344   case ISD::XOR:
19345     Commute = true;
19346     // fallthrough
19347   case ISD::SUB: {
19348     SDValue N0 = Op.getOperand(0);
19349     SDValue N1 = Op.getOperand(1);
19350     if (!Commute && MayFoldLoad(N1))
19351       return false;
19352     // Avoid disabling potential load folding opportunities.
19353     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19354       return false;
19355     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19356       return false;
19357     Promote = true;
19358   }
19359   }
19360
19361   PVT = MVT::i32;
19362   return Promote;
19363 }
19364
19365 //===----------------------------------------------------------------------===//
19366 //                           X86 Inline Assembly Support
19367 //===----------------------------------------------------------------------===//
19368
19369 namespace {
19370   // Helper to match a string separated by whitespace.
19371   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19372     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19373
19374     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19375       StringRef piece(*args[i]);
19376       if (!s.startswith(piece)) // Check if the piece matches.
19377         return false;
19378
19379       s = s.substr(piece.size());
19380       StringRef::size_type pos = s.find_first_not_of(" \t");
19381       if (pos == 0) // We matched a prefix.
19382         return false;
19383
19384       s = s.substr(pos);
19385     }
19386
19387     return s.empty();
19388   }
19389   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19390 }
19391
19392 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19393
19394   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19395     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19396         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19397         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19398
19399       if (AsmPieces.size() == 3)
19400         return true;
19401       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19402         return true;
19403     }
19404   }
19405   return false;
19406 }
19407
19408 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19409   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19410
19411   std::string AsmStr = IA->getAsmString();
19412
19413   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19414   if (!Ty || Ty->getBitWidth() % 16 != 0)
19415     return false;
19416
19417   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19418   SmallVector<StringRef, 4> AsmPieces;
19419   SplitString(AsmStr, AsmPieces, ";\n");
19420
19421   switch (AsmPieces.size()) {
19422   default: return false;
19423   case 1:
19424     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19425     // we will turn this bswap into something that will be lowered to logical
19426     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19427     // lower so don't worry about this.
19428     // bswap $0
19429     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19430         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19431         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19432         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19433         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19434         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19435       // No need to check constraints, nothing other than the equivalent of
19436       // "=r,0" would be valid here.
19437       return IntrinsicLowering::LowerToByteSwap(CI);
19438     }
19439
19440     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19441     if (CI->getType()->isIntegerTy(16) &&
19442         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19443         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19444          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19445       AsmPieces.clear();
19446       const std::string &ConstraintsStr = IA->getConstraintString();
19447       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19448       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19449       if (clobbersFlagRegisters(AsmPieces))
19450         return IntrinsicLowering::LowerToByteSwap(CI);
19451     }
19452     break;
19453   case 3:
19454     if (CI->getType()->isIntegerTy(32) &&
19455         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19456         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19457         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19458         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19459       AsmPieces.clear();
19460       const std::string &ConstraintsStr = IA->getConstraintString();
19461       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19462       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19463       if (clobbersFlagRegisters(AsmPieces))
19464         return IntrinsicLowering::LowerToByteSwap(CI);
19465     }
19466
19467     if (CI->getType()->isIntegerTy(64)) {
19468       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19469       if (Constraints.size() >= 2 &&
19470           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19471           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19472         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19473         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19474             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19475             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19476           return IntrinsicLowering::LowerToByteSwap(CI);
19477       }
19478     }
19479     break;
19480   }
19481   return false;
19482 }
19483
19484 /// getConstraintType - Given a constraint letter, return the type of
19485 /// constraint it is for this target.
19486 X86TargetLowering::ConstraintType
19487 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19488   if (Constraint.size() == 1) {
19489     switch (Constraint[0]) {
19490     case 'R':
19491     case 'q':
19492     case 'Q':
19493     case 'f':
19494     case 't':
19495     case 'u':
19496     case 'y':
19497     case 'x':
19498     case 'Y':
19499     case 'l':
19500       return C_RegisterClass;
19501     case 'a':
19502     case 'b':
19503     case 'c':
19504     case 'd':
19505     case 'S':
19506     case 'D':
19507     case 'A':
19508       return C_Register;
19509     case 'I':
19510     case 'J':
19511     case 'K':
19512     case 'L':
19513     case 'M':
19514     case 'N':
19515     case 'G':
19516     case 'C':
19517     case 'e':
19518     case 'Z':
19519       return C_Other;
19520     default:
19521       break;
19522     }
19523   }
19524   return TargetLowering::getConstraintType(Constraint);
19525 }
19526
19527 /// Examine constraint type and operand type and determine a weight value.
19528 /// This object must already have been set up with the operand type
19529 /// and the current alternative constraint selected.
19530 TargetLowering::ConstraintWeight
19531   X86TargetLowering::getSingleConstraintMatchWeight(
19532     AsmOperandInfo &info, const char *constraint) const {
19533   ConstraintWeight weight = CW_Invalid;
19534   Value *CallOperandVal = info.CallOperandVal;
19535     // If we don't have a value, we can't do a match,
19536     // but allow it at the lowest weight.
19537   if (CallOperandVal == NULL)
19538     return CW_Default;
19539   Type *type = CallOperandVal->getType();
19540   // Look at the constraint type.
19541   switch (*constraint) {
19542   default:
19543     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19544   case 'R':
19545   case 'q':
19546   case 'Q':
19547   case 'a':
19548   case 'b':
19549   case 'c':
19550   case 'd':
19551   case 'S':
19552   case 'D':
19553   case 'A':
19554     if (CallOperandVal->getType()->isIntegerTy())
19555       weight = CW_SpecificReg;
19556     break;
19557   case 'f':
19558   case 't':
19559   case 'u':
19560     if (type->isFloatingPointTy())
19561       weight = CW_SpecificReg;
19562     break;
19563   case 'y':
19564     if (type->isX86_MMXTy() && Subtarget->hasMMX())
19565       weight = CW_SpecificReg;
19566     break;
19567   case 'x':
19568   case 'Y':
19569     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19570         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19571       weight = CW_Register;
19572     break;
19573   case 'I':
19574     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19575       if (C->getZExtValue() <= 31)
19576         weight = CW_Constant;
19577     }
19578     break;
19579   case 'J':
19580     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19581       if (C->getZExtValue() <= 63)
19582         weight = CW_Constant;
19583     }
19584     break;
19585   case 'K':
19586     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19587       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
19588         weight = CW_Constant;
19589     }
19590     break;
19591   case 'L':
19592     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19593       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
19594         weight = CW_Constant;
19595     }
19596     break;
19597   case 'M':
19598     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19599       if (C->getZExtValue() <= 3)
19600         weight = CW_Constant;
19601     }
19602     break;
19603   case 'N':
19604     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19605       if (C->getZExtValue() <= 0xff)
19606         weight = CW_Constant;
19607     }
19608     break;
19609   case 'G':
19610   case 'C':
19611     if (dyn_cast<ConstantFP>(CallOperandVal)) {
19612       weight = CW_Constant;
19613     }
19614     break;
19615   case 'e':
19616     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19617       if ((C->getSExtValue() >= -0x80000000LL) &&
19618           (C->getSExtValue() <= 0x7fffffffLL))
19619         weight = CW_Constant;
19620     }
19621     break;
19622   case 'Z':
19623     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19624       if (C->getZExtValue() <= 0xffffffff)
19625         weight = CW_Constant;
19626     }
19627     break;
19628   }
19629   return weight;
19630 }
19631
19632 /// LowerXConstraint - try to replace an X constraint, which matches anything,
19633 /// with another that has more specific requirements based on the type of the
19634 /// corresponding operand.
19635 const char *X86TargetLowering::
19636 LowerXConstraint(EVT ConstraintVT) const {
19637   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
19638   // 'f' like normal targets.
19639   if (ConstraintVT.isFloatingPoint()) {
19640     if (Subtarget->hasSSE2())
19641       return "Y";
19642     if (Subtarget->hasSSE1())
19643       return "x";
19644   }
19645
19646   return TargetLowering::LowerXConstraint(ConstraintVT);
19647 }
19648
19649 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19650 /// vector.  If it is invalid, don't add anything to Ops.
19651 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19652                                                      std::string &Constraint,
19653                                                      std::vector<SDValue>&Ops,
19654                                                      SelectionDAG &DAG) const {
19655   SDValue Result(0, 0);
19656
19657   // Only support length 1 constraints for now.
19658   if (Constraint.length() > 1) return;
19659
19660   char ConstraintLetter = Constraint[0];
19661   switch (ConstraintLetter) {
19662   default: break;
19663   case 'I':
19664     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19665       if (C->getZExtValue() <= 31) {
19666         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19667         break;
19668       }
19669     }
19670     return;
19671   case 'J':
19672     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19673       if (C->getZExtValue() <= 63) {
19674         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19675         break;
19676       }
19677     }
19678     return;
19679   case 'K':
19680     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19681       if (isInt<8>(C->getSExtValue())) {
19682         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19683         break;
19684       }
19685     }
19686     return;
19687   case 'N':
19688     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19689       if (C->getZExtValue() <= 255) {
19690         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19691         break;
19692       }
19693     }
19694     return;
19695   case 'e': {
19696     // 32-bit signed value
19697     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19698       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19699                                            C->getSExtValue())) {
19700         // Widen to 64 bits here to get it sign extended.
19701         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
19702         break;
19703       }
19704     // FIXME gcc accepts some relocatable values here too, but only in certain
19705     // memory models; it's complicated.
19706     }
19707     return;
19708   }
19709   case 'Z': {
19710     // 32-bit unsigned value
19711     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19712       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19713                                            C->getZExtValue())) {
19714         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19715         break;
19716       }
19717     }
19718     // FIXME gcc accepts some relocatable values here too, but only in certain
19719     // memory models; it's complicated.
19720     return;
19721   }
19722   case 'i': {
19723     // Literal immediates are always ok.
19724     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19725       // Widen to 64 bits here to get it sign extended.
19726       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19727       break;
19728     }
19729
19730     // In any sort of PIC mode addresses need to be computed at runtime by
19731     // adding in a register or some sort of table lookup.  These can't
19732     // be used as immediates.
19733     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19734       return;
19735
19736     // If we are in non-pic codegen mode, we allow the address of a global (with
19737     // an optional displacement) to be used with 'i'.
19738     GlobalAddressSDNode *GA = 0;
19739     int64_t Offset = 0;
19740
19741     // Match either (GA), (GA+C), (GA+C1+C2), etc.
19742     while (1) {
19743       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19744         Offset += GA->getOffset();
19745         break;
19746       } else if (Op.getOpcode() == ISD::ADD) {
19747         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19748           Offset += C->getZExtValue();
19749           Op = Op.getOperand(0);
19750           continue;
19751         }
19752       } else if (Op.getOpcode() == ISD::SUB) {
19753         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19754           Offset += -C->getZExtValue();
19755           Op = Op.getOperand(0);
19756           continue;
19757         }
19758       }
19759
19760       // Otherwise, this isn't something we can handle, reject it.
19761       return;
19762     }
19763
19764     const GlobalValue *GV = GA->getGlobal();
19765     // If we require an extra load to get this address, as in PIC mode, we
19766     // can't accept it.
19767     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19768                                                         getTargetMachine())))
19769       return;
19770
19771     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19772                                         GA->getValueType(0), Offset);
19773     break;
19774   }
19775   }
19776
19777   if (Result.getNode()) {
19778     Ops.push_back(Result);
19779     return;
19780   }
19781   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19782 }
19783
19784 std::pair<unsigned, const TargetRegisterClass*>
19785 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19786                                                 MVT VT) const {
19787   // First, see if this is a constraint that directly corresponds to an LLVM
19788   // register class.
19789   if (Constraint.size() == 1) {
19790     // GCC Constraint Letters
19791     switch (Constraint[0]) {
19792     default: break;
19793       // TODO: Slight differences here in allocation order and leaving
19794       // RIP in the class. Do they matter any more here than they do
19795       // in the normal allocation?
19796     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19797       if (Subtarget->is64Bit()) {
19798         if (VT == MVT::i32 || VT == MVT::f32)
19799           return std::make_pair(0U, &X86::GR32RegClass);
19800         if (VT == MVT::i16)
19801           return std::make_pair(0U, &X86::GR16RegClass);
19802         if (VT == MVT::i8 || VT == MVT::i1)
19803           return std::make_pair(0U, &X86::GR8RegClass);
19804         if (VT == MVT::i64 || VT == MVT::f64)
19805           return std::make_pair(0U, &X86::GR64RegClass);
19806         break;
19807       }
19808       // 32-bit fallthrough
19809     case 'Q':   // Q_REGS
19810       if (VT == MVT::i32 || VT == MVT::f32)
19811         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19812       if (VT == MVT::i16)
19813         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19814       if (VT == MVT::i8 || VT == MVT::i1)
19815         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19816       if (VT == MVT::i64)
19817         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19818       break;
19819     case 'r':   // GENERAL_REGS
19820     case 'l':   // INDEX_REGS
19821       if (VT == MVT::i8 || VT == MVT::i1)
19822         return std::make_pair(0U, &X86::GR8RegClass);
19823       if (VT == MVT::i16)
19824         return std::make_pair(0U, &X86::GR16RegClass);
19825       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19826         return std::make_pair(0U, &X86::GR32RegClass);
19827       return std::make_pair(0U, &X86::GR64RegClass);
19828     case 'R':   // LEGACY_REGS
19829       if (VT == MVT::i8 || VT == MVT::i1)
19830         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19831       if (VT == MVT::i16)
19832         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19833       if (VT == MVT::i32 || !Subtarget->is64Bit())
19834         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19835       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19836     case 'f':  // FP Stack registers.
19837       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19838       // value to the correct fpstack register class.
19839       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19840         return std::make_pair(0U, &X86::RFP32RegClass);
19841       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19842         return std::make_pair(0U, &X86::RFP64RegClass);
19843       return std::make_pair(0U, &X86::RFP80RegClass);
19844     case 'y':   // MMX_REGS if MMX allowed.
19845       if (!Subtarget->hasMMX()) break;
19846       return std::make_pair(0U, &X86::VR64RegClass);
19847     case 'Y':   // SSE_REGS if SSE2 allowed
19848       if (!Subtarget->hasSSE2()) break;
19849       // FALL THROUGH.
19850     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19851       if (!Subtarget->hasSSE1()) break;
19852
19853       switch (VT.SimpleTy) {
19854       default: break;
19855       // Scalar SSE types.
19856       case MVT::f32:
19857       case MVT::i32:
19858         return std::make_pair(0U, &X86::FR32RegClass);
19859       case MVT::f64:
19860       case MVT::i64:
19861         return std::make_pair(0U, &X86::FR64RegClass);
19862       // Vector types.
19863       case MVT::v16i8:
19864       case MVT::v8i16:
19865       case MVT::v4i32:
19866       case MVT::v2i64:
19867       case MVT::v4f32:
19868       case MVT::v2f64:
19869         return std::make_pair(0U, &X86::VR128RegClass);
19870       // AVX types.
19871       case MVT::v32i8:
19872       case MVT::v16i16:
19873       case MVT::v8i32:
19874       case MVT::v4i64:
19875       case MVT::v8f32:
19876       case MVT::v4f64:
19877         return std::make_pair(0U, &X86::VR256RegClass);
19878       case MVT::v8f64:
19879       case MVT::v16f32:
19880       case MVT::v16i32:
19881       case MVT::v8i64:
19882         return std::make_pair(0U, &X86::VR512RegClass);
19883       }
19884       break;
19885     }
19886   }
19887
19888   // Use the default implementation in TargetLowering to convert the register
19889   // constraint into a member of a register class.
19890   std::pair<unsigned, const TargetRegisterClass*> Res;
19891   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19892
19893   // Not found as a standard register?
19894   if (Res.second == 0) {
19895     // Map st(0) -> st(7) -> ST0
19896     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19897         tolower(Constraint[1]) == 's' &&
19898         tolower(Constraint[2]) == 't' &&
19899         Constraint[3] == '(' &&
19900         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19901         Constraint[5] == ')' &&
19902         Constraint[6] == '}') {
19903
19904       Res.first = X86::ST0+Constraint[4]-'0';
19905       Res.second = &X86::RFP80RegClass;
19906       return Res;
19907     }
19908
19909     // GCC allows "st(0)" to be called just plain "st".
19910     if (StringRef("{st}").equals_lower(Constraint)) {
19911       Res.first = X86::ST0;
19912       Res.second = &X86::RFP80RegClass;
19913       return Res;
19914     }
19915
19916     // flags -> EFLAGS
19917     if (StringRef("{flags}").equals_lower(Constraint)) {
19918       Res.first = X86::EFLAGS;
19919       Res.second = &X86::CCRRegClass;
19920       return Res;
19921     }
19922
19923     // 'A' means EAX + EDX.
19924     if (Constraint == "A") {
19925       Res.first = X86::EAX;
19926       Res.second = &X86::GR32_ADRegClass;
19927       return Res;
19928     }
19929     return Res;
19930   }
19931
19932   // Otherwise, check to see if this is a register class of the wrong value
19933   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19934   // turn into {ax},{dx}.
19935   if (Res.second->hasType(VT))
19936     return Res;   // Correct type already, nothing to do.
19937
19938   // All of the single-register GCC register classes map their values onto
19939   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
19940   // really want an 8-bit or 32-bit register, map to the appropriate register
19941   // class and return the appropriate register.
19942   if (Res.second == &X86::GR16RegClass) {
19943     if (VT == MVT::i8 || VT == MVT::i1) {
19944       unsigned DestReg = 0;
19945       switch (Res.first) {
19946       default: break;
19947       case X86::AX: DestReg = X86::AL; break;
19948       case X86::DX: DestReg = X86::DL; break;
19949       case X86::CX: DestReg = X86::CL; break;
19950       case X86::BX: DestReg = X86::BL; break;
19951       }
19952       if (DestReg) {
19953         Res.first = DestReg;
19954         Res.second = &X86::GR8RegClass;
19955       }
19956     } else if (VT == MVT::i32 || VT == MVT::f32) {
19957       unsigned DestReg = 0;
19958       switch (Res.first) {
19959       default: break;
19960       case X86::AX: DestReg = X86::EAX; break;
19961       case X86::DX: DestReg = X86::EDX; break;
19962       case X86::CX: DestReg = X86::ECX; break;
19963       case X86::BX: DestReg = X86::EBX; break;
19964       case X86::SI: DestReg = X86::ESI; break;
19965       case X86::DI: DestReg = X86::EDI; break;
19966       case X86::BP: DestReg = X86::EBP; break;
19967       case X86::SP: DestReg = X86::ESP; break;
19968       }
19969       if (DestReg) {
19970         Res.first = DestReg;
19971         Res.second = &X86::GR32RegClass;
19972       }
19973     } else if (VT == MVT::i64 || VT == MVT::f64) {
19974       unsigned DestReg = 0;
19975       switch (Res.first) {
19976       default: break;
19977       case X86::AX: DestReg = X86::RAX; break;
19978       case X86::DX: DestReg = X86::RDX; break;
19979       case X86::CX: DestReg = X86::RCX; break;
19980       case X86::BX: DestReg = X86::RBX; break;
19981       case X86::SI: DestReg = X86::RSI; break;
19982       case X86::DI: DestReg = X86::RDI; break;
19983       case X86::BP: DestReg = X86::RBP; break;
19984       case X86::SP: DestReg = X86::RSP; break;
19985       }
19986       if (DestReg) {
19987         Res.first = DestReg;
19988         Res.second = &X86::GR64RegClass;
19989       }
19990     }
19991   } else if (Res.second == &X86::FR32RegClass ||
19992              Res.second == &X86::FR64RegClass ||
19993              Res.second == &X86::VR128RegClass ||
19994              Res.second == &X86::VR256RegClass ||
19995              Res.second == &X86::FR32XRegClass ||
19996              Res.second == &X86::FR64XRegClass ||
19997              Res.second == &X86::VR128XRegClass ||
19998              Res.second == &X86::VR256XRegClass ||
19999              Res.second == &X86::VR512RegClass) {
20000     // Handle references to XMM physical registers that got mapped into the
20001     // wrong class.  This can happen with constraints like {xmm0} where the
20002     // target independent register mapper will just pick the first match it can
20003     // find, ignoring the required type.
20004
20005     if (VT == MVT::f32 || VT == MVT::i32)
20006       Res.second = &X86::FR32RegClass;
20007     else if (VT == MVT::f64 || VT == MVT::i64)
20008       Res.second = &X86::FR64RegClass;
20009     else if (X86::VR128RegClass.hasType(VT))
20010       Res.second = &X86::VR128RegClass;
20011     else if (X86::VR256RegClass.hasType(VT))
20012       Res.second = &X86::VR256RegClass;
20013     else if (X86::VR512RegClass.hasType(VT))
20014       Res.second = &X86::VR512RegClass;
20015   }
20016
20017   return Res;
20018 }