AVX-512: fixed some patterns for MVT::i1
[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     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1317     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1318     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1323     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1324
1325     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1329     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1330     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1331
1332     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1336     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1337     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1338     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1339     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1340     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1341
1342     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1343     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1344     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1346     if (Subtarget->is64Bit()) {
1347       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1348       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1349       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1350       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1351     }
1352     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1353     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1355     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1358     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1359     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1360
1361     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1362     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1363     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1364     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1365     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1366     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1367     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1368     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1369     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1370     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1371     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1372     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1373
1374     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1375     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1376     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1377     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1378     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1379     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1380
1381     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1382     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1383
1384     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1385
1386     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1387     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1388     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1389     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1390     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1391     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1392     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1393
1394     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1395     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1396
1397     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1398     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1399
1400     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1401
1402     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1403     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1404
1405     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1406     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1407
1408     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1409     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1410
1411     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1412     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1413     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1414     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1415     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1416     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1417
1418     // Custom lower several nodes.
1419     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1420              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1421       MVT VT = (MVT::SimpleValueType)i;
1422
1423       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1424       // Extract subvector is special because the value type
1425       // (result) is 256/128-bit but the source is 512-bit wide.
1426       if (VT.is128BitVector() || VT.is256BitVector())
1427         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1428
1429       if (VT.getVectorElementType() == MVT::i1)
1430         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1431
1432       // Do not attempt to custom lower other non-512-bit vectors
1433       if (!VT.is512BitVector())
1434         continue;
1435
1436       if ( EltSize >= 32) {
1437         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1438         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1439         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1440         setOperationAction(ISD::VSELECT,             VT, Legal);
1441         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1442         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1443         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1444       }
1445     }
1446     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1447       MVT VT = (MVT::SimpleValueType)i;
1448
1449       // Do not attempt to promote non-256-bit vectors
1450       if (!VT.is512BitVector())
1451         continue;
1452
1453       setOperationAction(ISD::SELECT, VT, Promote);
1454       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1455     }
1456   }// has  AVX-512
1457
1458   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1459   // of this type with custom code.
1460   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1461            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1462     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1463                        Custom);
1464   }
1465
1466   // We want to custom lower some of our intrinsics.
1467   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1468   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1469   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1470
1471   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1472   // handle type legalization for these operations here.
1473   //
1474   // FIXME: We really should do custom legalization for addition and
1475   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1476   // than generic legalization for 64-bit multiplication-with-overflow, though.
1477   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1478     // Add/Sub/Mul with overflow operations are custom lowered.
1479     MVT VT = IntVTs[i];
1480     setOperationAction(ISD::SADDO, VT, Custom);
1481     setOperationAction(ISD::UADDO, VT, Custom);
1482     setOperationAction(ISD::SSUBO, VT, Custom);
1483     setOperationAction(ISD::USUBO, VT, Custom);
1484     setOperationAction(ISD::SMULO, VT, Custom);
1485     setOperationAction(ISD::UMULO, VT, Custom);
1486   }
1487
1488   // There are no 8-bit 3-address imul/mul instructions
1489   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1490   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1491
1492   if (!Subtarget->is64Bit()) {
1493     // These libcalls are not available in 32-bit.
1494     setLibcallName(RTLIB::SHL_I128, 0);
1495     setLibcallName(RTLIB::SRL_I128, 0);
1496     setLibcallName(RTLIB::SRA_I128, 0);
1497   }
1498
1499   // Combine sin / cos into one node or libcall if possible.
1500   if (Subtarget->hasSinCos()) {
1501     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1502     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1503     if (Subtarget->isTargetDarwin()) {
1504       // For MacOSX, we don't want to the normal expansion of a libcall to
1505       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1506       // traffic.
1507       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1508       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1509     }
1510   }
1511
1512   // We have target-specific dag combine patterns for the following nodes:
1513   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1514   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1515   setTargetDAGCombine(ISD::VSELECT);
1516   setTargetDAGCombine(ISD::SELECT);
1517   setTargetDAGCombine(ISD::SHL);
1518   setTargetDAGCombine(ISD::SRA);
1519   setTargetDAGCombine(ISD::SRL);
1520   setTargetDAGCombine(ISD::OR);
1521   setTargetDAGCombine(ISD::AND);
1522   setTargetDAGCombine(ISD::ADD);
1523   setTargetDAGCombine(ISD::FADD);
1524   setTargetDAGCombine(ISD::FSUB);
1525   setTargetDAGCombine(ISD::FMA);
1526   setTargetDAGCombine(ISD::SUB);
1527   setTargetDAGCombine(ISD::LOAD);
1528   setTargetDAGCombine(ISD::STORE);
1529   setTargetDAGCombine(ISD::ZERO_EXTEND);
1530   setTargetDAGCombine(ISD::ANY_EXTEND);
1531   setTargetDAGCombine(ISD::SIGN_EXTEND);
1532   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1533   setTargetDAGCombine(ISD::TRUNCATE);
1534   setTargetDAGCombine(ISD::SINT_TO_FP);
1535   setTargetDAGCombine(ISD::SETCC);
1536   if (Subtarget->is64Bit())
1537     setTargetDAGCombine(ISD::MUL);
1538   setTargetDAGCombine(ISD::XOR);
1539
1540   computeRegisterProperties();
1541
1542   // On Darwin, -Os means optimize for size without hurting performance,
1543   // do not reduce the limit.
1544   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1545   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1546   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1547   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1548   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1549   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1550   setPrefLoopAlignment(4); // 2^4 bytes.
1551
1552   // Predictable cmov don't hurt on atom because it's in-order.
1553   PredictableSelectIsExpensive = !Subtarget->isAtom();
1554
1555   setPrefFunctionAlignment(4); // 2^4 bytes.
1556 }
1557
1558 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1559   if (!VT.isVector())
1560     return MVT::i8;
1561
1562   const TargetMachine &TM = getTargetMachine();
1563   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512())
1564     switch(VT.getVectorNumElements()) {
1565     case  8: return MVT::v8i1;
1566     case 16: return MVT::v16i1;
1567     }
1568
1569   return VT.changeVectorElementTypeToInteger();
1570 }
1571
1572 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1573 /// the desired ByVal argument alignment.
1574 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1575   if (MaxAlign == 16)
1576     return;
1577   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1578     if (VTy->getBitWidth() == 128)
1579       MaxAlign = 16;
1580   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1581     unsigned EltAlign = 0;
1582     getMaxByValAlign(ATy->getElementType(), EltAlign);
1583     if (EltAlign > MaxAlign)
1584       MaxAlign = EltAlign;
1585   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1586     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1587       unsigned EltAlign = 0;
1588       getMaxByValAlign(STy->getElementType(i), EltAlign);
1589       if (EltAlign > MaxAlign)
1590         MaxAlign = EltAlign;
1591       if (MaxAlign == 16)
1592         break;
1593     }
1594   }
1595 }
1596
1597 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1598 /// function arguments in the caller parameter area. For X86, aggregates
1599 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1600 /// are at 4-byte boundaries.
1601 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1602   if (Subtarget->is64Bit()) {
1603     // Max of 8 and alignment of type.
1604     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1605     if (TyAlign > 8)
1606       return TyAlign;
1607     return 8;
1608   }
1609
1610   unsigned Align = 4;
1611   if (Subtarget->hasSSE1())
1612     getMaxByValAlign(Ty, Align);
1613   return Align;
1614 }
1615
1616 /// getOptimalMemOpType - Returns the target specific optimal type for load
1617 /// and store operations as a result of memset, memcpy, and memmove
1618 /// lowering. If DstAlign is zero that means it's safe to destination
1619 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1620 /// means there isn't a need to check it against alignment requirement,
1621 /// probably because the source does not need to be loaded. If 'IsMemset' is
1622 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1623 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1624 /// source is constant so it does not need to be loaded.
1625 /// It returns EVT::Other if the type should be determined using generic
1626 /// target-independent logic.
1627 EVT
1628 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1629                                        unsigned DstAlign, unsigned SrcAlign,
1630                                        bool IsMemset, bool ZeroMemset,
1631                                        bool MemcpyStrSrc,
1632                                        MachineFunction &MF) const {
1633   const Function *F = MF.getFunction();
1634   if ((!IsMemset || ZeroMemset) &&
1635       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1636                                        Attribute::NoImplicitFloat)) {
1637     if (Size >= 16 &&
1638         (Subtarget->isUnalignedMemAccessFast() ||
1639          ((DstAlign == 0 || DstAlign >= 16) &&
1640           (SrcAlign == 0 || SrcAlign >= 16)))) {
1641       if (Size >= 32) {
1642         if (Subtarget->hasInt256())
1643           return MVT::v8i32;
1644         if (Subtarget->hasFp256())
1645           return MVT::v8f32;
1646       }
1647       if (Subtarget->hasSSE2())
1648         return MVT::v4i32;
1649       if (Subtarget->hasSSE1())
1650         return MVT::v4f32;
1651     } else if (!MemcpyStrSrc && Size >= 8 &&
1652                !Subtarget->is64Bit() &&
1653                Subtarget->hasSSE2()) {
1654       // Do not use f64 to lower memcpy if source is string constant. It's
1655       // better to use i32 to avoid the loads.
1656       return MVT::f64;
1657     }
1658   }
1659   if (Subtarget->is64Bit() && Size >= 8)
1660     return MVT::i64;
1661   return MVT::i32;
1662 }
1663
1664 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1665   if (VT == MVT::f32)
1666     return X86ScalarSSEf32;
1667   else if (VT == MVT::f64)
1668     return X86ScalarSSEf64;
1669   return true;
1670 }
1671
1672 bool
1673 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1674   if (Fast)
1675     *Fast = Subtarget->isUnalignedMemAccessFast();
1676   return true;
1677 }
1678
1679 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1680 /// current function.  The returned value is a member of the
1681 /// MachineJumpTableInfo::JTEntryKind enum.
1682 unsigned X86TargetLowering::getJumpTableEncoding() const {
1683   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1684   // symbol.
1685   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1686       Subtarget->isPICStyleGOT())
1687     return MachineJumpTableInfo::EK_Custom32;
1688
1689   // Otherwise, use the normal jump table encoding heuristics.
1690   return TargetLowering::getJumpTableEncoding();
1691 }
1692
1693 const MCExpr *
1694 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1695                                              const MachineBasicBlock *MBB,
1696                                              unsigned uid,MCContext &Ctx) const{
1697   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1698          Subtarget->isPICStyleGOT());
1699   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1700   // entries.
1701   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1702                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1703 }
1704
1705 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1706 /// jumptable.
1707 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1708                                                     SelectionDAG &DAG) const {
1709   if (!Subtarget->is64Bit())
1710     // This doesn't have SDLoc associated with it, but is not really the
1711     // same as a Register.
1712     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1713   return Table;
1714 }
1715
1716 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1717 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1718 /// MCExpr.
1719 const MCExpr *X86TargetLowering::
1720 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1721                              MCContext &Ctx) const {
1722   // X86-64 uses RIP relative addressing based on the jump table label.
1723   if (Subtarget->isPICStyleRIPRel())
1724     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1725
1726   // Otherwise, the reference is relative to the PIC base.
1727   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1728 }
1729
1730 // FIXME: Why this routine is here? Move to RegInfo!
1731 std::pair<const TargetRegisterClass*, uint8_t>
1732 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1733   const TargetRegisterClass *RRC = 0;
1734   uint8_t Cost = 1;
1735   switch (VT.SimpleTy) {
1736   default:
1737     return TargetLowering::findRepresentativeClass(VT);
1738   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1739     RRC = Subtarget->is64Bit() ?
1740       (const TargetRegisterClass*)&X86::GR64RegClass :
1741       (const TargetRegisterClass*)&X86::GR32RegClass;
1742     break;
1743   case MVT::x86mmx:
1744     RRC = &X86::VR64RegClass;
1745     break;
1746   case MVT::f32: case MVT::f64:
1747   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1748   case MVT::v4f32: case MVT::v2f64:
1749   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1750   case MVT::v4f64:
1751     RRC = &X86::VR128RegClass;
1752     break;
1753   }
1754   return std::make_pair(RRC, Cost);
1755 }
1756
1757 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1758                                                unsigned &Offset) const {
1759   if (!Subtarget->isTargetLinux())
1760     return false;
1761
1762   if (Subtarget->is64Bit()) {
1763     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1764     Offset = 0x28;
1765     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1766       AddressSpace = 256;
1767     else
1768       AddressSpace = 257;
1769   } else {
1770     // %gs:0x14 on i386
1771     Offset = 0x14;
1772     AddressSpace = 256;
1773   }
1774   return true;
1775 }
1776
1777 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1778                                             unsigned DestAS) const {
1779   assert(SrcAS != DestAS && "Expected different address spaces!");
1780
1781   return SrcAS < 256 && DestAS < 256;
1782 }
1783
1784 //===----------------------------------------------------------------------===//
1785 //               Return Value Calling Convention Implementation
1786 //===----------------------------------------------------------------------===//
1787
1788 #include "X86GenCallingConv.inc"
1789
1790 bool
1791 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1792                                   MachineFunction &MF, bool isVarArg,
1793                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1794                         LLVMContext &Context) const {
1795   SmallVector<CCValAssign, 16> RVLocs;
1796   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1797                  RVLocs, Context);
1798   return CCInfo.CheckReturn(Outs, RetCC_X86);
1799 }
1800
1801 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1802   static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1803   return ScratchRegs;
1804 }
1805
1806 SDValue
1807 X86TargetLowering::LowerReturn(SDValue Chain,
1808                                CallingConv::ID CallConv, bool isVarArg,
1809                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1810                                const SmallVectorImpl<SDValue> &OutVals,
1811                                SDLoc dl, SelectionDAG &DAG) const {
1812   MachineFunction &MF = DAG.getMachineFunction();
1813   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1814
1815   SmallVector<CCValAssign, 16> RVLocs;
1816   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1817                  RVLocs, *DAG.getContext());
1818   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1819
1820   SDValue Flag;
1821   SmallVector<SDValue, 6> RetOps;
1822   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1823   // Operand #1 = Bytes To Pop
1824   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1825                    MVT::i16));
1826
1827   // Copy the result values into the output registers.
1828   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1829     CCValAssign &VA = RVLocs[i];
1830     assert(VA.isRegLoc() && "Can only return in registers!");
1831     SDValue ValToCopy = OutVals[i];
1832     EVT ValVT = ValToCopy.getValueType();
1833
1834     // Promote values to the appropriate types
1835     if (VA.getLocInfo() == CCValAssign::SExt)
1836       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1837     else if (VA.getLocInfo() == CCValAssign::ZExt)
1838       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1839     else if (VA.getLocInfo() == CCValAssign::AExt)
1840       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1841     else if (VA.getLocInfo() == CCValAssign::BCvt)
1842       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1843
1844     // If this is x86-64, and we disabled SSE, we can't return FP values,
1845     // or SSE or MMX vectors.
1846     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1847          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1848           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1849       report_fatal_error("SSE register return with SSE disabled");
1850     }
1851     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1852     // llvm-gcc has never done it right and no one has noticed, so this
1853     // should be OK for now.
1854     if (ValVT == MVT::f64 &&
1855         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1856       report_fatal_error("SSE2 register return with SSE2 disabled");
1857
1858     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1859     // the RET instruction and handled by the FP Stackifier.
1860     if (VA.getLocReg() == X86::ST0 ||
1861         VA.getLocReg() == X86::ST1) {
1862       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1863       // change the value to the FP stack register class.
1864       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1865         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1866       RetOps.push_back(ValToCopy);
1867       // Don't emit a copytoreg.
1868       continue;
1869     }
1870
1871     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1872     // which is returned in RAX / RDX.
1873     if (Subtarget->is64Bit()) {
1874       if (ValVT == MVT::x86mmx) {
1875         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1876           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1877           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1878                                   ValToCopy);
1879           // If we don't have SSE2 available, convert to v4f32 so the generated
1880           // register is legal.
1881           if (!Subtarget->hasSSE2())
1882             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1883         }
1884       }
1885     }
1886
1887     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1888     Flag = Chain.getValue(1);
1889     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1890   }
1891
1892   // The x86-64 ABIs require that for returning structs by value we copy
1893   // the sret argument into %rax/%eax (depending on ABI) for the return.
1894   // Win32 requires us to put the sret argument to %eax as well.
1895   // We saved the argument into a virtual register in the entry block,
1896   // so now we copy the value out and into %rax/%eax.
1897   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1898       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1899     MachineFunction &MF = DAG.getMachineFunction();
1900     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1901     unsigned Reg = FuncInfo->getSRetReturnReg();
1902     assert(Reg &&
1903            "SRetReturnReg should have been set in LowerFormalArguments().");
1904     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1905
1906     unsigned RetValReg
1907         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1908           X86::RAX : X86::EAX;
1909     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1910     Flag = Chain.getValue(1);
1911
1912     // RAX/EAX now acts like a return value.
1913     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1914   }
1915
1916   RetOps[0] = Chain;  // Update chain.
1917
1918   // Add the flag if we have it.
1919   if (Flag.getNode())
1920     RetOps.push_back(Flag);
1921
1922   return DAG.getNode(X86ISD::RET_FLAG, dl,
1923                      MVT::Other, &RetOps[0], RetOps.size());
1924 }
1925
1926 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1927   if (N->getNumValues() != 1)
1928     return false;
1929   if (!N->hasNUsesOfValue(1, 0))
1930     return false;
1931
1932   SDValue TCChain = Chain;
1933   SDNode *Copy = *N->use_begin();
1934   if (Copy->getOpcode() == ISD::CopyToReg) {
1935     // If the copy has a glue operand, we conservatively assume it isn't safe to
1936     // perform a tail call.
1937     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1938       return false;
1939     TCChain = Copy->getOperand(0);
1940   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1941     return false;
1942
1943   bool HasRet = false;
1944   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1945        UI != UE; ++UI) {
1946     if (UI->getOpcode() != X86ISD::RET_FLAG)
1947       return false;
1948     HasRet = true;
1949   }
1950
1951   if (!HasRet)
1952     return false;
1953
1954   Chain = TCChain;
1955   return true;
1956 }
1957
1958 MVT
1959 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1960                                             ISD::NodeType ExtendKind) const {
1961   MVT ReturnMVT;
1962   // TODO: Is this also valid on 32-bit?
1963   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1964     ReturnMVT = MVT::i8;
1965   else
1966     ReturnMVT = MVT::i32;
1967
1968   MVT MinVT = getRegisterType(ReturnMVT);
1969   return VT.bitsLT(MinVT) ? MinVT : VT;
1970 }
1971
1972 /// LowerCallResult - Lower the result values of a call into the
1973 /// appropriate copies out of appropriate physical registers.
1974 ///
1975 SDValue
1976 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1977                                    CallingConv::ID CallConv, bool isVarArg,
1978                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1979                                    SDLoc dl, SelectionDAG &DAG,
1980                                    SmallVectorImpl<SDValue> &InVals) const {
1981
1982   // Assign locations to each value returned by this call.
1983   SmallVector<CCValAssign, 16> RVLocs;
1984   bool Is64Bit = Subtarget->is64Bit();
1985   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1986                  getTargetMachine(), RVLocs, *DAG.getContext());
1987   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1988
1989   // Copy all of the result registers out of their specified physreg.
1990   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1991     CCValAssign &VA = RVLocs[i];
1992     EVT CopyVT = VA.getValVT();
1993
1994     // If this is x86-64, and we disabled SSE, we can't return FP values
1995     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1996         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1997       report_fatal_error("SSE register return with SSE disabled");
1998     }
1999
2000     SDValue Val;
2001
2002     // If this is a call to a function that returns an fp value on the floating
2003     // point stack, we must guarantee the value is popped from the stack, so
2004     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2005     // if the return value is not used. We use the FpPOP_RETVAL instruction
2006     // instead.
2007     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2008       // If we prefer to use the value in xmm registers, copy it out as f80 and
2009       // use a truncate to move it from fp stack reg to xmm reg.
2010       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2011       SDValue Ops[] = { Chain, InFlag };
2012       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2013                                          MVT::Other, MVT::Glue, Ops), 1);
2014       Val = Chain.getValue(0);
2015
2016       // Round the f80 to the right size, which also moves it to the appropriate
2017       // xmm register.
2018       if (CopyVT != VA.getValVT())
2019         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2020                           // This truncation won't change the value.
2021                           DAG.getIntPtrConstant(1));
2022     } else {
2023       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2024                                  CopyVT, InFlag).getValue(1);
2025       Val = Chain.getValue(0);
2026     }
2027     InFlag = Chain.getValue(2);
2028     InVals.push_back(Val);
2029   }
2030
2031   return Chain;
2032 }
2033
2034 //===----------------------------------------------------------------------===//
2035 //                C & StdCall & Fast Calling Convention implementation
2036 //===----------------------------------------------------------------------===//
2037 //  StdCall calling convention seems to be standard for many Windows' API
2038 //  routines and around. It differs from C calling convention just a little:
2039 //  callee should clean up the stack, not caller. Symbols should be also
2040 //  decorated in some fancy way :) It doesn't support any vector arguments.
2041 //  For info on fast calling convention see Fast Calling Convention (tail call)
2042 //  implementation LowerX86_32FastCCCallTo.
2043
2044 /// CallIsStructReturn - Determines whether a call uses struct return
2045 /// semantics.
2046 enum StructReturnType {
2047   NotStructReturn,
2048   RegStructReturn,
2049   StackStructReturn
2050 };
2051 static StructReturnType
2052 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2053   if (Outs.empty())
2054     return NotStructReturn;
2055
2056   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2057   if (!Flags.isSRet())
2058     return NotStructReturn;
2059   if (Flags.isInReg())
2060     return RegStructReturn;
2061   return StackStructReturn;
2062 }
2063
2064 /// ArgsAreStructReturn - Determines whether a function uses struct
2065 /// return semantics.
2066 static StructReturnType
2067 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2068   if (Ins.empty())
2069     return NotStructReturn;
2070
2071   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2072   if (!Flags.isSRet())
2073     return NotStructReturn;
2074   if (Flags.isInReg())
2075     return RegStructReturn;
2076   return StackStructReturn;
2077 }
2078
2079 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2080 /// by "Src" to address "Dst" with size and alignment information specified by
2081 /// the specific parameter attribute. The copy will be passed as a byval
2082 /// function parameter.
2083 static SDValue
2084 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2085                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2086                           SDLoc dl) {
2087   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2088
2089   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2090                        /*isVolatile*/false, /*AlwaysInline=*/true,
2091                        MachinePointerInfo(), MachinePointerInfo());
2092 }
2093
2094 /// IsTailCallConvention - Return true if the calling convention is one that
2095 /// supports tail call optimization.
2096 static bool IsTailCallConvention(CallingConv::ID CC) {
2097   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2098           CC == CallingConv::HiPE);
2099 }
2100
2101 /// \brief Return true if the calling convention is a C calling convention.
2102 static bool IsCCallConvention(CallingConv::ID CC) {
2103   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2104           CC == CallingConv::X86_64_SysV);
2105 }
2106
2107 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2108   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2109     return false;
2110
2111   CallSite CS(CI);
2112   CallingConv::ID CalleeCC = CS.getCallingConv();
2113   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2114     return false;
2115
2116   return true;
2117 }
2118
2119 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2120 /// a tailcall target by changing its ABI.
2121 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2122                                    bool GuaranteedTailCallOpt) {
2123   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2124 }
2125
2126 SDValue
2127 X86TargetLowering::LowerMemArgument(SDValue Chain,
2128                                     CallingConv::ID CallConv,
2129                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2130                                     SDLoc dl, SelectionDAG &DAG,
2131                                     const CCValAssign &VA,
2132                                     MachineFrameInfo *MFI,
2133                                     unsigned i) const {
2134   // Create the nodes corresponding to a load from this parameter slot.
2135   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2136   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2137                               getTargetMachine().Options.GuaranteedTailCallOpt);
2138   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2139   EVT ValVT;
2140
2141   // If value is passed by pointer we have address passed instead of the value
2142   // itself.
2143   if (VA.getLocInfo() == CCValAssign::Indirect)
2144     ValVT = VA.getLocVT();
2145   else
2146     ValVT = VA.getValVT();
2147
2148   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2149   // changed with more analysis.
2150   // In case of tail call optimization mark all arguments mutable. Since they
2151   // could be overwritten by lowering of arguments in case of a tail call.
2152   if (Flags.isByVal()) {
2153     unsigned Bytes = Flags.getByValSize();
2154     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2155     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2156     return DAG.getFrameIndex(FI, getPointerTy());
2157   } else {
2158     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2159                                     VA.getLocMemOffset(), isImmutable);
2160     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2161     return DAG.getLoad(ValVT, dl, Chain, FIN,
2162                        MachinePointerInfo::getFixedStack(FI),
2163                        false, false, false, 0);
2164   }
2165 }
2166
2167 SDValue
2168 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2169                                         CallingConv::ID CallConv,
2170                                         bool isVarArg,
2171                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2172                                         SDLoc dl,
2173                                         SelectionDAG &DAG,
2174                                         SmallVectorImpl<SDValue> &InVals)
2175                                           const {
2176   MachineFunction &MF = DAG.getMachineFunction();
2177   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2178
2179   const Function* Fn = MF.getFunction();
2180   if (Fn->hasExternalLinkage() &&
2181       Subtarget->isTargetCygMing() &&
2182       Fn->getName() == "main")
2183     FuncInfo->setForceFramePointer(true);
2184
2185   MachineFrameInfo *MFI = MF.getFrameInfo();
2186   bool Is64Bit = Subtarget->is64Bit();
2187   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2188
2189   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2190          "Var args not supported with calling convention fastcc, ghc or hipe");
2191
2192   // Assign locations to all of the incoming arguments.
2193   SmallVector<CCValAssign, 16> ArgLocs;
2194   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2195                  ArgLocs, *DAG.getContext());
2196
2197   // Allocate shadow area for Win64
2198   if (IsWin64)
2199     CCInfo.AllocateStack(32, 8);
2200
2201   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2202
2203   unsigned LastVal = ~0U;
2204   SDValue ArgValue;
2205   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2206     CCValAssign &VA = ArgLocs[i];
2207     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2208     // places.
2209     assert(VA.getValNo() != LastVal &&
2210            "Don't support value assigned to multiple locs yet");
2211     (void)LastVal;
2212     LastVal = VA.getValNo();
2213
2214     if (VA.isRegLoc()) {
2215       EVT RegVT = VA.getLocVT();
2216       const TargetRegisterClass *RC;
2217       if (RegVT == MVT::i32)
2218         RC = &X86::GR32RegClass;
2219       else if (Is64Bit && RegVT == MVT::i64)
2220         RC = &X86::GR64RegClass;
2221       else if (RegVT == MVT::f32)
2222         RC = &X86::FR32RegClass;
2223       else if (RegVT == MVT::f64)
2224         RC = &X86::FR64RegClass;
2225       else if (RegVT.is512BitVector())
2226         RC = &X86::VR512RegClass;
2227       else if (RegVT.is256BitVector())
2228         RC = &X86::VR256RegClass;
2229       else if (RegVT.is128BitVector())
2230         RC = &X86::VR128RegClass;
2231       else if (RegVT == MVT::x86mmx)
2232         RC = &X86::VR64RegClass;
2233       else if (RegVT == MVT::i1)
2234         RC = &X86::VK1RegClass;
2235       else if (RegVT == MVT::v8i1)
2236         RC = &X86::VK8RegClass;
2237       else if (RegVT == MVT::v16i1)
2238         RC = &X86::VK16RegClass;
2239       else
2240         llvm_unreachable("Unknown argument type!");
2241
2242       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2243       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2244
2245       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2246       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2247       // right size.
2248       if (VA.getLocInfo() == CCValAssign::SExt)
2249         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2250                                DAG.getValueType(VA.getValVT()));
2251       else if (VA.getLocInfo() == CCValAssign::ZExt)
2252         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2253                                DAG.getValueType(VA.getValVT()));
2254       else if (VA.getLocInfo() == CCValAssign::BCvt)
2255         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2256
2257       if (VA.isExtInLoc()) {
2258         // Handle MMX values passed in XMM regs.
2259         if (RegVT.isVector())
2260           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2261         else
2262           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2263       }
2264     } else {
2265       assert(VA.isMemLoc());
2266       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2267     }
2268
2269     // If value is passed via pointer - do a load.
2270     if (VA.getLocInfo() == CCValAssign::Indirect)
2271       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2272                              MachinePointerInfo(), false, false, false, 0);
2273
2274     InVals.push_back(ArgValue);
2275   }
2276
2277   // The x86-64 ABIs require that for returning structs by value we copy
2278   // the sret argument into %rax/%eax (depending on ABI) for the return.
2279   // Win32 requires us to put the sret argument to %eax as well.
2280   // Save the argument into a virtual register so that we can access it
2281   // from the return points.
2282   if (MF.getFunction()->hasStructRetAttr() &&
2283       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2284     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2285     unsigned Reg = FuncInfo->getSRetReturnReg();
2286     if (!Reg) {
2287       MVT PtrTy = getPointerTy();
2288       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2289       FuncInfo->setSRetReturnReg(Reg);
2290     }
2291     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2292     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2293   }
2294
2295   unsigned StackSize = CCInfo.getNextStackOffset();
2296   // Align stack specially for tail calls.
2297   if (FuncIsMadeTailCallSafe(CallConv,
2298                              MF.getTarget().Options.GuaranteedTailCallOpt))
2299     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2300
2301   // If the function takes variable number of arguments, make a frame index for
2302   // the start of the first vararg value... for expansion of llvm.va_start.
2303   if (isVarArg) {
2304     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2305                     CallConv != CallingConv::X86_ThisCall)) {
2306       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2307     }
2308     if (Is64Bit) {
2309       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2310
2311       // FIXME: We should really autogenerate these arrays
2312       static const uint16_t GPR64ArgRegsWin64[] = {
2313         X86::RCX, X86::RDX, X86::R8,  X86::R9
2314       };
2315       static const uint16_t GPR64ArgRegs64Bit[] = {
2316         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2317       };
2318       static const uint16_t XMMArgRegs64Bit[] = {
2319         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2320         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2321       };
2322       const uint16_t *GPR64ArgRegs;
2323       unsigned NumXMMRegs = 0;
2324
2325       if (IsWin64) {
2326         // The XMM registers which might contain var arg parameters are shadowed
2327         // in their paired GPR.  So we only need to save the GPR to their home
2328         // slots.
2329         TotalNumIntRegs = 4;
2330         GPR64ArgRegs = GPR64ArgRegsWin64;
2331       } else {
2332         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2333         GPR64ArgRegs = GPR64ArgRegs64Bit;
2334
2335         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2336                                                 TotalNumXMMRegs);
2337       }
2338       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2339                                                        TotalNumIntRegs);
2340
2341       bool NoImplicitFloatOps = Fn->getAttributes().
2342         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2343       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2344              "SSE register cannot be used when SSE is disabled!");
2345       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2346                NoImplicitFloatOps) &&
2347              "SSE register cannot be used when SSE is disabled!");
2348       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2349           !Subtarget->hasSSE1())
2350         // Kernel mode asks for SSE to be disabled, so don't push them
2351         // on the stack.
2352         TotalNumXMMRegs = 0;
2353
2354       if (IsWin64) {
2355         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2356         // Get to the caller-allocated home save location.  Add 8 to account
2357         // for the return address.
2358         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2359         FuncInfo->setRegSaveFrameIndex(
2360           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2361         // Fixup to set vararg frame on shadow area (4 x i64).
2362         if (NumIntRegs < 4)
2363           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2364       } else {
2365         // For X86-64, if there are vararg parameters that are passed via
2366         // registers, then we must store them to their spots on the stack so
2367         // they may be loaded by deferencing the result of va_next.
2368         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2369         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2370         FuncInfo->setRegSaveFrameIndex(
2371           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2372                                false));
2373       }
2374
2375       // Store the integer parameter registers.
2376       SmallVector<SDValue, 8> MemOps;
2377       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2378                                         getPointerTy());
2379       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2380       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2381         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2382                                   DAG.getIntPtrConstant(Offset));
2383         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2384                                      &X86::GR64RegClass);
2385         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2386         SDValue Store =
2387           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2388                        MachinePointerInfo::getFixedStack(
2389                          FuncInfo->getRegSaveFrameIndex(), Offset),
2390                        false, false, 0);
2391         MemOps.push_back(Store);
2392         Offset += 8;
2393       }
2394
2395       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2396         // Now store the XMM (fp + vector) parameter registers.
2397         SmallVector<SDValue, 11> SaveXMMOps;
2398         SaveXMMOps.push_back(Chain);
2399
2400         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2401         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2402         SaveXMMOps.push_back(ALVal);
2403
2404         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2405                                FuncInfo->getRegSaveFrameIndex()));
2406         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2407                                FuncInfo->getVarArgsFPOffset()));
2408
2409         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2410           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2411                                        &X86::VR128RegClass);
2412           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2413           SaveXMMOps.push_back(Val);
2414         }
2415         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2416                                      MVT::Other,
2417                                      &SaveXMMOps[0], SaveXMMOps.size()));
2418       }
2419
2420       if (!MemOps.empty())
2421         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2422                             &MemOps[0], MemOps.size());
2423     }
2424   }
2425
2426   // Some CCs need callee pop.
2427   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2428                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2429     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2430   } else {
2431     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2432     // If this is an sret function, the return should pop the hidden pointer.
2433     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2434         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2435         argsAreStructReturn(Ins) == StackStructReturn)
2436       FuncInfo->setBytesToPopOnReturn(4);
2437   }
2438
2439   if (!Is64Bit) {
2440     // RegSaveFrameIndex is X86-64 only.
2441     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2442     if (CallConv == CallingConv::X86_FastCall ||
2443         CallConv == CallingConv::X86_ThisCall)
2444       // fastcc functions can't have varargs.
2445       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2446   }
2447
2448   FuncInfo->setArgumentStackSize(StackSize);
2449
2450   return Chain;
2451 }
2452
2453 SDValue
2454 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2455                                     SDValue StackPtr, SDValue Arg,
2456                                     SDLoc dl, SelectionDAG &DAG,
2457                                     const CCValAssign &VA,
2458                                     ISD::ArgFlagsTy Flags) const {
2459   unsigned LocMemOffset = VA.getLocMemOffset();
2460   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2461   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2462   if (Flags.isByVal())
2463     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2464
2465   return DAG.getStore(Chain, dl, Arg, PtrOff,
2466                       MachinePointerInfo::getStack(LocMemOffset),
2467                       false, false, 0);
2468 }
2469
2470 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2471 /// optimization is performed and it is required.
2472 SDValue
2473 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2474                                            SDValue &OutRetAddr, SDValue Chain,
2475                                            bool IsTailCall, bool Is64Bit,
2476                                            int FPDiff, SDLoc dl) const {
2477   // Adjust the Return address stack slot.
2478   EVT VT = getPointerTy();
2479   OutRetAddr = getReturnAddressFrameIndex(DAG);
2480
2481   // Load the "old" Return address.
2482   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2483                            false, false, false, 0);
2484   return SDValue(OutRetAddr.getNode(), 1);
2485 }
2486
2487 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2488 /// optimization is performed and it is required (FPDiff!=0).
2489 static SDValue
2490 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2491                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2492                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2493   // Store the return address to the appropriate stack slot.
2494   if (!FPDiff) return Chain;
2495   // Calculate the new stack slot for the return address.
2496   int NewReturnAddrFI =
2497     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2498                                          false);
2499   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2500   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2501                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2502                        false, false, 0);
2503   return Chain;
2504 }
2505
2506 SDValue
2507 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2508                              SmallVectorImpl<SDValue> &InVals) const {
2509   SelectionDAG &DAG                     = CLI.DAG;
2510   SDLoc &dl                             = CLI.DL;
2511   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2512   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2513   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2514   SDValue Chain                         = CLI.Chain;
2515   SDValue Callee                        = CLI.Callee;
2516   CallingConv::ID CallConv              = CLI.CallConv;
2517   bool &isTailCall                      = CLI.IsTailCall;
2518   bool isVarArg                         = CLI.IsVarArg;
2519
2520   MachineFunction &MF = DAG.getMachineFunction();
2521   bool Is64Bit        = Subtarget->is64Bit();
2522   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2523   StructReturnType SR = callIsStructReturn(Outs);
2524   bool IsSibcall      = false;
2525
2526   if (MF.getTarget().Options.DisableTailCalls)
2527     isTailCall = false;
2528
2529   if (isTailCall) {
2530     // Check if it's really possible to do a tail call.
2531     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2532                     isVarArg, SR != NotStructReturn,
2533                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2534                     Outs, OutVals, Ins, DAG);
2535
2536     // Sibcalls are automatically detected tailcalls which do not require
2537     // ABI changes.
2538     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2539       IsSibcall = true;
2540
2541     if (isTailCall)
2542       ++NumTailCalls;
2543   }
2544
2545   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2546          "Var args not supported with calling convention fastcc, ghc or hipe");
2547
2548   // Analyze operands of the call, assigning locations to each operand.
2549   SmallVector<CCValAssign, 16> ArgLocs;
2550   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2551                  ArgLocs, *DAG.getContext());
2552
2553   // Allocate shadow area for Win64
2554   if (IsWin64)
2555     CCInfo.AllocateStack(32, 8);
2556
2557   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2558
2559   // Get a count of how many bytes are to be pushed on the stack.
2560   unsigned NumBytes = CCInfo.getNextStackOffset();
2561   if (IsSibcall)
2562     // This is a sibcall. The memory operands are available in caller's
2563     // own caller's stack.
2564     NumBytes = 0;
2565   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2566            IsTailCallConvention(CallConv))
2567     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2568
2569   int FPDiff = 0;
2570   if (isTailCall && !IsSibcall) {
2571     // Lower arguments at fp - stackoffset + fpdiff.
2572     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2573     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2574
2575     FPDiff = NumBytesCallerPushed - NumBytes;
2576
2577     // Set the delta of movement of the returnaddr stackslot.
2578     // But only set if delta is greater than previous delta.
2579     if (FPDiff < X86Info->getTCReturnAddrDelta())
2580       X86Info->setTCReturnAddrDelta(FPDiff);
2581   }
2582
2583   if (!IsSibcall)
2584     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2585                                  dl);
2586
2587   SDValue RetAddrFrIdx;
2588   // Load return address for tail calls.
2589   if (isTailCall && FPDiff)
2590     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2591                                     Is64Bit, FPDiff, dl);
2592
2593   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2594   SmallVector<SDValue, 8> MemOpChains;
2595   SDValue StackPtr;
2596
2597   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2598   // of tail call optimization arguments are handle later.
2599   const X86RegisterInfo *RegInfo =
2600     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2601   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2602     CCValAssign &VA = ArgLocs[i];
2603     EVT RegVT = VA.getLocVT();
2604     SDValue Arg = OutVals[i];
2605     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2606     bool isByVal = Flags.isByVal();
2607
2608     // Promote the value if needed.
2609     switch (VA.getLocInfo()) {
2610     default: llvm_unreachable("Unknown loc info!");
2611     case CCValAssign::Full: break;
2612     case CCValAssign::SExt:
2613       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2614       break;
2615     case CCValAssign::ZExt:
2616       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2617       break;
2618     case CCValAssign::AExt:
2619       if (RegVT.is128BitVector()) {
2620         // Special case: passing MMX values in XMM registers.
2621         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2622         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2623         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2624       } else
2625         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2626       break;
2627     case CCValAssign::BCvt:
2628       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2629       break;
2630     case CCValAssign::Indirect: {
2631       // Store the argument.
2632       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2633       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2634       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2635                            MachinePointerInfo::getFixedStack(FI),
2636                            false, false, 0);
2637       Arg = SpillSlot;
2638       break;
2639     }
2640     }
2641
2642     if (VA.isRegLoc()) {
2643       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2644       if (isVarArg && IsWin64) {
2645         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2646         // shadow reg if callee is a varargs function.
2647         unsigned ShadowReg = 0;
2648         switch (VA.getLocReg()) {
2649         case X86::XMM0: ShadowReg = X86::RCX; break;
2650         case X86::XMM1: ShadowReg = X86::RDX; break;
2651         case X86::XMM2: ShadowReg = X86::R8; break;
2652         case X86::XMM3: ShadowReg = X86::R9; break;
2653         }
2654         if (ShadowReg)
2655           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2656       }
2657     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2658       assert(VA.isMemLoc());
2659       if (StackPtr.getNode() == 0)
2660         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2661                                       getPointerTy());
2662       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2663                                              dl, DAG, VA, Flags));
2664     }
2665   }
2666
2667   if (!MemOpChains.empty())
2668     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2669                         &MemOpChains[0], MemOpChains.size());
2670
2671   if (Subtarget->isPICStyleGOT()) {
2672     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2673     // GOT pointer.
2674     if (!isTailCall) {
2675       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2676                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2677     } else {
2678       // If we are tail calling and generating PIC/GOT style code load the
2679       // address of the callee into ECX. The value in ecx is used as target of
2680       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2681       // for tail calls on PIC/GOT architectures. Normally we would just put the
2682       // address of GOT into ebx and then call target@PLT. But for tail calls
2683       // ebx would be restored (since ebx is callee saved) before jumping to the
2684       // target@PLT.
2685
2686       // Note: The actual moving to ECX is done further down.
2687       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2688       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2689           !G->getGlobal()->hasProtectedVisibility())
2690         Callee = LowerGlobalAddress(Callee, DAG);
2691       else if (isa<ExternalSymbolSDNode>(Callee))
2692         Callee = LowerExternalSymbol(Callee, DAG);
2693     }
2694   }
2695
2696   if (Is64Bit && isVarArg && !IsWin64) {
2697     // From AMD64 ABI document:
2698     // For calls that may call functions that use varargs or stdargs
2699     // (prototype-less calls or calls to functions containing ellipsis (...) in
2700     // the declaration) %al is used as hidden argument to specify the number
2701     // of SSE registers used. The contents of %al do not need to match exactly
2702     // the number of registers, but must be an ubound on the number of SSE
2703     // registers used and is in the range 0 - 8 inclusive.
2704
2705     // Count the number of XMM registers allocated.
2706     static const uint16_t XMMArgRegs[] = {
2707       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2708       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2709     };
2710     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2711     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2712            && "SSE registers cannot be used when SSE is disabled");
2713
2714     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2715                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2716   }
2717
2718   // For tail calls lower the arguments to the 'real' stack slot.
2719   if (isTailCall) {
2720     // Force all the incoming stack arguments to be loaded from the stack
2721     // before any new outgoing arguments are stored to the stack, because the
2722     // outgoing stack slots may alias the incoming argument stack slots, and
2723     // the alias isn't otherwise explicit. This is slightly more conservative
2724     // than necessary, because it means that each store effectively depends
2725     // on every argument instead of just those arguments it would clobber.
2726     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2727
2728     SmallVector<SDValue, 8> MemOpChains2;
2729     SDValue FIN;
2730     int FI = 0;
2731     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2732       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2733         CCValAssign &VA = ArgLocs[i];
2734         if (VA.isRegLoc())
2735           continue;
2736         assert(VA.isMemLoc());
2737         SDValue Arg = OutVals[i];
2738         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2739         // Create frame index.
2740         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2741         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2742         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2743         FIN = DAG.getFrameIndex(FI, getPointerTy());
2744
2745         if (Flags.isByVal()) {
2746           // Copy relative to framepointer.
2747           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2748           if (StackPtr.getNode() == 0)
2749             StackPtr = DAG.getCopyFromReg(Chain, dl,
2750                                           RegInfo->getStackRegister(),
2751                                           getPointerTy());
2752           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2753
2754           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2755                                                            ArgChain,
2756                                                            Flags, DAG, dl));
2757         } else {
2758           // Store relative to framepointer.
2759           MemOpChains2.push_back(
2760             DAG.getStore(ArgChain, dl, Arg, FIN,
2761                          MachinePointerInfo::getFixedStack(FI),
2762                          false, false, 0));
2763         }
2764       }
2765     }
2766
2767     if (!MemOpChains2.empty())
2768       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2769                           &MemOpChains2[0], MemOpChains2.size());
2770
2771     // Store the return address to the appropriate stack slot.
2772     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2773                                      getPointerTy(), RegInfo->getSlotSize(),
2774                                      FPDiff, dl);
2775   }
2776
2777   // Build a sequence of copy-to-reg nodes chained together with token chain
2778   // and flag operands which copy the outgoing args into registers.
2779   SDValue InFlag;
2780   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2781     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2782                              RegsToPass[i].second, InFlag);
2783     InFlag = Chain.getValue(1);
2784   }
2785
2786   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2787     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2788     // In the 64-bit large code model, we have to make all calls
2789     // through a register, since the call instruction's 32-bit
2790     // pc-relative offset may not be large enough to hold the whole
2791     // address.
2792   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2793     // If the callee is a GlobalAddress node (quite common, every direct call
2794     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2795     // it.
2796
2797     // We should use extra load for direct calls to dllimported functions in
2798     // non-JIT mode.
2799     const GlobalValue *GV = G->getGlobal();
2800     if (!GV->hasDLLImportLinkage()) {
2801       unsigned char OpFlags = 0;
2802       bool ExtraLoad = false;
2803       unsigned WrapperKind = ISD::DELETED_NODE;
2804
2805       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2806       // external symbols most go through the PLT in PIC mode.  If the symbol
2807       // has hidden or protected visibility, or if it is static or local, then
2808       // we don't need to use the PLT - we can directly call it.
2809       if (Subtarget->isTargetELF() &&
2810           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2811           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2812         OpFlags = X86II::MO_PLT;
2813       } else if (Subtarget->isPICStyleStubAny() &&
2814                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2815                  (!Subtarget->getTargetTriple().isMacOSX() ||
2816                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2817         // PC-relative references to external symbols should go through $stub,
2818         // unless we're building with the leopard linker or later, which
2819         // automatically synthesizes these stubs.
2820         OpFlags = X86II::MO_DARWIN_STUB;
2821       } else if (Subtarget->isPICStyleRIPRel() &&
2822                  isa<Function>(GV) &&
2823                  cast<Function>(GV)->getAttributes().
2824                    hasAttribute(AttributeSet::FunctionIndex,
2825                                 Attribute::NonLazyBind)) {
2826         // If the function is marked as non-lazy, generate an indirect call
2827         // which loads from the GOT directly. This avoids runtime overhead
2828         // at the cost of eager binding (and one extra byte of encoding).
2829         OpFlags = X86II::MO_GOTPCREL;
2830         WrapperKind = X86ISD::WrapperRIP;
2831         ExtraLoad = true;
2832       }
2833
2834       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2835                                           G->getOffset(), OpFlags);
2836
2837       // Add a wrapper if needed.
2838       if (WrapperKind != ISD::DELETED_NODE)
2839         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2840       // Add extra indirection if needed.
2841       if (ExtraLoad)
2842         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2843                              MachinePointerInfo::getGOT(),
2844                              false, false, false, 0);
2845     }
2846   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2847     unsigned char OpFlags = 0;
2848
2849     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2850     // external symbols should go through the PLT.
2851     if (Subtarget->isTargetELF() &&
2852         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2853       OpFlags = X86II::MO_PLT;
2854     } else if (Subtarget->isPICStyleStubAny() &&
2855                (!Subtarget->getTargetTriple().isMacOSX() ||
2856                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2857       // PC-relative references to external symbols should go through $stub,
2858       // unless we're building with the leopard linker or later, which
2859       // automatically synthesizes these stubs.
2860       OpFlags = X86II::MO_DARWIN_STUB;
2861     }
2862
2863     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2864                                          OpFlags);
2865   }
2866
2867   // Returns a chain & a flag for retval copy to use.
2868   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2869   SmallVector<SDValue, 8> Ops;
2870
2871   if (!IsSibcall && isTailCall) {
2872     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2873                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2874     InFlag = Chain.getValue(1);
2875   }
2876
2877   Ops.push_back(Chain);
2878   Ops.push_back(Callee);
2879
2880   if (isTailCall)
2881     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2882
2883   // Add argument registers to the end of the list so that they are known live
2884   // into the call.
2885   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2886     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2887                                   RegsToPass[i].second.getValueType()));
2888
2889   // Add a register mask operand representing the call-preserved registers.
2890   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2891   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2892   assert(Mask && "Missing call preserved mask for calling convention");
2893   Ops.push_back(DAG.getRegisterMask(Mask));
2894
2895   if (InFlag.getNode())
2896     Ops.push_back(InFlag);
2897
2898   if (isTailCall) {
2899     // We used to do:
2900     //// If this is the first return lowered for this function, add the regs
2901     //// to the liveout set for the function.
2902     // This isn't right, although it's probably harmless on x86; liveouts
2903     // should be computed from returns not tail calls.  Consider a void
2904     // function making a tail call to a function returning int.
2905     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2906   }
2907
2908   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2909   InFlag = Chain.getValue(1);
2910
2911   // Create the CALLSEQ_END node.
2912   unsigned NumBytesForCalleeToPush;
2913   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2914                        getTargetMachine().Options.GuaranteedTailCallOpt))
2915     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2916   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2917            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2918            SR == StackStructReturn)
2919     // If this is a call to a struct-return function, the callee
2920     // pops the hidden struct pointer, so we have to push it back.
2921     // This is common for Darwin/X86, Linux & Mingw32 targets.
2922     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2923     NumBytesForCalleeToPush = 4;
2924   else
2925     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2926
2927   // Returns a flag for retval copy to use.
2928   if (!IsSibcall) {
2929     Chain = DAG.getCALLSEQ_END(Chain,
2930                                DAG.getIntPtrConstant(NumBytes, true),
2931                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2932                                                      true),
2933                                InFlag, dl);
2934     InFlag = Chain.getValue(1);
2935   }
2936
2937   // Handle result values, copying them out of physregs into vregs that we
2938   // return.
2939   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2940                          Ins, dl, DAG, InVals);
2941 }
2942
2943 //===----------------------------------------------------------------------===//
2944 //                Fast Calling Convention (tail call) implementation
2945 //===----------------------------------------------------------------------===//
2946
2947 //  Like std call, callee cleans arguments, convention except that ECX is
2948 //  reserved for storing the tail called function address. Only 2 registers are
2949 //  free for argument passing (inreg). Tail call optimization is performed
2950 //  provided:
2951 //                * tailcallopt is enabled
2952 //                * caller/callee are fastcc
2953 //  On X86_64 architecture with GOT-style position independent code only local
2954 //  (within module) calls are supported at the moment.
2955 //  To keep the stack aligned according to platform abi the function
2956 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2957 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2958 //  If a tail called function callee has more arguments than the caller the
2959 //  caller needs to make sure that there is room to move the RETADDR to. This is
2960 //  achieved by reserving an area the size of the argument delta right after the
2961 //  original REtADDR, but before the saved framepointer or the spilled registers
2962 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2963 //  stack layout:
2964 //    arg1
2965 //    arg2
2966 //    RETADDR
2967 //    [ new RETADDR
2968 //      move area ]
2969 //    (possible EBP)
2970 //    ESI
2971 //    EDI
2972 //    local1 ..
2973
2974 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2975 /// for a 16 byte align requirement.
2976 unsigned
2977 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2978                                                SelectionDAG& DAG) const {
2979   MachineFunction &MF = DAG.getMachineFunction();
2980   const TargetMachine &TM = MF.getTarget();
2981   const X86RegisterInfo *RegInfo =
2982     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2983   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2984   unsigned StackAlignment = TFI.getStackAlignment();
2985   uint64_t AlignMask = StackAlignment - 1;
2986   int64_t Offset = StackSize;
2987   unsigned SlotSize = RegInfo->getSlotSize();
2988   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2989     // Number smaller than 12 so just add the difference.
2990     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2991   } else {
2992     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2993     Offset = ((~AlignMask) & Offset) + StackAlignment +
2994       (StackAlignment-SlotSize);
2995   }
2996   return Offset;
2997 }
2998
2999 /// MatchingStackOffset - Return true if the given stack call argument is
3000 /// already available in the same position (relatively) of the caller's
3001 /// incoming argument stack.
3002 static
3003 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3004                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3005                          const X86InstrInfo *TII) {
3006   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3007   int FI = INT_MAX;
3008   if (Arg.getOpcode() == ISD::CopyFromReg) {
3009     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3010     if (!TargetRegisterInfo::isVirtualRegister(VR))
3011       return false;
3012     MachineInstr *Def = MRI->getVRegDef(VR);
3013     if (!Def)
3014       return false;
3015     if (!Flags.isByVal()) {
3016       if (!TII->isLoadFromStackSlot(Def, FI))
3017         return false;
3018     } else {
3019       unsigned Opcode = Def->getOpcode();
3020       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3021           Def->getOperand(1).isFI()) {
3022         FI = Def->getOperand(1).getIndex();
3023         Bytes = Flags.getByValSize();
3024       } else
3025         return false;
3026     }
3027   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3028     if (Flags.isByVal())
3029       // ByVal argument is passed in as a pointer but it's now being
3030       // dereferenced. e.g.
3031       // define @foo(%struct.X* %A) {
3032       //   tail call @bar(%struct.X* byval %A)
3033       // }
3034       return false;
3035     SDValue Ptr = Ld->getBasePtr();
3036     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3037     if (!FINode)
3038       return false;
3039     FI = FINode->getIndex();
3040   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3041     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3042     FI = FINode->getIndex();
3043     Bytes = Flags.getByValSize();
3044   } else
3045     return false;
3046
3047   assert(FI != INT_MAX);
3048   if (!MFI->isFixedObjectIndex(FI))
3049     return false;
3050   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3051 }
3052
3053 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3054 /// for tail call optimization. Targets which want to do tail call
3055 /// optimization should implement this function.
3056 bool
3057 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3058                                                      CallingConv::ID CalleeCC,
3059                                                      bool isVarArg,
3060                                                      bool isCalleeStructRet,
3061                                                      bool isCallerStructRet,
3062                                                      Type *RetTy,
3063                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3064                                     const SmallVectorImpl<SDValue> &OutVals,
3065                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3066                                                      SelectionDAG &DAG) const {
3067   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3068     return false;
3069
3070   // If -tailcallopt is specified, make fastcc functions tail-callable.
3071   const MachineFunction &MF = DAG.getMachineFunction();
3072   const Function *CallerF = MF.getFunction();
3073
3074   // If the function return type is x86_fp80 and the callee return type is not,
3075   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3076   // perform a tailcall optimization here.
3077   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3078     return false;
3079
3080   CallingConv::ID CallerCC = CallerF->getCallingConv();
3081   bool CCMatch = CallerCC == CalleeCC;
3082   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3083   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3084
3085   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3086     if (IsTailCallConvention(CalleeCC) && CCMatch)
3087       return true;
3088     return false;
3089   }
3090
3091   // Look for obvious safe cases to perform tail call optimization that do not
3092   // require ABI changes. This is what gcc calls sibcall.
3093
3094   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3095   // emit a special epilogue.
3096   const X86RegisterInfo *RegInfo =
3097     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3098   if (RegInfo->needsStackRealignment(MF))
3099     return false;
3100
3101   // Also avoid sibcall optimization if either caller or callee uses struct
3102   // return semantics.
3103   if (isCalleeStructRet || isCallerStructRet)
3104     return false;
3105
3106   // An stdcall/thiscall caller is expected to clean up its arguments; the
3107   // callee isn't going to do that.
3108   // FIXME: this is more restrictive than needed. We could produce a tailcall
3109   // when the stack adjustment matches. For example, with a thiscall that takes
3110   // only one argument.
3111   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3112                    CallerCC == CallingConv::X86_ThisCall))
3113     return false;
3114
3115   // Do not sibcall optimize vararg calls unless all arguments are passed via
3116   // registers.
3117   if (isVarArg && !Outs.empty()) {
3118
3119     // Optimizing for varargs on Win64 is unlikely to be safe without
3120     // additional testing.
3121     if (IsCalleeWin64 || IsCallerWin64)
3122       return false;
3123
3124     SmallVector<CCValAssign, 16> ArgLocs;
3125     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3126                    getTargetMachine(), ArgLocs, *DAG.getContext());
3127
3128     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3129     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3130       if (!ArgLocs[i].isRegLoc())
3131         return false;
3132   }
3133
3134   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3135   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3136   // this into a sibcall.
3137   bool Unused = false;
3138   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3139     if (!Ins[i].Used) {
3140       Unused = true;
3141       break;
3142     }
3143   }
3144   if (Unused) {
3145     SmallVector<CCValAssign, 16> RVLocs;
3146     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3147                    getTargetMachine(), RVLocs, *DAG.getContext());
3148     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3149     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3150       CCValAssign &VA = RVLocs[i];
3151       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3152         return false;
3153     }
3154   }
3155
3156   // If the calling conventions do not match, then we'd better make sure the
3157   // results are returned in the same way as what the caller expects.
3158   if (!CCMatch) {
3159     SmallVector<CCValAssign, 16> RVLocs1;
3160     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3161                     getTargetMachine(), RVLocs1, *DAG.getContext());
3162     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3163
3164     SmallVector<CCValAssign, 16> RVLocs2;
3165     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3166                     getTargetMachine(), RVLocs2, *DAG.getContext());
3167     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3168
3169     if (RVLocs1.size() != RVLocs2.size())
3170       return false;
3171     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3172       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3173         return false;
3174       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3175         return false;
3176       if (RVLocs1[i].isRegLoc()) {
3177         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3178           return false;
3179       } else {
3180         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3181           return false;
3182       }
3183     }
3184   }
3185
3186   // If the callee takes no arguments then go on to check the results of the
3187   // call.
3188   if (!Outs.empty()) {
3189     // Check if stack adjustment is needed. For now, do not do this if any
3190     // argument is passed on the stack.
3191     SmallVector<CCValAssign, 16> ArgLocs;
3192     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3193                    getTargetMachine(), ArgLocs, *DAG.getContext());
3194
3195     // Allocate shadow area for Win64
3196     if (IsCalleeWin64)
3197       CCInfo.AllocateStack(32, 8);
3198
3199     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3200     if (CCInfo.getNextStackOffset()) {
3201       MachineFunction &MF = DAG.getMachineFunction();
3202       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3203         return false;
3204
3205       // Check if the arguments are already laid out in the right way as
3206       // the caller's fixed stack objects.
3207       MachineFrameInfo *MFI = MF.getFrameInfo();
3208       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3209       const X86InstrInfo *TII =
3210         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3211       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3212         CCValAssign &VA = ArgLocs[i];
3213         SDValue Arg = OutVals[i];
3214         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3215         if (VA.getLocInfo() == CCValAssign::Indirect)
3216           return false;
3217         if (!VA.isRegLoc()) {
3218           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3219                                    MFI, MRI, TII))
3220             return false;
3221         }
3222       }
3223     }
3224
3225     // If the tailcall address may be in a register, then make sure it's
3226     // possible to register allocate for it. In 32-bit, the call address can
3227     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3228     // callee-saved registers are restored. These happen to be the same
3229     // registers used to pass 'inreg' arguments so watch out for those.
3230     if (!Subtarget->is64Bit() &&
3231         ((!isa<GlobalAddressSDNode>(Callee) &&
3232           !isa<ExternalSymbolSDNode>(Callee)) ||
3233          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3234       unsigned NumInRegs = 0;
3235       // In PIC we need an extra register to formulate the address computation
3236       // for the callee.
3237       unsigned MaxInRegs =
3238           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3239
3240       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3241         CCValAssign &VA = ArgLocs[i];
3242         if (!VA.isRegLoc())
3243           continue;
3244         unsigned Reg = VA.getLocReg();
3245         switch (Reg) {
3246         default: break;
3247         case X86::EAX: case X86::EDX: case X86::ECX:
3248           if (++NumInRegs == MaxInRegs)
3249             return false;
3250           break;
3251         }
3252       }
3253     }
3254   }
3255
3256   return true;
3257 }
3258
3259 FastISel *
3260 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3261                                   const TargetLibraryInfo *libInfo) const {
3262   return X86::createFastISel(funcInfo, libInfo);
3263 }
3264
3265 //===----------------------------------------------------------------------===//
3266 //                           Other Lowering Hooks
3267 //===----------------------------------------------------------------------===//
3268
3269 static bool MayFoldLoad(SDValue Op) {
3270   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3271 }
3272
3273 static bool MayFoldIntoStore(SDValue Op) {
3274   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3275 }
3276
3277 static bool isTargetShuffle(unsigned Opcode) {
3278   switch(Opcode) {
3279   default: return false;
3280   case X86ISD::PSHUFD:
3281   case X86ISD::PSHUFHW:
3282   case X86ISD::PSHUFLW:
3283   case X86ISD::SHUFP:
3284   case X86ISD::PALIGNR:
3285   case X86ISD::MOVLHPS:
3286   case X86ISD::MOVLHPD:
3287   case X86ISD::MOVHLPS:
3288   case X86ISD::MOVLPS:
3289   case X86ISD::MOVLPD:
3290   case X86ISD::MOVSHDUP:
3291   case X86ISD::MOVSLDUP:
3292   case X86ISD::MOVDDUP:
3293   case X86ISD::MOVSS:
3294   case X86ISD::MOVSD:
3295   case X86ISD::UNPCKL:
3296   case X86ISD::UNPCKH:
3297   case X86ISD::VPERMILP:
3298   case X86ISD::VPERM2X128:
3299   case X86ISD::VPERMI:
3300     return true;
3301   }
3302 }
3303
3304 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3305                                     SDValue V1, SelectionDAG &DAG) {
3306   switch(Opc) {
3307   default: llvm_unreachable("Unknown x86 shuffle node");
3308   case X86ISD::MOVSHDUP:
3309   case X86ISD::MOVSLDUP:
3310   case X86ISD::MOVDDUP:
3311     return DAG.getNode(Opc, dl, VT, V1);
3312   }
3313 }
3314
3315 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3316                                     SDValue V1, unsigned TargetMask,
3317                                     SelectionDAG &DAG) {
3318   switch(Opc) {
3319   default: llvm_unreachable("Unknown x86 shuffle node");
3320   case X86ISD::PSHUFD:
3321   case X86ISD::PSHUFHW:
3322   case X86ISD::PSHUFLW:
3323   case X86ISD::VPERMILP:
3324   case X86ISD::VPERMI:
3325     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3326   }
3327 }
3328
3329 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3330                                     SDValue V1, SDValue V2, unsigned TargetMask,
3331                                     SelectionDAG &DAG) {
3332   switch(Opc) {
3333   default: llvm_unreachable("Unknown x86 shuffle node");
3334   case X86ISD::PALIGNR:
3335   case X86ISD::SHUFP:
3336   case X86ISD::VPERM2X128:
3337     return DAG.getNode(Opc, dl, VT, V1, V2,
3338                        DAG.getConstant(TargetMask, MVT::i8));
3339   }
3340 }
3341
3342 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3343                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3344   switch(Opc) {
3345   default: llvm_unreachable("Unknown x86 shuffle node");
3346   case X86ISD::MOVLHPS:
3347   case X86ISD::MOVLHPD:
3348   case X86ISD::MOVHLPS:
3349   case X86ISD::MOVLPS:
3350   case X86ISD::MOVLPD:
3351   case X86ISD::MOVSS:
3352   case X86ISD::MOVSD:
3353   case X86ISD::UNPCKL:
3354   case X86ISD::UNPCKH:
3355     return DAG.getNode(Opc, dl, VT, V1, V2);
3356   }
3357 }
3358
3359 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3360   MachineFunction &MF = DAG.getMachineFunction();
3361   const X86RegisterInfo *RegInfo =
3362     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3363   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3364   int ReturnAddrIndex = FuncInfo->getRAIndex();
3365
3366   if (ReturnAddrIndex == 0) {
3367     // Set up a frame object for the return address.
3368     unsigned SlotSize = RegInfo->getSlotSize();
3369     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3370                                                            -(int64_t)SlotSize,
3371                                                            false);
3372     FuncInfo->setRAIndex(ReturnAddrIndex);
3373   }
3374
3375   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3376 }
3377
3378 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3379                                        bool hasSymbolicDisplacement) {
3380   // Offset should fit into 32 bit immediate field.
3381   if (!isInt<32>(Offset))
3382     return false;
3383
3384   // If we don't have a symbolic displacement - we don't have any extra
3385   // restrictions.
3386   if (!hasSymbolicDisplacement)
3387     return true;
3388
3389   // FIXME: Some tweaks might be needed for medium code model.
3390   if (M != CodeModel::Small && M != CodeModel::Kernel)
3391     return false;
3392
3393   // For small code model we assume that latest object is 16MB before end of 31
3394   // bits boundary. We may also accept pretty large negative constants knowing
3395   // that all objects are in the positive half of address space.
3396   if (M == CodeModel::Small && Offset < 16*1024*1024)
3397     return true;
3398
3399   // For kernel code model we know that all object resist in the negative half
3400   // of 32bits address space. We may not accept negative offsets, since they may
3401   // be just off and we may accept pretty large positive ones.
3402   if (M == CodeModel::Kernel && Offset > 0)
3403     return true;
3404
3405   return false;
3406 }
3407
3408 /// isCalleePop - Determines whether the callee is required to pop its
3409 /// own arguments. Callee pop is necessary to support tail calls.
3410 bool X86::isCalleePop(CallingConv::ID CallingConv,
3411                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3412   if (IsVarArg)
3413     return false;
3414
3415   switch (CallingConv) {
3416   default:
3417     return false;
3418   case CallingConv::X86_StdCall:
3419     return !is64Bit;
3420   case CallingConv::X86_FastCall:
3421     return !is64Bit;
3422   case CallingConv::X86_ThisCall:
3423     return !is64Bit;
3424   case CallingConv::Fast:
3425     return TailCallOpt;
3426   case CallingConv::GHC:
3427     return TailCallOpt;
3428   case CallingConv::HiPE:
3429     return TailCallOpt;
3430   }
3431 }
3432
3433 /// \brief Return true if the condition is an unsigned comparison operation.
3434 static bool isX86CCUnsigned(unsigned X86CC) {
3435   switch (X86CC) {
3436   default: llvm_unreachable("Invalid integer condition!");
3437   case X86::COND_E:     return true;
3438   case X86::COND_G:     return false;
3439   case X86::COND_GE:    return false;
3440   case X86::COND_L:     return false;
3441   case X86::COND_LE:    return false;
3442   case X86::COND_NE:    return true;
3443   case X86::COND_B:     return true;
3444   case X86::COND_A:     return true;
3445   case X86::COND_BE:    return true;
3446   case X86::COND_AE:    return true;
3447   }
3448   llvm_unreachable("covered switch fell through?!");
3449 }
3450
3451 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3452 /// specific condition code, returning the condition code and the LHS/RHS of the
3453 /// comparison to make.
3454 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3455                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3456   if (!isFP) {
3457     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3458       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3459         // X > -1   -> X == 0, jump !sign.
3460         RHS = DAG.getConstant(0, RHS.getValueType());
3461         return X86::COND_NS;
3462       }
3463       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3464         // X < 0   -> X == 0, jump on sign.
3465         return X86::COND_S;
3466       }
3467       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3468         // X < 1   -> X <= 0
3469         RHS = DAG.getConstant(0, RHS.getValueType());
3470         return X86::COND_LE;
3471       }
3472     }
3473
3474     switch (SetCCOpcode) {
3475     default: llvm_unreachable("Invalid integer condition!");
3476     case ISD::SETEQ:  return X86::COND_E;
3477     case ISD::SETGT:  return X86::COND_G;
3478     case ISD::SETGE:  return X86::COND_GE;
3479     case ISD::SETLT:  return X86::COND_L;
3480     case ISD::SETLE:  return X86::COND_LE;
3481     case ISD::SETNE:  return X86::COND_NE;
3482     case ISD::SETULT: return X86::COND_B;
3483     case ISD::SETUGT: return X86::COND_A;
3484     case ISD::SETULE: return X86::COND_BE;
3485     case ISD::SETUGE: return X86::COND_AE;
3486     }
3487   }
3488
3489   // First determine if it is required or is profitable to flip the operands.
3490
3491   // If LHS is a foldable load, but RHS is not, flip the condition.
3492   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3493       !ISD::isNON_EXTLoad(RHS.getNode())) {
3494     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3495     std::swap(LHS, RHS);
3496   }
3497
3498   switch (SetCCOpcode) {
3499   default: break;
3500   case ISD::SETOLT:
3501   case ISD::SETOLE:
3502   case ISD::SETUGT:
3503   case ISD::SETUGE:
3504     std::swap(LHS, RHS);
3505     break;
3506   }
3507
3508   // On a floating point condition, the flags are set as follows:
3509   // ZF  PF  CF   op
3510   //  0 | 0 | 0 | X > Y
3511   //  0 | 0 | 1 | X < Y
3512   //  1 | 0 | 0 | X == Y
3513   //  1 | 1 | 1 | unordered
3514   switch (SetCCOpcode) {
3515   default: llvm_unreachable("Condcode should be pre-legalized away");
3516   case ISD::SETUEQ:
3517   case ISD::SETEQ:   return X86::COND_E;
3518   case ISD::SETOLT:              // flipped
3519   case ISD::SETOGT:
3520   case ISD::SETGT:   return X86::COND_A;
3521   case ISD::SETOLE:              // flipped
3522   case ISD::SETOGE:
3523   case ISD::SETGE:   return X86::COND_AE;
3524   case ISD::SETUGT:              // flipped
3525   case ISD::SETULT:
3526   case ISD::SETLT:   return X86::COND_B;
3527   case ISD::SETUGE:              // flipped
3528   case ISD::SETULE:
3529   case ISD::SETLE:   return X86::COND_BE;
3530   case ISD::SETONE:
3531   case ISD::SETNE:   return X86::COND_NE;
3532   case ISD::SETUO:   return X86::COND_P;
3533   case ISD::SETO:    return X86::COND_NP;
3534   case ISD::SETOEQ:
3535   case ISD::SETUNE:  return X86::COND_INVALID;
3536   }
3537 }
3538
3539 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3540 /// code. Current x86 isa includes the following FP cmov instructions:
3541 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3542 static bool hasFPCMov(unsigned X86CC) {
3543   switch (X86CC) {
3544   default:
3545     return false;
3546   case X86::COND_B:
3547   case X86::COND_BE:
3548   case X86::COND_E:
3549   case X86::COND_P:
3550   case X86::COND_A:
3551   case X86::COND_AE:
3552   case X86::COND_NE:
3553   case X86::COND_NP:
3554     return true;
3555   }
3556 }
3557
3558 /// isFPImmLegal - Returns true if the target can instruction select the
3559 /// specified FP immediate natively. If false, the legalizer will
3560 /// materialize the FP immediate as a load from a constant pool.
3561 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3562   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3563     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3564       return true;
3565   }
3566   return false;
3567 }
3568
3569 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3570 /// the specified range (L, H].
3571 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3572   return (Val < 0) || (Val >= Low && Val < Hi);
3573 }
3574
3575 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3576 /// specified value.
3577 static bool isUndefOrEqual(int Val, int CmpVal) {
3578   return (Val < 0 || Val == CmpVal);
3579 }
3580
3581 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3582 /// from position Pos and ending in Pos+Size, falls within the specified
3583 /// sequential range (L, L+Pos]. or is undef.
3584 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3585                                        unsigned Pos, unsigned Size, int Low) {
3586   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3587     if (!isUndefOrEqual(Mask[i], Low))
3588       return false;
3589   return true;
3590 }
3591
3592 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3593 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3594 /// the second operand.
3595 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3596   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3597     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3598   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3599     return (Mask[0] < 2 && Mask[1] < 2);
3600   return false;
3601 }
3602
3603 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3604 /// is suitable for input to PSHUFHW.
3605 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3606   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3607     return false;
3608
3609   // Lower quadword copied in order or undef.
3610   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3611     return false;
3612
3613   // Upper quadword shuffled.
3614   for (unsigned i = 4; i != 8; ++i)
3615     if (!isUndefOrInRange(Mask[i], 4, 8))
3616       return false;
3617
3618   if (VT == MVT::v16i16) {
3619     // Lower quadword copied in order or undef.
3620     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3621       return false;
3622
3623     // Upper quadword shuffled.
3624     for (unsigned i = 12; i != 16; ++i)
3625       if (!isUndefOrInRange(Mask[i], 12, 16))
3626         return false;
3627   }
3628
3629   return true;
3630 }
3631
3632 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3633 /// is suitable for input to PSHUFLW.
3634 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3635   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3636     return false;
3637
3638   // Upper quadword copied in order.
3639   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3640     return false;
3641
3642   // Lower quadword shuffled.
3643   for (unsigned i = 0; i != 4; ++i)
3644     if (!isUndefOrInRange(Mask[i], 0, 4))
3645       return false;
3646
3647   if (VT == MVT::v16i16) {
3648     // Upper quadword copied in order.
3649     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3650       return false;
3651
3652     // Lower quadword shuffled.
3653     for (unsigned i = 8; i != 12; ++i)
3654       if (!isUndefOrInRange(Mask[i], 8, 12))
3655         return false;
3656   }
3657
3658   return true;
3659 }
3660
3661 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3662 /// is suitable for input to PALIGNR.
3663 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3664                           const X86Subtarget *Subtarget) {
3665   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3666       (VT.is256BitVector() && !Subtarget->hasInt256()))
3667     return false;
3668
3669   unsigned NumElts = VT.getVectorNumElements();
3670   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3671   unsigned NumLaneElts = NumElts/NumLanes;
3672
3673   // Do not handle 64-bit element shuffles with palignr.
3674   if (NumLaneElts == 2)
3675     return false;
3676
3677   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3678     unsigned i;
3679     for (i = 0; i != NumLaneElts; ++i) {
3680       if (Mask[i+l] >= 0)
3681         break;
3682     }
3683
3684     // Lane is all undef, go to next lane
3685     if (i == NumLaneElts)
3686       continue;
3687
3688     int Start = Mask[i+l];
3689
3690     // Make sure its in this lane in one of the sources
3691     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3692         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3693       return false;
3694
3695     // If not lane 0, then we must match lane 0
3696     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3697       return false;
3698
3699     // Correct second source to be contiguous with first source
3700     if (Start >= (int)NumElts)
3701       Start -= NumElts - NumLaneElts;
3702
3703     // Make sure we're shifting in the right direction.
3704     if (Start <= (int)(i+l))
3705       return false;
3706
3707     Start -= i;
3708
3709     // Check the rest of the elements to see if they are consecutive.
3710     for (++i; i != NumLaneElts; ++i) {
3711       int Idx = Mask[i+l];
3712
3713       // Make sure its in this lane
3714       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3715           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3716         return false;
3717
3718       // If not lane 0, then we must match lane 0
3719       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3720         return false;
3721
3722       if (Idx >= (int)NumElts)
3723         Idx -= NumElts - NumLaneElts;
3724
3725       if (!isUndefOrEqual(Idx, Start+i))
3726         return false;
3727
3728     }
3729   }
3730
3731   return true;
3732 }
3733
3734 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3735 /// the two vector operands have swapped position.
3736 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3737                                      unsigned NumElems) {
3738   for (unsigned i = 0; i != NumElems; ++i) {
3739     int idx = Mask[i];
3740     if (idx < 0)
3741       continue;
3742     else if (idx < (int)NumElems)
3743       Mask[i] = idx + NumElems;
3744     else
3745       Mask[i] = idx - NumElems;
3746   }
3747 }
3748
3749 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3750 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3751 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3752 /// reverse of what x86 shuffles want.
3753 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3754
3755   unsigned NumElems = VT.getVectorNumElements();
3756   unsigned NumLanes = VT.getSizeInBits()/128;
3757   unsigned NumLaneElems = NumElems/NumLanes;
3758
3759   if (NumLaneElems != 2 && NumLaneElems != 4)
3760     return false;
3761
3762   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3763   bool symetricMaskRequired =
3764     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3765
3766   // VSHUFPSY divides the resulting vector into 4 chunks.
3767   // The sources are also splitted into 4 chunks, and each destination
3768   // chunk must come from a different source chunk.
3769   //
3770   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3771   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3772   //
3773   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3774   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3775   //
3776   // VSHUFPDY divides the resulting vector into 4 chunks.
3777   // The sources are also splitted into 4 chunks, and each destination
3778   // chunk must come from a different source chunk.
3779   //
3780   //  SRC1 =>      X3       X2       X1       X0
3781   //  SRC2 =>      Y3       Y2       Y1       Y0
3782   //
3783   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3784   //
3785   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3786   unsigned HalfLaneElems = NumLaneElems/2;
3787   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3788     for (unsigned i = 0; i != NumLaneElems; ++i) {
3789       int Idx = Mask[i+l];
3790       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3791       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3792         return false;
3793       // For VSHUFPSY, the mask of the second half must be the same as the
3794       // first but with the appropriate offsets. This works in the same way as
3795       // VPERMILPS works with masks.
3796       if (!symetricMaskRequired || Idx < 0)
3797         continue;
3798       if (MaskVal[i] < 0) {
3799         MaskVal[i] = Idx - l;
3800         continue;
3801       }
3802       if ((signed)(Idx - l) != MaskVal[i])
3803         return false;
3804     }
3805   }
3806
3807   return true;
3808 }
3809
3810 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3811 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3812 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3813   if (!VT.is128BitVector())
3814     return false;
3815
3816   unsigned NumElems = VT.getVectorNumElements();
3817
3818   if (NumElems != 4)
3819     return false;
3820
3821   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3822   return isUndefOrEqual(Mask[0], 6) &&
3823          isUndefOrEqual(Mask[1], 7) &&
3824          isUndefOrEqual(Mask[2], 2) &&
3825          isUndefOrEqual(Mask[3], 3);
3826 }
3827
3828 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3829 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3830 /// <2, 3, 2, 3>
3831 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3832   if (!VT.is128BitVector())
3833     return false;
3834
3835   unsigned NumElems = VT.getVectorNumElements();
3836
3837   if (NumElems != 4)
3838     return false;
3839
3840   return isUndefOrEqual(Mask[0], 2) &&
3841          isUndefOrEqual(Mask[1], 3) &&
3842          isUndefOrEqual(Mask[2], 2) &&
3843          isUndefOrEqual(Mask[3], 3);
3844 }
3845
3846 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3847 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3848 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3849   if (!VT.is128BitVector())
3850     return false;
3851
3852   unsigned NumElems = VT.getVectorNumElements();
3853
3854   if (NumElems != 2 && NumElems != 4)
3855     return false;
3856
3857   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3858     if (!isUndefOrEqual(Mask[i], i + NumElems))
3859       return false;
3860
3861   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3862     if (!isUndefOrEqual(Mask[i], i))
3863       return false;
3864
3865   return true;
3866 }
3867
3868 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3869 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3870 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3871   if (!VT.is128BitVector())
3872     return false;
3873
3874   unsigned NumElems = VT.getVectorNumElements();
3875
3876   if (NumElems != 2 && NumElems != 4)
3877     return false;
3878
3879   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3880     if (!isUndefOrEqual(Mask[i], i))
3881       return false;
3882
3883   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3884     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3885       return false;
3886
3887   return true;
3888 }
3889
3890 //
3891 // Some special combinations that can be optimized.
3892 //
3893 static
3894 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3895                                SelectionDAG &DAG) {
3896   MVT VT = SVOp->getSimpleValueType(0);
3897   SDLoc dl(SVOp);
3898
3899   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3900     return SDValue();
3901
3902   ArrayRef<int> Mask = SVOp->getMask();
3903
3904   // These are the special masks that may be optimized.
3905   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3906   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3907   bool MatchEvenMask = true;
3908   bool MatchOddMask  = true;
3909   for (int i=0; i<8; ++i) {
3910     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3911       MatchEvenMask = false;
3912     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3913       MatchOddMask = false;
3914   }
3915
3916   if (!MatchEvenMask && !MatchOddMask)
3917     return SDValue();
3918
3919   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3920
3921   SDValue Op0 = SVOp->getOperand(0);
3922   SDValue Op1 = SVOp->getOperand(1);
3923
3924   if (MatchEvenMask) {
3925     // Shift the second operand right to 32 bits.
3926     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3927     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3928   } else {
3929     // Shift the first operand left to 32 bits.
3930     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3931     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3932   }
3933   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3934   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3935 }
3936
3937 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3938 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3939 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3940                          bool HasInt256, bool V2IsSplat = false) {
3941
3942   assert(VT.getSizeInBits() >= 128 &&
3943          "Unsupported vector type for unpckl");
3944
3945   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3946   unsigned NumLanes;
3947   unsigned NumOf256BitLanes;
3948   unsigned NumElts = VT.getVectorNumElements();
3949   if (VT.is256BitVector()) {
3950     if (NumElts != 4 && NumElts != 8 &&
3951         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3952     return false;
3953     NumLanes = 2;
3954     NumOf256BitLanes = 1;
3955   } else if (VT.is512BitVector()) {
3956     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3957            "Unsupported vector type for unpckh");
3958     NumLanes = 2;
3959     NumOf256BitLanes = 2;
3960   } else {
3961     NumLanes = 1;
3962     NumOf256BitLanes = 1;
3963   }
3964
3965   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
3966   unsigned NumLaneElts = NumEltsInStride/NumLanes;
3967
3968   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
3969     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
3970       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3971         int BitI  = Mask[l256*NumEltsInStride+l+i];
3972         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
3973         if (!isUndefOrEqual(BitI, j+l256*NumElts))
3974           return false;
3975         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
3976           return false;
3977         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
3978           return false;
3979       }
3980     }
3981   }
3982   return true;
3983 }
3984
3985 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3986 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3987 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
3988                          bool HasInt256, bool V2IsSplat = false) {
3989   assert(VT.getSizeInBits() >= 128 &&
3990          "Unsupported vector type for unpckh");
3991
3992   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3993   unsigned NumLanes;
3994   unsigned NumOf256BitLanes;
3995   unsigned NumElts = VT.getVectorNumElements();
3996   if (VT.is256BitVector()) {
3997     if (NumElts != 4 && NumElts != 8 &&
3998         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3999     return false;
4000     NumLanes = 2;
4001     NumOf256BitLanes = 1;
4002   } else if (VT.is512BitVector()) {
4003     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4004            "Unsupported vector type for unpckh");
4005     NumLanes = 2;
4006     NumOf256BitLanes = 2;
4007   } else {
4008     NumLanes = 1;
4009     NumOf256BitLanes = 1;
4010   }
4011
4012   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4013   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4014
4015   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4016     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4017       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4018         int BitI  = Mask[l256*NumEltsInStride+l+i];
4019         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4020         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4021           return false;
4022         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4023           return false;
4024         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4025           return false;
4026       }
4027     }
4028   }
4029   return true;
4030 }
4031
4032 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4033 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4034 /// <0, 0, 1, 1>
4035 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4036   unsigned NumElts = VT.getVectorNumElements();
4037   bool Is256BitVec = VT.is256BitVector();
4038
4039   if (VT.is512BitVector())
4040     return false;
4041   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4042          "Unsupported vector type for unpckh");
4043
4044   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4045       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4046     return false;
4047
4048   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4049   // FIXME: Need a better way to get rid of this, there's no latency difference
4050   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4051   // the former later. We should also remove the "_undef" special mask.
4052   if (NumElts == 4 && Is256BitVec)
4053     return false;
4054
4055   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4056   // independently on 128-bit lanes.
4057   unsigned NumLanes = VT.getSizeInBits()/128;
4058   unsigned NumLaneElts = NumElts/NumLanes;
4059
4060   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4061     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4062       int BitI  = Mask[l+i];
4063       int BitI1 = Mask[l+i+1];
4064
4065       if (!isUndefOrEqual(BitI, j))
4066         return false;
4067       if (!isUndefOrEqual(BitI1, j))
4068         return false;
4069     }
4070   }
4071
4072   return true;
4073 }
4074
4075 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4076 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4077 /// <2, 2, 3, 3>
4078 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4079   unsigned NumElts = VT.getVectorNumElements();
4080
4081   if (VT.is512BitVector())
4082     return false;
4083
4084   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4085          "Unsupported vector type for unpckh");
4086
4087   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4088       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4089     return false;
4090
4091   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4092   // independently on 128-bit lanes.
4093   unsigned NumLanes = VT.getSizeInBits()/128;
4094   unsigned NumLaneElts = NumElts/NumLanes;
4095
4096   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4097     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4098       int BitI  = Mask[l+i];
4099       int BitI1 = Mask[l+i+1];
4100       if (!isUndefOrEqual(BitI, j))
4101         return false;
4102       if (!isUndefOrEqual(BitI1, j))
4103         return false;
4104     }
4105   }
4106   return true;
4107 }
4108
4109 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4110 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4111 /// MOVSD, and MOVD, i.e. setting the lowest element.
4112 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4113   if (VT.getVectorElementType().getSizeInBits() < 32)
4114     return false;
4115   if (!VT.is128BitVector())
4116     return false;
4117
4118   unsigned NumElts = VT.getVectorNumElements();
4119
4120   if (!isUndefOrEqual(Mask[0], NumElts))
4121     return false;
4122
4123   for (unsigned i = 1; i != NumElts; ++i)
4124     if (!isUndefOrEqual(Mask[i], i))
4125       return false;
4126
4127   return true;
4128 }
4129
4130 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4131 /// as permutations between 128-bit chunks or halves. As an example: this
4132 /// shuffle bellow:
4133 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4134 /// The first half comes from the second half of V1 and the second half from the
4135 /// the second half of V2.
4136 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4137   if (!HasFp256 || !VT.is256BitVector())
4138     return false;
4139
4140   // The shuffle result is divided into half A and half B. In total the two
4141   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4142   // B must come from C, D, E or F.
4143   unsigned HalfSize = VT.getVectorNumElements()/2;
4144   bool MatchA = false, MatchB = false;
4145
4146   // Check if A comes from one of C, D, E, F.
4147   for (unsigned Half = 0; Half != 4; ++Half) {
4148     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4149       MatchA = true;
4150       break;
4151     }
4152   }
4153
4154   // Check if B comes from one of C, D, E, F.
4155   for (unsigned Half = 0; Half != 4; ++Half) {
4156     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4157       MatchB = true;
4158       break;
4159     }
4160   }
4161
4162   return MatchA && MatchB;
4163 }
4164
4165 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4166 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4167 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4168   MVT VT = SVOp->getSimpleValueType(0);
4169
4170   unsigned HalfSize = VT.getVectorNumElements()/2;
4171
4172   unsigned FstHalf = 0, SndHalf = 0;
4173   for (unsigned i = 0; i < HalfSize; ++i) {
4174     if (SVOp->getMaskElt(i) > 0) {
4175       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4176       break;
4177     }
4178   }
4179   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4180     if (SVOp->getMaskElt(i) > 0) {
4181       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4182       break;
4183     }
4184   }
4185
4186   return (FstHalf | (SndHalf << 4));
4187 }
4188
4189 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4190 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4191   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4192   if (EltSize < 32)
4193     return false;
4194
4195   unsigned NumElts = VT.getVectorNumElements();
4196   Imm8 = 0;
4197   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4198     for (unsigned i = 0; i != NumElts; ++i) {
4199       if (Mask[i] < 0)
4200         continue;
4201       Imm8 |= Mask[i] << (i*2);
4202     }
4203     return true;
4204   }
4205
4206   unsigned LaneSize = 4;
4207   SmallVector<int, 4> MaskVal(LaneSize, -1);
4208
4209   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4210     for (unsigned i = 0; i != LaneSize; ++i) {
4211       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4212         return false;
4213       if (Mask[i+l] < 0)
4214         continue;
4215       if (MaskVal[i] < 0) {
4216         MaskVal[i] = Mask[i+l] - l;
4217         Imm8 |= MaskVal[i] << (i*2);
4218         continue;
4219       }
4220       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4221         return false;
4222     }
4223   }
4224   return true;
4225 }
4226
4227 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4228 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4229 /// Note that VPERMIL mask matching is different depending whether theunderlying
4230 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4231 /// to the same elements of the low, but to the higher half of the source.
4232 /// In VPERMILPD the two lanes could be shuffled independently of each other
4233 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4234 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4235   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4236   if (VT.getSizeInBits() < 256 || EltSize < 32)
4237     return false;
4238   bool symetricMaskRequired = (EltSize == 32);
4239   unsigned NumElts = VT.getVectorNumElements();
4240
4241   unsigned NumLanes = VT.getSizeInBits()/128;
4242   unsigned LaneSize = NumElts/NumLanes;
4243   // 2 or 4 elements in one lane
4244
4245   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4246   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4247     for (unsigned i = 0; i != LaneSize; ++i) {
4248       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4249         return false;
4250       if (symetricMaskRequired) {
4251         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4252           ExpectedMaskVal[i] = Mask[i+l] - l;
4253           continue;
4254         }
4255         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4256           return false;
4257       }
4258     }
4259   }
4260   return true;
4261 }
4262
4263 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4264 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4265 /// element of vector 2 and the other elements to come from vector 1 in order.
4266 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4267                                bool V2IsSplat = false, bool V2IsUndef = false) {
4268   if (!VT.is128BitVector())
4269     return false;
4270
4271   unsigned NumOps = VT.getVectorNumElements();
4272   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4273     return false;
4274
4275   if (!isUndefOrEqual(Mask[0], 0))
4276     return false;
4277
4278   for (unsigned i = 1; i != NumOps; ++i)
4279     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4280           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4281           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4282       return false;
4283
4284   return true;
4285 }
4286
4287 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4288 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4289 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4290 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4291                            const X86Subtarget *Subtarget) {
4292   if (!Subtarget->hasSSE3())
4293     return false;
4294
4295   unsigned NumElems = VT.getVectorNumElements();
4296
4297   if ((VT.is128BitVector() && NumElems != 4) ||
4298       (VT.is256BitVector() && NumElems != 8) ||
4299       (VT.is512BitVector() && NumElems != 16))
4300     return false;
4301
4302   // "i+1" is the value the indexed mask element must have
4303   for (unsigned i = 0; i != NumElems; i += 2)
4304     if (!isUndefOrEqual(Mask[i], i+1) ||
4305         !isUndefOrEqual(Mask[i+1], i+1))
4306       return false;
4307
4308   return true;
4309 }
4310
4311 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4312 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4313 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4314 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4315                            const X86Subtarget *Subtarget) {
4316   if (!Subtarget->hasSSE3())
4317     return false;
4318
4319   unsigned NumElems = VT.getVectorNumElements();
4320
4321   if ((VT.is128BitVector() && NumElems != 4) ||
4322       (VT.is256BitVector() && NumElems != 8) ||
4323       (VT.is512BitVector() && NumElems != 16))
4324     return false;
4325
4326   // "i" is the value the indexed mask element must have
4327   for (unsigned i = 0; i != NumElems; i += 2)
4328     if (!isUndefOrEqual(Mask[i], i) ||
4329         !isUndefOrEqual(Mask[i+1], i))
4330       return false;
4331
4332   return true;
4333 }
4334
4335 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4336 /// specifies a shuffle of elements that is suitable for input to 256-bit
4337 /// version of MOVDDUP.
4338 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4339   if (!HasFp256 || !VT.is256BitVector())
4340     return false;
4341
4342   unsigned NumElts = VT.getVectorNumElements();
4343   if (NumElts != 4)
4344     return false;
4345
4346   for (unsigned i = 0; i != NumElts/2; ++i)
4347     if (!isUndefOrEqual(Mask[i], 0))
4348       return false;
4349   for (unsigned i = NumElts/2; i != NumElts; ++i)
4350     if (!isUndefOrEqual(Mask[i], NumElts/2))
4351       return false;
4352   return true;
4353 }
4354
4355 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4356 /// specifies a shuffle of elements that is suitable for input to 128-bit
4357 /// version of MOVDDUP.
4358 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4359   if (!VT.is128BitVector())
4360     return false;
4361
4362   unsigned e = VT.getVectorNumElements() / 2;
4363   for (unsigned i = 0; i != e; ++i)
4364     if (!isUndefOrEqual(Mask[i], i))
4365       return false;
4366   for (unsigned i = 0; i != e; ++i)
4367     if (!isUndefOrEqual(Mask[e+i], i))
4368       return false;
4369   return true;
4370 }
4371
4372 /// isVEXTRACTIndex - Return true if the specified
4373 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4374 /// suitable for instruction that extract 128 or 256 bit vectors
4375 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4376   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4377   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4378     return false;
4379
4380   // The index should be aligned on a vecWidth-bit boundary.
4381   uint64_t Index =
4382     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4383
4384   MVT VT = N->getSimpleValueType(0);
4385   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4386   bool Result = (Index * ElSize) % vecWidth == 0;
4387
4388   return Result;
4389 }
4390
4391 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4392 /// operand specifies a subvector insert that is suitable for input to
4393 /// insertion of 128 or 256-bit subvectors
4394 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4395   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4396   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4397     return false;
4398   // The index should be aligned on a vecWidth-bit boundary.
4399   uint64_t Index =
4400     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4401
4402   MVT VT = N->getSimpleValueType(0);
4403   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4404   bool Result = (Index * ElSize) % vecWidth == 0;
4405
4406   return Result;
4407 }
4408
4409 bool X86::isVINSERT128Index(SDNode *N) {
4410   return isVINSERTIndex(N, 128);
4411 }
4412
4413 bool X86::isVINSERT256Index(SDNode *N) {
4414   return isVINSERTIndex(N, 256);
4415 }
4416
4417 bool X86::isVEXTRACT128Index(SDNode *N) {
4418   return isVEXTRACTIndex(N, 128);
4419 }
4420
4421 bool X86::isVEXTRACT256Index(SDNode *N) {
4422   return isVEXTRACTIndex(N, 256);
4423 }
4424
4425 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4426 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4427 /// Handles 128-bit and 256-bit.
4428 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4429   MVT VT = N->getSimpleValueType(0);
4430
4431   assert((VT.getSizeInBits() >= 128) &&
4432          "Unsupported vector type for PSHUF/SHUFP");
4433
4434   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4435   // independently on 128-bit lanes.
4436   unsigned NumElts = VT.getVectorNumElements();
4437   unsigned NumLanes = VT.getSizeInBits()/128;
4438   unsigned NumLaneElts = NumElts/NumLanes;
4439
4440   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4441          "Only supports 2, 4 or 8 elements per lane");
4442
4443   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4444   unsigned Mask = 0;
4445   for (unsigned i = 0; i != NumElts; ++i) {
4446     int Elt = N->getMaskElt(i);
4447     if (Elt < 0) continue;
4448     Elt &= NumLaneElts - 1;
4449     unsigned ShAmt = (i << Shift) % 8;
4450     Mask |= Elt << ShAmt;
4451   }
4452
4453   return Mask;
4454 }
4455
4456 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4457 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4458 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4459   MVT VT = N->getSimpleValueType(0);
4460
4461   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4462          "Unsupported vector type for PSHUFHW");
4463
4464   unsigned NumElts = VT.getVectorNumElements();
4465
4466   unsigned Mask = 0;
4467   for (unsigned l = 0; l != NumElts; l += 8) {
4468     // 8 nodes per lane, but we only care about the last 4.
4469     for (unsigned i = 0; i < 4; ++i) {
4470       int Elt = N->getMaskElt(l+i+4);
4471       if (Elt < 0) continue;
4472       Elt &= 0x3; // only 2-bits.
4473       Mask |= Elt << (i * 2);
4474     }
4475   }
4476
4477   return Mask;
4478 }
4479
4480 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4481 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4482 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4483   MVT VT = N->getSimpleValueType(0);
4484
4485   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4486          "Unsupported vector type for PSHUFHW");
4487
4488   unsigned NumElts = VT.getVectorNumElements();
4489
4490   unsigned Mask = 0;
4491   for (unsigned l = 0; l != NumElts; l += 8) {
4492     // 8 nodes per lane, but we only care about the first 4.
4493     for (unsigned i = 0; i < 4; ++i) {
4494       int Elt = N->getMaskElt(l+i);
4495       if (Elt < 0) continue;
4496       Elt &= 0x3; // only 2-bits
4497       Mask |= Elt << (i * 2);
4498     }
4499   }
4500
4501   return Mask;
4502 }
4503
4504 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4505 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4506 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4507   MVT VT = SVOp->getSimpleValueType(0);
4508   unsigned EltSize = VT.is512BitVector() ? 1 :
4509     VT.getVectorElementType().getSizeInBits() >> 3;
4510
4511   unsigned NumElts = VT.getVectorNumElements();
4512   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4513   unsigned NumLaneElts = NumElts/NumLanes;
4514
4515   int Val = 0;
4516   unsigned i;
4517   for (i = 0; i != NumElts; ++i) {
4518     Val = SVOp->getMaskElt(i);
4519     if (Val >= 0)
4520       break;
4521   }
4522   if (Val >= (int)NumElts)
4523     Val -= NumElts - NumLaneElts;
4524
4525   assert(Val - i > 0 && "PALIGNR imm should be positive");
4526   return (Val - i) * EltSize;
4527 }
4528
4529 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4530   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4531   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4532     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4533
4534   uint64_t Index =
4535     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4536
4537   MVT VecVT = N->getOperand(0).getSimpleValueType();
4538   MVT ElVT = VecVT.getVectorElementType();
4539
4540   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4541   return Index / NumElemsPerChunk;
4542 }
4543
4544 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4545   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4546   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4547     llvm_unreachable("Illegal insert subvector for VINSERT");
4548
4549   uint64_t Index =
4550     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4551
4552   MVT VecVT = N->getSimpleValueType(0);
4553   MVT ElVT = VecVT.getVectorElementType();
4554
4555   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4556   return Index / NumElemsPerChunk;
4557 }
4558
4559 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4560 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4561 /// and VINSERTI128 instructions.
4562 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4563   return getExtractVEXTRACTImmediate(N, 128);
4564 }
4565
4566 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4567 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4568 /// and VINSERTI64x4 instructions.
4569 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4570   return getExtractVEXTRACTImmediate(N, 256);
4571 }
4572
4573 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4574 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4575 /// and VINSERTI128 instructions.
4576 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4577   return getInsertVINSERTImmediate(N, 128);
4578 }
4579
4580 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4581 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4582 /// and VINSERTI64x4 instructions.
4583 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4584   return getInsertVINSERTImmediate(N, 256);
4585 }
4586
4587 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4588 /// constant +0.0.
4589 bool X86::isZeroNode(SDValue Elt) {
4590   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4591     return CN->isNullValue();
4592   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4593     return CFP->getValueAPF().isPosZero();
4594   return false;
4595 }
4596
4597 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4598 /// their permute mask.
4599 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4600                                     SelectionDAG &DAG) {
4601   MVT VT = SVOp->getSimpleValueType(0);
4602   unsigned NumElems = VT.getVectorNumElements();
4603   SmallVector<int, 8> MaskVec;
4604
4605   for (unsigned i = 0; i != NumElems; ++i) {
4606     int Idx = SVOp->getMaskElt(i);
4607     if (Idx >= 0) {
4608       if (Idx < (int)NumElems)
4609         Idx += NumElems;
4610       else
4611         Idx -= NumElems;
4612     }
4613     MaskVec.push_back(Idx);
4614   }
4615   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4616                               SVOp->getOperand(0), &MaskVec[0]);
4617 }
4618
4619 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4620 /// match movhlps. The lower half elements should come from upper half of
4621 /// V1 (and in order), and the upper half elements should come from the upper
4622 /// half of V2 (and in order).
4623 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4624   if (!VT.is128BitVector())
4625     return false;
4626   if (VT.getVectorNumElements() != 4)
4627     return false;
4628   for (unsigned i = 0, e = 2; i != e; ++i)
4629     if (!isUndefOrEqual(Mask[i], i+2))
4630       return false;
4631   for (unsigned i = 2; i != 4; ++i)
4632     if (!isUndefOrEqual(Mask[i], i+4))
4633       return false;
4634   return true;
4635 }
4636
4637 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4638 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4639 /// required.
4640 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4641   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4642     return false;
4643   N = N->getOperand(0).getNode();
4644   if (!ISD::isNON_EXTLoad(N))
4645     return false;
4646   if (LD)
4647     *LD = cast<LoadSDNode>(N);
4648   return true;
4649 }
4650
4651 // Test whether the given value is a vector value which will be legalized
4652 // into a load.
4653 static bool WillBeConstantPoolLoad(SDNode *N) {
4654   if (N->getOpcode() != ISD::BUILD_VECTOR)
4655     return false;
4656
4657   // Check for any non-constant elements.
4658   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4659     switch (N->getOperand(i).getNode()->getOpcode()) {
4660     case ISD::UNDEF:
4661     case ISD::ConstantFP:
4662     case ISD::Constant:
4663       break;
4664     default:
4665       return false;
4666     }
4667
4668   // Vectors of all-zeros and all-ones are materialized with special
4669   // instructions rather than being loaded.
4670   return !ISD::isBuildVectorAllZeros(N) &&
4671          !ISD::isBuildVectorAllOnes(N);
4672 }
4673
4674 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4675 /// match movlp{s|d}. The lower half elements should come from lower half of
4676 /// V1 (and in order), and the upper half elements should come from the upper
4677 /// half of V2 (and in order). And since V1 will become the source of the
4678 /// MOVLP, it must be either a vector load or a scalar load to vector.
4679 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4680                                ArrayRef<int> Mask, MVT VT) {
4681   if (!VT.is128BitVector())
4682     return false;
4683
4684   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4685     return false;
4686   // Is V2 is a vector load, don't do this transformation. We will try to use
4687   // load folding shufps op.
4688   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4689     return false;
4690
4691   unsigned NumElems = VT.getVectorNumElements();
4692
4693   if (NumElems != 2 && NumElems != 4)
4694     return false;
4695   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4696     if (!isUndefOrEqual(Mask[i], i))
4697       return false;
4698   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4699     if (!isUndefOrEqual(Mask[i], i+NumElems))
4700       return false;
4701   return true;
4702 }
4703
4704 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4705 /// all the same.
4706 static bool isSplatVector(SDNode *N) {
4707   if (N->getOpcode() != ISD::BUILD_VECTOR)
4708     return false;
4709
4710   SDValue SplatValue = N->getOperand(0);
4711   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4712     if (N->getOperand(i) != SplatValue)
4713       return false;
4714   return true;
4715 }
4716
4717 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4718 /// to an zero vector.
4719 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4720 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4721   SDValue V1 = N->getOperand(0);
4722   SDValue V2 = N->getOperand(1);
4723   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4724   for (unsigned i = 0; i != NumElems; ++i) {
4725     int Idx = N->getMaskElt(i);
4726     if (Idx >= (int)NumElems) {
4727       unsigned Opc = V2.getOpcode();
4728       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4729         continue;
4730       if (Opc != ISD::BUILD_VECTOR ||
4731           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4732         return false;
4733     } else if (Idx >= 0) {
4734       unsigned Opc = V1.getOpcode();
4735       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4736         continue;
4737       if (Opc != ISD::BUILD_VECTOR ||
4738           !X86::isZeroNode(V1.getOperand(Idx)))
4739         return false;
4740     }
4741   }
4742   return true;
4743 }
4744
4745 /// getZeroVector - Returns a vector of specified type with all zero elements.
4746 ///
4747 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4748                              SelectionDAG &DAG, SDLoc dl) {
4749   assert(VT.isVector() && "Expected a vector type");
4750
4751   // Always build SSE zero vectors as <4 x i32> bitcasted
4752   // to their dest type. This ensures they get CSE'd.
4753   SDValue Vec;
4754   if (VT.is128BitVector()) {  // SSE
4755     if (Subtarget->hasSSE2()) {  // SSE2
4756       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4757       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4758     } else { // SSE1
4759       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4760       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4761     }
4762   } else if (VT.is256BitVector()) { // AVX
4763     if (Subtarget->hasInt256()) { // AVX2
4764       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4765       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4766       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4767                         array_lengthof(Ops));
4768     } else {
4769       // 256-bit logic and arithmetic instructions in AVX are all
4770       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4771       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4772       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4773       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4774                         array_lengthof(Ops));
4775     }
4776   } else if (VT.is512BitVector()) { // AVX-512
4777       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4778       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4779                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4780       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4781   } else
4782     llvm_unreachable("Unexpected vector type");
4783
4784   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4785 }
4786
4787 /// getOnesVector - Returns a vector of specified type with all bits set.
4788 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4789 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4790 /// Then bitcast to their original type, ensuring they get CSE'd.
4791 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4792                              SDLoc dl) {
4793   assert(VT.isVector() && "Expected a vector type");
4794
4795   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4796   SDValue Vec;
4797   if (VT.is256BitVector()) {
4798     if (HasInt256) { // AVX2
4799       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4800       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4801                         array_lengthof(Ops));
4802     } else { // AVX
4803       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4804       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4805     }
4806   } else if (VT.is128BitVector()) {
4807     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4808   } else
4809     llvm_unreachable("Unexpected vector type");
4810
4811   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4812 }
4813
4814 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4815 /// that point to V2 points to its first element.
4816 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4817   for (unsigned i = 0; i != NumElems; ++i) {
4818     if (Mask[i] > (int)NumElems) {
4819       Mask[i] = NumElems;
4820     }
4821   }
4822 }
4823
4824 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4825 /// operation of specified width.
4826 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4827                        SDValue V2) {
4828   unsigned NumElems = VT.getVectorNumElements();
4829   SmallVector<int, 8> Mask;
4830   Mask.push_back(NumElems);
4831   for (unsigned i = 1; i != NumElems; ++i)
4832     Mask.push_back(i);
4833   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4834 }
4835
4836 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4837 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4838                           SDValue V2) {
4839   unsigned NumElems = VT.getVectorNumElements();
4840   SmallVector<int, 8> Mask;
4841   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4842     Mask.push_back(i);
4843     Mask.push_back(i + NumElems);
4844   }
4845   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4846 }
4847
4848 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4849 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4850                           SDValue V2) {
4851   unsigned NumElems = VT.getVectorNumElements();
4852   SmallVector<int, 8> Mask;
4853   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4854     Mask.push_back(i + Half);
4855     Mask.push_back(i + NumElems + Half);
4856   }
4857   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4858 }
4859
4860 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4861 // a generic shuffle instruction because the target has no such instructions.
4862 // Generate shuffles which repeat i16 and i8 several times until they can be
4863 // represented by v4f32 and then be manipulated by target suported shuffles.
4864 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4865   MVT VT = V.getSimpleValueType();
4866   int NumElems = VT.getVectorNumElements();
4867   SDLoc dl(V);
4868
4869   while (NumElems > 4) {
4870     if (EltNo < NumElems/2) {
4871       V = getUnpackl(DAG, dl, VT, V, V);
4872     } else {
4873       V = getUnpackh(DAG, dl, VT, V, V);
4874       EltNo -= NumElems/2;
4875     }
4876     NumElems >>= 1;
4877   }
4878   return V;
4879 }
4880
4881 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4882 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4883   MVT VT = V.getSimpleValueType();
4884   SDLoc dl(V);
4885
4886   if (VT.is128BitVector()) {
4887     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4888     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4889     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4890                              &SplatMask[0]);
4891   } else if (VT.is256BitVector()) {
4892     // To use VPERMILPS to splat scalars, the second half of indicies must
4893     // refer to the higher part, which is a duplication of the lower one,
4894     // because VPERMILPS can only handle in-lane permutations.
4895     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4896                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4897
4898     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4899     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4900                              &SplatMask[0]);
4901   } else
4902     llvm_unreachable("Vector size not supported");
4903
4904   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4905 }
4906
4907 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4908 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4909   MVT SrcVT = SV->getSimpleValueType(0);
4910   SDValue V1 = SV->getOperand(0);
4911   SDLoc dl(SV);
4912
4913   int EltNo = SV->getSplatIndex();
4914   int NumElems = SrcVT.getVectorNumElements();
4915   bool Is256BitVec = SrcVT.is256BitVector();
4916
4917   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4918          "Unknown how to promote splat for type");
4919
4920   // Extract the 128-bit part containing the splat element and update
4921   // the splat element index when it refers to the higher register.
4922   if (Is256BitVec) {
4923     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4924     if (EltNo >= NumElems/2)
4925       EltNo -= NumElems/2;
4926   }
4927
4928   // All i16 and i8 vector types can't be used directly by a generic shuffle
4929   // instruction because the target has no such instruction. Generate shuffles
4930   // which repeat i16 and i8 several times until they fit in i32, and then can
4931   // be manipulated by target suported shuffles.
4932   MVT EltVT = SrcVT.getVectorElementType();
4933   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4934     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4935
4936   // Recreate the 256-bit vector and place the same 128-bit vector
4937   // into the low and high part. This is necessary because we want
4938   // to use VPERM* to shuffle the vectors
4939   if (Is256BitVec) {
4940     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4941   }
4942
4943   return getLegalSplat(DAG, V1, EltNo);
4944 }
4945
4946 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4947 /// vector of zero or undef vector.  This produces a shuffle where the low
4948 /// element of V2 is swizzled into the zero/undef vector, landing at element
4949 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4950 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4951                                            bool IsZero,
4952                                            const X86Subtarget *Subtarget,
4953                                            SelectionDAG &DAG) {
4954   MVT VT = V2.getSimpleValueType();
4955   SDValue V1 = IsZero
4956     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4957   unsigned NumElems = VT.getVectorNumElements();
4958   SmallVector<int, 16> MaskVec;
4959   for (unsigned i = 0; i != NumElems; ++i)
4960     // If this is the insertion idx, put the low elt of V2 here.
4961     MaskVec.push_back(i == Idx ? NumElems : i);
4962   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4963 }
4964
4965 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4966 /// target specific opcode. Returns true if the Mask could be calculated.
4967 /// Sets IsUnary to true if only uses one source.
4968 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4969                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4970   unsigned NumElems = VT.getVectorNumElements();
4971   SDValue ImmN;
4972
4973   IsUnary = false;
4974   switch(N->getOpcode()) {
4975   case X86ISD::SHUFP:
4976     ImmN = N->getOperand(N->getNumOperands()-1);
4977     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4978     break;
4979   case X86ISD::UNPCKH:
4980     DecodeUNPCKHMask(VT, Mask);
4981     break;
4982   case X86ISD::UNPCKL:
4983     DecodeUNPCKLMask(VT, Mask);
4984     break;
4985   case X86ISD::MOVHLPS:
4986     DecodeMOVHLPSMask(NumElems, Mask);
4987     break;
4988   case X86ISD::MOVLHPS:
4989     DecodeMOVLHPSMask(NumElems, Mask);
4990     break;
4991   case X86ISD::PALIGNR:
4992     ImmN = N->getOperand(N->getNumOperands()-1);
4993     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4994     break;
4995   case X86ISD::PSHUFD:
4996   case X86ISD::VPERMILP:
4997     ImmN = N->getOperand(N->getNumOperands()-1);
4998     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4999     IsUnary = true;
5000     break;
5001   case X86ISD::PSHUFHW:
5002     ImmN = N->getOperand(N->getNumOperands()-1);
5003     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5004     IsUnary = true;
5005     break;
5006   case X86ISD::PSHUFLW:
5007     ImmN = N->getOperand(N->getNumOperands()-1);
5008     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5009     IsUnary = true;
5010     break;
5011   case X86ISD::VPERMI:
5012     ImmN = N->getOperand(N->getNumOperands()-1);
5013     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5014     IsUnary = true;
5015     break;
5016   case X86ISD::MOVSS:
5017   case X86ISD::MOVSD: {
5018     // The index 0 always comes from the first element of the second source,
5019     // this is why MOVSS and MOVSD are used in the first place. The other
5020     // elements come from the other positions of the first source vector
5021     Mask.push_back(NumElems);
5022     for (unsigned i = 1; i != NumElems; ++i) {
5023       Mask.push_back(i);
5024     }
5025     break;
5026   }
5027   case X86ISD::VPERM2X128:
5028     ImmN = N->getOperand(N->getNumOperands()-1);
5029     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5030     if (Mask.empty()) return false;
5031     break;
5032   case X86ISD::MOVDDUP:
5033   case X86ISD::MOVLHPD:
5034   case X86ISD::MOVLPD:
5035   case X86ISD::MOVLPS:
5036   case X86ISD::MOVSHDUP:
5037   case X86ISD::MOVSLDUP:
5038     // Not yet implemented
5039     return false;
5040   default: llvm_unreachable("unknown target shuffle node");
5041   }
5042
5043   return true;
5044 }
5045
5046 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5047 /// element of the result of the vector shuffle.
5048 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5049                                    unsigned Depth) {
5050   if (Depth == 6)
5051     return SDValue();  // Limit search depth.
5052
5053   SDValue V = SDValue(N, 0);
5054   EVT VT = V.getValueType();
5055   unsigned Opcode = V.getOpcode();
5056
5057   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5058   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5059     int Elt = SV->getMaskElt(Index);
5060
5061     if (Elt < 0)
5062       return DAG.getUNDEF(VT.getVectorElementType());
5063
5064     unsigned NumElems = VT.getVectorNumElements();
5065     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5066                                          : SV->getOperand(1);
5067     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5068   }
5069
5070   // Recurse into target specific vector shuffles to find scalars.
5071   if (isTargetShuffle(Opcode)) {
5072     MVT ShufVT = V.getSimpleValueType();
5073     unsigned NumElems = ShufVT.getVectorNumElements();
5074     SmallVector<int, 16> ShuffleMask;
5075     bool IsUnary;
5076
5077     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5078       return SDValue();
5079
5080     int Elt = ShuffleMask[Index];
5081     if (Elt < 0)
5082       return DAG.getUNDEF(ShufVT.getVectorElementType());
5083
5084     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5085                                          : N->getOperand(1);
5086     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5087                                Depth+1);
5088   }
5089
5090   // Actual nodes that may contain scalar elements
5091   if (Opcode == ISD::BITCAST) {
5092     V = V.getOperand(0);
5093     EVT SrcVT = V.getValueType();
5094     unsigned NumElems = VT.getVectorNumElements();
5095
5096     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5097       return SDValue();
5098   }
5099
5100   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5101     return (Index == 0) ? V.getOperand(0)
5102                         : DAG.getUNDEF(VT.getVectorElementType());
5103
5104   if (V.getOpcode() == ISD::BUILD_VECTOR)
5105     return V.getOperand(Index);
5106
5107   return SDValue();
5108 }
5109
5110 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5111 /// shuffle operation which come from a consecutively from a zero. The
5112 /// search can start in two different directions, from left or right.
5113 /// We count undefs as zeros until PreferredNum is reached.
5114 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5115                                          unsigned NumElems, bool ZerosFromLeft,
5116                                          SelectionDAG &DAG,
5117                                          unsigned PreferredNum = -1U) {
5118   unsigned NumZeros = 0;
5119   for (unsigned i = 0; i != NumElems; ++i) {
5120     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5121     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5122     if (!Elt.getNode())
5123       break;
5124
5125     if (X86::isZeroNode(Elt))
5126       ++NumZeros;
5127     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5128       NumZeros = std::min(NumZeros + 1, PreferredNum);
5129     else
5130       break;
5131   }
5132
5133   return NumZeros;
5134 }
5135
5136 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5137 /// correspond consecutively to elements from one of the vector operands,
5138 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5139 static
5140 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5141                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5142                               unsigned NumElems, unsigned &OpNum) {
5143   bool SeenV1 = false;
5144   bool SeenV2 = false;
5145
5146   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5147     int Idx = SVOp->getMaskElt(i);
5148     // Ignore undef indicies
5149     if (Idx < 0)
5150       continue;
5151
5152     if (Idx < (int)NumElems)
5153       SeenV1 = true;
5154     else
5155       SeenV2 = true;
5156
5157     // Only accept consecutive elements from the same vector
5158     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5159       return false;
5160   }
5161
5162   OpNum = SeenV1 ? 0 : 1;
5163   return true;
5164 }
5165
5166 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5167 /// logical left shift of a vector.
5168 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5169                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5170   unsigned NumElems =
5171     SVOp->getSimpleValueType(0).getVectorNumElements();
5172   unsigned NumZeros = getNumOfConsecutiveZeros(
5173       SVOp, NumElems, false /* check zeros from right */, DAG,
5174       SVOp->getMaskElt(0));
5175   unsigned OpSrc;
5176
5177   if (!NumZeros)
5178     return false;
5179
5180   // Considering the elements in the mask that are not consecutive zeros,
5181   // check if they consecutively come from only one of the source vectors.
5182   //
5183   //               V1 = {X, A, B, C}     0
5184   //                         \  \  \    /
5185   //   vector_shuffle V1, V2 <1, 2, 3, X>
5186   //
5187   if (!isShuffleMaskConsecutive(SVOp,
5188             0,                   // Mask Start Index
5189             NumElems-NumZeros,   // Mask End Index(exclusive)
5190             NumZeros,            // Where to start looking in the src vector
5191             NumElems,            // Number of elements in vector
5192             OpSrc))              // Which source operand ?
5193     return false;
5194
5195   isLeft = false;
5196   ShAmt = NumZeros;
5197   ShVal = SVOp->getOperand(OpSrc);
5198   return true;
5199 }
5200
5201 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5202 /// logical left shift of a vector.
5203 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5204                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5205   unsigned NumElems =
5206     SVOp->getSimpleValueType(0).getVectorNumElements();
5207   unsigned NumZeros = getNumOfConsecutiveZeros(
5208       SVOp, NumElems, true /* check zeros from left */, DAG,
5209       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5210   unsigned OpSrc;
5211
5212   if (!NumZeros)
5213     return false;
5214
5215   // Considering the elements in the mask that are not consecutive zeros,
5216   // check if they consecutively come from only one of the source vectors.
5217   //
5218   //                           0    { A, B, X, X } = V2
5219   //                          / \    /  /
5220   //   vector_shuffle V1, V2 <X, X, 4, 5>
5221   //
5222   if (!isShuffleMaskConsecutive(SVOp,
5223             NumZeros,     // Mask Start Index
5224             NumElems,     // Mask End Index(exclusive)
5225             0,            // Where to start looking in the src vector
5226             NumElems,     // Number of elements in vector
5227             OpSrc))       // Which source operand ?
5228     return false;
5229
5230   isLeft = true;
5231   ShAmt = NumZeros;
5232   ShVal = SVOp->getOperand(OpSrc);
5233   return true;
5234 }
5235
5236 /// isVectorShift - Returns true if the shuffle can be implemented as a
5237 /// logical left or right shift of a vector.
5238 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5239                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5240   // Although the logic below support any bitwidth size, there are no
5241   // shift instructions which handle more than 128-bit vectors.
5242   if (!SVOp->getSimpleValueType(0).is128BitVector())
5243     return false;
5244
5245   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5246       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5247     return true;
5248
5249   return false;
5250 }
5251
5252 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5253 ///
5254 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5255                                        unsigned NumNonZero, unsigned NumZero,
5256                                        SelectionDAG &DAG,
5257                                        const X86Subtarget* Subtarget,
5258                                        const TargetLowering &TLI) {
5259   if (NumNonZero > 8)
5260     return SDValue();
5261
5262   SDLoc dl(Op);
5263   SDValue V(0, 0);
5264   bool First = true;
5265   for (unsigned i = 0; i < 16; ++i) {
5266     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5267     if (ThisIsNonZero && First) {
5268       if (NumZero)
5269         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5270       else
5271         V = DAG.getUNDEF(MVT::v8i16);
5272       First = false;
5273     }
5274
5275     if ((i & 1) != 0) {
5276       SDValue ThisElt(0, 0), LastElt(0, 0);
5277       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5278       if (LastIsNonZero) {
5279         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5280                               MVT::i16, Op.getOperand(i-1));
5281       }
5282       if (ThisIsNonZero) {
5283         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5284         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5285                               ThisElt, DAG.getConstant(8, MVT::i8));
5286         if (LastIsNonZero)
5287           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5288       } else
5289         ThisElt = LastElt;
5290
5291       if (ThisElt.getNode())
5292         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5293                         DAG.getIntPtrConstant(i/2));
5294     }
5295   }
5296
5297   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5298 }
5299
5300 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5301 ///
5302 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5303                                      unsigned NumNonZero, unsigned NumZero,
5304                                      SelectionDAG &DAG,
5305                                      const X86Subtarget* Subtarget,
5306                                      const TargetLowering &TLI) {
5307   if (NumNonZero > 4)
5308     return SDValue();
5309
5310   SDLoc dl(Op);
5311   SDValue V(0, 0);
5312   bool First = true;
5313   for (unsigned i = 0; i < 8; ++i) {
5314     bool isNonZero = (NonZeros & (1 << i)) != 0;
5315     if (isNonZero) {
5316       if (First) {
5317         if (NumZero)
5318           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5319         else
5320           V = DAG.getUNDEF(MVT::v8i16);
5321         First = false;
5322       }
5323       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5324                       MVT::v8i16, V, Op.getOperand(i),
5325                       DAG.getIntPtrConstant(i));
5326     }
5327   }
5328
5329   return V;
5330 }
5331
5332 /// getVShift - Return a vector logical shift node.
5333 ///
5334 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5335                          unsigned NumBits, SelectionDAG &DAG,
5336                          const TargetLowering &TLI, SDLoc dl) {
5337   assert(VT.is128BitVector() && "Unknown type for VShift");
5338   EVT ShVT = MVT::v2i64;
5339   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5340   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5341   return DAG.getNode(ISD::BITCAST, dl, VT,
5342                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5343                              DAG.getConstant(NumBits,
5344                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5345 }
5346
5347 static SDValue
5348 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5349
5350   // Check if the scalar load can be widened into a vector load. And if
5351   // the address is "base + cst" see if the cst can be "absorbed" into
5352   // the shuffle mask.
5353   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5354     SDValue Ptr = LD->getBasePtr();
5355     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5356       return SDValue();
5357     EVT PVT = LD->getValueType(0);
5358     if (PVT != MVT::i32 && PVT != MVT::f32)
5359       return SDValue();
5360
5361     int FI = -1;
5362     int64_t Offset = 0;
5363     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5364       FI = FINode->getIndex();
5365       Offset = 0;
5366     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5367                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5368       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5369       Offset = Ptr.getConstantOperandVal(1);
5370       Ptr = Ptr.getOperand(0);
5371     } else {
5372       return SDValue();
5373     }
5374
5375     // FIXME: 256-bit vector instructions don't require a strict alignment,
5376     // improve this code to support it better.
5377     unsigned RequiredAlign = VT.getSizeInBits()/8;
5378     SDValue Chain = LD->getChain();
5379     // Make sure the stack object alignment is at least 16 or 32.
5380     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5381     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5382       if (MFI->isFixedObjectIndex(FI)) {
5383         // Can't change the alignment. FIXME: It's possible to compute
5384         // the exact stack offset and reference FI + adjust offset instead.
5385         // If someone *really* cares about this. That's the way to implement it.
5386         return SDValue();
5387       } else {
5388         MFI->setObjectAlignment(FI, RequiredAlign);
5389       }
5390     }
5391
5392     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5393     // Ptr + (Offset & ~15).
5394     if (Offset < 0)
5395       return SDValue();
5396     if ((Offset % RequiredAlign) & 3)
5397       return SDValue();
5398     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5399     if (StartOffset)
5400       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5401                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5402
5403     int EltNo = (Offset - StartOffset) >> 2;
5404     unsigned NumElems = VT.getVectorNumElements();
5405
5406     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5407     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5408                              LD->getPointerInfo().getWithOffset(StartOffset),
5409                              false, false, false, 0);
5410
5411     SmallVector<int, 8> Mask;
5412     for (unsigned i = 0; i != NumElems; ++i)
5413       Mask.push_back(EltNo);
5414
5415     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5416   }
5417
5418   return SDValue();
5419 }
5420
5421 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5422 /// vector of type 'VT', see if the elements can be replaced by a single large
5423 /// load which has the same value as a build_vector whose operands are 'elts'.
5424 ///
5425 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5426 ///
5427 /// FIXME: we'd also like to handle the case where the last elements are zero
5428 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5429 /// There's even a handy isZeroNode for that purpose.
5430 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5431                                         SDLoc &DL, SelectionDAG &DAG,
5432                                         bool isAfterLegalize) {
5433   EVT EltVT = VT.getVectorElementType();
5434   unsigned NumElems = Elts.size();
5435
5436   LoadSDNode *LDBase = NULL;
5437   unsigned LastLoadedElt = -1U;
5438
5439   // For each element in the initializer, see if we've found a load or an undef.
5440   // If we don't find an initial load element, or later load elements are
5441   // non-consecutive, bail out.
5442   for (unsigned i = 0; i < NumElems; ++i) {
5443     SDValue Elt = Elts[i];
5444
5445     if (!Elt.getNode() ||
5446         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5447       return SDValue();
5448     if (!LDBase) {
5449       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5450         return SDValue();
5451       LDBase = cast<LoadSDNode>(Elt.getNode());
5452       LastLoadedElt = i;
5453       continue;
5454     }
5455     if (Elt.getOpcode() == ISD::UNDEF)
5456       continue;
5457
5458     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5459     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5460       return SDValue();
5461     LastLoadedElt = i;
5462   }
5463
5464   // If we have found an entire vector of loads and undefs, then return a large
5465   // load of the entire vector width starting at the base pointer.  If we found
5466   // consecutive loads for the low half, generate a vzext_load node.
5467   if (LastLoadedElt == NumElems - 1) {
5468
5469     if (isAfterLegalize &&
5470         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5471       return SDValue();
5472
5473     SDValue NewLd = SDValue();
5474
5475     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5476       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5477                           LDBase->getPointerInfo(),
5478                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5479                           LDBase->isInvariant(), 0);
5480     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5481                         LDBase->getPointerInfo(),
5482                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5483                         LDBase->isInvariant(), LDBase->getAlignment());
5484
5485     if (LDBase->hasAnyUseOfValue(1)) {
5486       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5487                                      SDValue(LDBase, 1),
5488                                      SDValue(NewLd.getNode(), 1));
5489       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5490       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5491                              SDValue(NewLd.getNode(), 1));
5492     }
5493
5494     return NewLd;
5495   }
5496   if (NumElems == 4 && LastLoadedElt == 1 &&
5497       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5498     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5499     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5500     SDValue ResNode =
5501         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5502                                 array_lengthof(Ops), MVT::i64,
5503                                 LDBase->getPointerInfo(),
5504                                 LDBase->getAlignment(),
5505                                 false/*isVolatile*/, true/*ReadMem*/,
5506                                 false/*WriteMem*/);
5507
5508     // Make sure the newly-created LOAD is in the same position as LDBase in
5509     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5510     // update uses of LDBase's output chain to use the TokenFactor.
5511     if (LDBase->hasAnyUseOfValue(1)) {
5512       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5513                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5514       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5515       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5516                              SDValue(ResNode.getNode(), 1));
5517     }
5518
5519     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5520   }
5521   return SDValue();
5522 }
5523
5524 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5525 /// to generate a splat value for the following cases:
5526 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5527 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5528 /// a scalar load, or a constant.
5529 /// The VBROADCAST node is returned when a pattern is found,
5530 /// or SDValue() otherwise.
5531 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5532                                     SelectionDAG &DAG) {
5533   if (!Subtarget->hasFp256())
5534     return SDValue();
5535
5536   MVT VT = Op.getSimpleValueType();
5537   SDLoc dl(Op);
5538
5539   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5540          "Unsupported vector type for broadcast.");
5541
5542   SDValue Ld;
5543   bool ConstSplatVal;
5544
5545   switch (Op.getOpcode()) {
5546     default:
5547       // Unknown pattern found.
5548       return SDValue();
5549
5550     case ISD::BUILD_VECTOR: {
5551       // The BUILD_VECTOR node must be a splat.
5552       if (!isSplatVector(Op.getNode()))
5553         return SDValue();
5554
5555       Ld = Op.getOperand(0);
5556       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5557                      Ld.getOpcode() == ISD::ConstantFP);
5558
5559       // The suspected load node has several users. Make sure that all
5560       // of its users are from the BUILD_VECTOR node.
5561       // Constants may have multiple users.
5562       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5563         return SDValue();
5564       break;
5565     }
5566
5567     case ISD::VECTOR_SHUFFLE: {
5568       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5569
5570       // Shuffles must have a splat mask where the first element is
5571       // broadcasted.
5572       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5573         return SDValue();
5574
5575       SDValue Sc = Op.getOperand(0);
5576       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5577           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5578
5579         if (!Subtarget->hasInt256())
5580           return SDValue();
5581
5582         // Use the register form of the broadcast instruction available on AVX2.
5583         if (VT.getSizeInBits() >= 256)
5584           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5585         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5586       }
5587
5588       Ld = Sc.getOperand(0);
5589       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5590                        Ld.getOpcode() == ISD::ConstantFP);
5591
5592       // The scalar_to_vector node and the suspected
5593       // load node must have exactly one user.
5594       // Constants may have multiple users.
5595
5596       // AVX-512 has register version of the broadcast
5597       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5598         Ld.getValueType().getSizeInBits() >= 32;
5599       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5600           !hasRegVer))
5601         return SDValue();
5602       break;
5603     }
5604   }
5605
5606   bool IsGE256 = (VT.getSizeInBits() >= 256);
5607
5608   // Handle the broadcasting a single constant scalar from the constant pool
5609   // into a vector. On Sandybridge it is still better to load a constant vector
5610   // from the constant pool and not to broadcast it from a scalar.
5611   if (ConstSplatVal && Subtarget->hasInt256()) {
5612     EVT CVT = Ld.getValueType();
5613     assert(!CVT.isVector() && "Must not broadcast a vector type");
5614     unsigned ScalarSize = CVT.getSizeInBits();
5615
5616     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5617       const Constant *C = 0;
5618       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5619         C = CI->getConstantIntValue();
5620       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5621         C = CF->getConstantFPValue();
5622
5623       assert(C && "Invalid constant type");
5624
5625       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5626       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5627       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5628       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5629                        MachinePointerInfo::getConstantPool(),
5630                        false, false, false, Alignment);
5631
5632       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5633     }
5634   }
5635
5636   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5637   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5638
5639   // Handle AVX2 in-register broadcasts.
5640   if (!IsLoad && Subtarget->hasInt256() &&
5641       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5642     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5643
5644   // The scalar source must be a normal load.
5645   if (!IsLoad)
5646     return SDValue();
5647
5648   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5649     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5650
5651   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5652   // double since there is no vbroadcastsd xmm
5653   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5654     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5655       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5656   }
5657
5658   // Unsupported broadcast.
5659   return SDValue();
5660 }
5661
5662 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5663   MVT VT = Op.getSimpleValueType();
5664
5665   // Skip if insert_vec_elt is not supported.
5666   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5667   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5668     return SDValue();
5669
5670   SDLoc DL(Op);
5671   unsigned NumElems = Op.getNumOperands();
5672
5673   SDValue VecIn1;
5674   SDValue VecIn2;
5675   SmallVector<unsigned, 4> InsertIndices;
5676   SmallVector<int, 8> Mask(NumElems, -1);
5677
5678   for (unsigned i = 0; i != NumElems; ++i) {
5679     unsigned Opc = Op.getOperand(i).getOpcode();
5680
5681     if (Opc == ISD::UNDEF)
5682       continue;
5683
5684     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5685       // Quit if more than 1 elements need inserting.
5686       if (InsertIndices.size() > 1)
5687         return SDValue();
5688
5689       InsertIndices.push_back(i);
5690       continue;
5691     }
5692
5693     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5694     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5695
5696     // Quit if extracted from vector of different type.
5697     if (ExtractedFromVec.getValueType() != VT)
5698       return SDValue();
5699
5700     // Quit if non-constant index.
5701     if (!isa<ConstantSDNode>(ExtIdx))
5702       return SDValue();
5703
5704     if (VecIn1.getNode() == 0)
5705       VecIn1 = ExtractedFromVec;
5706     else if (VecIn1 != ExtractedFromVec) {
5707       if (VecIn2.getNode() == 0)
5708         VecIn2 = ExtractedFromVec;
5709       else if (VecIn2 != ExtractedFromVec)
5710         // Quit if more than 2 vectors to shuffle
5711         return SDValue();
5712     }
5713
5714     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5715
5716     if (ExtractedFromVec == VecIn1)
5717       Mask[i] = Idx;
5718     else if (ExtractedFromVec == VecIn2)
5719       Mask[i] = Idx + NumElems;
5720   }
5721
5722   if (VecIn1.getNode() == 0)
5723     return SDValue();
5724
5725   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5726   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5727   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5728     unsigned Idx = InsertIndices[i];
5729     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5730                      DAG.getIntPtrConstant(Idx));
5731   }
5732
5733   return NV;
5734 }
5735
5736 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5737 SDValue
5738 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5739
5740   MVT VT = Op.getSimpleValueType();
5741   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5742          "Unexpected type in LowerBUILD_VECTORvXi1!");
5743
5744   SDLoc dl(Op);
5745   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5746     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5747     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5748                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5749     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5750                        Ops, VT.getVectorNumElements());
5751   }
5752
5753   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5754     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5755     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5756                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5757     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5758                        Ops, VT.getVectorNumElements());
5759   }
5760
5761   bool AllContants = true;
5762   uint64_t Immediate = 0;
5763   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5764     SDValue In = Op.getOperand(idx);
5765     if (In.getOpcode() == ISD::UNDEF)
5766       continue;
5767     if (!isa<ConstantSDNode>(In)) {
5768       AllContants = false;
5769       break;
5770     }
5771     if (cast<ConstantSDNode>(In)->getZExtValue())
5772       Immediate |= (1ULL << idx);
5773   }
5774
5775   if (AllContants) {
5776     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5777       DAG.getConstant(Immediate, MVT::i16));
5778     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5779                        DAG.getIntPtrConstant(0));
5780   }
5781
5782   // Splat vector (with undefs)
5783   SDValue In = Op.getOperand(0);
5784   for (unsigned i = 1, e = Op.getNumOperands(); i != e; ++i) {
5785     if (Op.getOperand(i) != In && Op.getOperand(i).getOpcode() != ISD::UNDEF)
5786       llvm_unreachable("Unsupported predicate operation");
5787   }
5788
5789   SDValue EFLAGS, X86CC;
5790   if (In.getOpcode() == ISD::SETCC) {
5791     SDValue Op0 = In.getOperand(0);
5792     SDValue Op1 = In.getOperand(1);
5793     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5794     bool isFP = Op1.getValueType().isFloatingPoint();
5795     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5796
5797     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5798
5799     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5800     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5801     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5802   } else if (In.getOpcode() == X86ISD::SETCC) {
5803     X86CC = In.getOperand(0);
5804     EFLAGS = In.getOperand(1);
5805   } else {
5806     // The algorithm:
5807     //   Bit1 = In & 0x1
5808     //   if (Bit1 != 0)
5809     //     ZF = 0
5810     //   else
5811     //     ZF = 1
5812     //   if (ZF == 0)
5813     //     res = allOnes ### CMOVNE -1, %res
5814     //   else
5815     //     res = allZero
5816     MVT InVT = In.getSimpleValueType();
5817     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5818     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5819     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5820   }
5821
5822   if (VT == MVT::v16i1) {
5823     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5824     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5825     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5826           Cst0, Cst1, X86CC, EFLAGS);
5827     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5828   }
5829
5830   if (VT == MVT::v8i1) {
5831     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5832     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5833     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5834           Cst0, Cst1, X86CC, EFLAGS);
5835     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5836     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5837   }
5838   llvm_unreachable("Unsupported predicate operation");
5839 }
5840
5841 SDValue
5842 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5843   SDLoc dl(Op);
5844
5845   MVT VT = Op.getSimpleValueType();
5846   MVT ExtVT = VT.getVectorElementType();
5847   unsigned NumElems = Op.getNumOperands();
5848
5849   // Generate vectors for predicate vectors.
5850   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5851     return LowerBUILD_VECTORvXi1(Op, DAG);
5852
5853   // Vectors containing all zeros can be matched by pxor and xorps later
5854   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5855     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5856     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5857     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5858       return Op;
5859
5860     return getZeroVector(VT, Subtarget, DAG, dl);
5861   }
5862
5863   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5864   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5865   // vpcmpeqd on 256-bit vectors.
5866   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5867     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5868       return Op;
5869
5870     if (!VT.is512BitVector())
5871       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5872   }
5873
5874   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5875   if (Broadcast.getNode())
5876     return Broadcast;
5877
5878   unsigned EVTBits = ExtVT.getSizeInBits();
5879
5880   unsigned NumZero  = 0;
5881   unsigned NumNonZero = 0;
5882   unsigned NonZeros = 0;
5883   bool IsAllConstants = true;
5884   SmallSet<SDValue, 8> Values;
5885   for (unsigned i = 0; i < NumElems; ++i) {
5886     SDValue Elt = Op.getOperand(i);
5887     if (Elt.getOpcode() == ISD::UNDEF)
5888       continue;
5889     Values.insert(Elt);
5890     if (Elt.getOpcode() != ISD::Constant &&
5891         Elt.getOpcode() != ISD::ConstantFP)
5892       IsAllConstants = false;
5893     if (X86::isZeroNode(Elt))
5894       NumZero++;
5895     else {
5896       NonZeros |= (1 << i);
5897       NumNonZero++;
5898     }
5899   }
5900
5901   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5902   if (NumNonZero == 0)
5903     return DAG.getUNDEF(VT);
5904
5905   // Special case for single non-zero, non-undef, element.
5906   if (NumNonZero == 1) {
5907     unsigned Idx = countTrailingZeros(NonZeros);
5908     SDValue Item = Op.getOperand(Idx);
5909
5910     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5911     // the value are obviously zero, truncate the value to i32 and do the
5912     // insertion that way.  Only do this if the value is non-constant or if the
5913     // value is a constant being inserted into element 0.  It is cheaper to do
5914     // a constant pool load than it is to do a movd + shuffle.
5915     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5916         (!IsAllConstants || Idx == 0)) {
5917       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5918         // Handle SSE only.
5919         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5920         EVT VecVT = MVT::v4i32;
5921         unsigned VecElts = 4;
5922
5923         // Truncate the value (which may itself be a constant) to i32, and
5924         // convert it to a vector with movd (S2V+shuffle to zero extend).
5925         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5926         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5927         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5928
5929         // Now we have our 32-bit value zero extended in the low element of
5930         // a vector.  If Idx != 0, swizzle it into place.
5931         if (Idx != 0) {
5932           SmallVector<int, 4> Mask;
5933           Mask.push_back(Idx);
5934           for (unsigned i = 1; i != VecElts; ++i)
5935             Mask.push_back(i);
5936           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5937                                       &Mask[0]);
5938         }
5939         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5940       }
5941     }
5942
5943     // If we have a constant or non-constant insertion into the low element of
5944     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5945     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5946     // depending on what the source datatype is.
5947     if (Idx == 0) {
5948       if (NumZero == 0)
5949         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5950
5951       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5952           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5953         if (VT.is256BitVector() || VT.is512BitVector()) {
5954           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5955           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5956                              Item, DAG.getIntPtrConstant(0));
5957         }
5958         assert(VT.is128BitVector() && "Expected an SSE value type!");
5959         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5960         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5961         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5962       }
5963
5964       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5965         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5966         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5967         if (VT.is256BitVector()) {
5968           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5969           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5970         } else {
5971           assert(VT.is128BitVector() && "Expected an SSE value type!");
5972           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5973         }
5974         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5975       }
5976     }
5977
5978     // Is it a vector logical left shift?
5979     if (NumElems == 2 && Idx == 1 &&
5980         X86::isZeroNode(Op.getOperand(0)) &&
5981         !X86::isZeroNode(Op.getOperand(1))) {
5982       unsigned NumBits = VT.getSizeInBits();
5983       return getVShift(true, VT,
5984                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5985                                    VT, Op.getOperand(1)),
5986                        NumBits/2, DAG, *this, dl);
5987     }
5988
5989     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5990       return SDValue();
5991
5992     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5993     // is a non-constant being inserted into an element other than the low one,
5994     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5995     // movd/movss) to move this into the low element, then shuffle it into
5996     // place.
5997     if (EVTBits == 32) {
5998       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5999
6000       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6001       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6002       SmallVector<int, 8> MaskVec;
6003       for (unsigned i = 0; i != NumElems; ++i)
6004         MaskVec.push_back(i == Idx ? 0 : 1);
6005       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6006     }
6007   }
6008
6009   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6010   if (Values.size() == 1) {
6011     if (EVTBits == 32) {
6012       // Instead of a shuffle like this:
6013       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6014       // Check if it's possible to issue this instead.
6015       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6016       unsigned Idx = countTrailingZeros(NonZeros);
6017       SDValue Item = Op.getOperand(Idx);
6018       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6019         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6020     }
6021     return SDValue();
6022   }
6023
6024   // A vector full of immediates; various special cases are already
6025   // handled, so this is best done with a single constant-pool load.
6026   if (IsAllConstants)
6027     return SDValue();
6028
6029   // For AVX-length vectors, build the individual 128-bit pieces and use
6030   // shuffles to put them in place.
6031   if (VT.is256BitVector()) {
6032     SmallVector<SDValue, 32> V;
6033     for (unsigned i = 0; i != NumElems; ++i)
6034       V.push_back(Op.getOperand(i));
6035
6036     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6037
6038     // Build both the lower and upper subvector.
6039     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6040     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6041                                 NumElems/2);
6042
6043     // Recreate the wider vector with the lower and upper part.
6044     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6045   }
6046
6047   // Let legalizer expand 2-wide build_vectors.
6048   if (EVTBits == 64) {
6049     if (NumNonZero == 1) {
6050       // One half is zero or undef.
6051       unsigned Idx = countTrailingZeros(NonZeros);
6052       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6053                                  Op.getOperand(Idx));
6054       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6055     }
6056     return SDValue();
6057   }
6058
6059   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6060   if (EVTBits == 8 && NumElems == 16) {
6061     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6062                                         Subtarget, *this);
6063     if (V.getNode()) return V;
6064   }
6065
6066   if (EVTBits == 16 && NumElems == 8) {
6067     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6068                                       Subtarget, *this);
6069     if (V.getNode()) return V;
6070   }
6071
6072   // If element VT is == 32 bits, turn it into a number of shuffles.
6073   SmallVector<SDValue, 8> V(NumElems);
6074   if (NumElems == 4 && NumZero > 0) {
6075     for (unsigned i = 0; i < 4; ++i) {
6076       bool isZero = !(NonZeros & (1 << i));
6077       if (isZero)
6078         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6079       else
6080         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6081     }
6082
6083     for (unsigned i = 0; i < 2; ++i) {
6084       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6085         default: break;
6086         case 0:
6087           V[i] = V[i*2];  // Must be a zero vector.
6088           break;
6089         case 1:
6090           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6091           break;
6092         case 2:
6093           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6094           break;
6095         case 3:
6096           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6097           break;
6098       }
6099     }
6100
6101     bool Reverse1 = (NonZeros & 0x3) == 2;
6102     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6103     int MaskVec[] = {
6104       Reverse1 ? 1 : 0,
6105       Reverse1 ? 0 : 1,
6106       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6107       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6108     };
6109     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6110   }
6111
6112   if (Values.size() > 1 && VT.is128BitVector()) {
6113     // Check for a build vector of consecutive loads.
6114     for (unsigned i = 0; i < NumElems; ++i)
6115       V[i] = Op.getOperand(i);
6116
6117     // Check for elements which are consecutive loads.
6118     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6119     if (LD.getNode())
6120       return LD;
6121
6122     // Check for a build vector from mostly shuffle plus few inserting.
6123     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6124     if (Sh.getNode())
6125       return Sh;
6126
6127     // For SSE 4.1, use insertps to put the high elements into the low element.
6128     if (getSubtarget()->hasSSE41()) {
6129       SDValue Result;
6130       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6131         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6132       else
6133         Result = DAG.getUNDEF(VT);
6134
6135       for (unsigned i = 1; i < NumElems; ++i) {
6136         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6137         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6138                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6139       }
6140       return Result;
6141     }
6142
6143     // Otherwise, expand into a number of unpckl*, start by extending each of
6144     // our (non-undef) elements to the full vector width with the element in the
6145     // bottom slot of the vector (which generates no code for SSE).
6146     for (unsigned i = 0; i < NumElems; ++i) {
6147       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6148         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6149       else
6150         V[i] = DAG.getUNDEF(VT);
6151     }
6152
6153     // Next, we iteratively mix elements, e.g. for v4f32:
6154     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6155     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6156     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6157     unsigned EltStride = NumElems >> 1;
6158     while (EltStride != 0) {
6159       for (unsigned i = 0; i < EltStride; ++i) {
6160         // If V[i+EltStride] is undef and this is the first round of mixing,
6161         // then it is safe to just drop this shuffle: V[i] is already in the
6162         // right place, the one element (since it's the first round) being
6163         // inserted as undef can be dropped.  This isn't safe for successive
6164         // rounds because they will permute elements within both vectors.
6165         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6166             EltStride == NumElems/2)
6167           continue;
6168
6169         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6170       }
6171       EltStride >>= 1;
6172     }
6173     return V[0];
6174   }
6175   return SDValue();
6176 }
6177
6178 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6179 // to create 256-bit vectors from two other 128-bit ones.
6180 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6181   SDLoc dl(Op);
6182   MVT ResVT = Op.getSimpleValueType();
6183
6184   assert((ResVT.is256BitVector() ||
6185           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6186
6187   SDValue V1 = Op.getOperand(0);
6188   SDValue V2 = Op.getOperand(1);
6189   unsigned NumElems = ResVT.getVectorNumElements();
6190   if(ResVT.is256BitVector())
6191     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6192
6193   if (Op.getNumOperands() == 4) {
6194     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6195                                 ResVT.getVectorNumElements()/2);
6196     SDValue V3 = Op.getOperand(2);
6197     SDValue V4 = Op.getOperand(3);
6198     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6199       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6200   }
6201   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6202 }
6203
6204 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6205   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6206   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6207          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6208           Op.getNumOperands() == 4)));
6209
6210   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6211   // from two other 128-bit ones.
6212
6213   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6214   return LowerAVXCONCAT_VECTORS(Op, DAG);
6215 }
6216
6217 // Try to lower a shuffle node into a simple blend instruction.
6218 static SDValue
6219 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6220                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6221   SDValue V1 = SVOp->getOperand(0);
6222   SDValue V2 = SVOp->getOperand(1);
6223   SDLoc dl(SVOp);
6224   MVT VT = SVOp->getSimpleValueType(0);
6225   MVT EltVT = VT.getVectorElementType();
6226   unsigned NumElems = VT.getVectorNumElements();
6227
6228   // There is no blend with immediate in AVX-512.
6229   if (VT.is512BitVector())
6230     return SDValue();
6231
6232   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6233     return SDValue();
6234   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6235     return SDValue();
6236
6237   // Check the mask for BLEND and build the value.
6238   unsigned MaskValue = 0;
6239   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6240   unsigned NumLanes = (NumElems-1)/8 + 1;
6241   unsigned NumElemsInLane = NumElems / NumLanes;
6242
6243   // Blend for v16i16 should be symetric for the both lanes.
6244   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6245
6246     int SndLaneEltIdx = (NumLanes == 2) ?
6247       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6248     int EltIdx = SVOp->getMaskElt(i);
6249
6250     if ((EltIdx < 0 || EltIdx == (int)i) &&
6251         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6252       continue;
6253
6254     if (((unsigned)EltIdx == (i + NumElems)) &&
6255         (SndLaneEltIdx < 0 ||
6256          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6257       MaskValue |= (1<<i);
6258     else
6259       return SDValue();
6260   }
6261
6262   // Convert i32 vectors to floating point if it is not AVX2.
6263   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6264   MVT BlendVT = VT;
6265   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6266     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6267                                NumElems);
6268     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6269     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6270   }
6271
6272   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6273                             DAG.getConstant(MaskValue, MVT::i32));
6274   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6275 }
6276
6277 // v8i16 shuffles - Prefer shuffles in the following order:
6278 // 1. [all]   pshuflw, pshufhw, optional move
6279 // 2. [ssse3] 1 x pshufb
6280 // 3. [ssse3] 2 x pshufb + 1 x por
6281 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6282 static SDValue
6283 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6284                          SelectionDAG &DAG) {
6285   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6286   SDValue V1 = SVOp->getOperand(0);
6287   SDValue V2 = SVOp->getOperand(1);
6288   SDLoc dl(SVOp);
6289   SmallVector<int, 8> MaskVals;
6290
6291   // Determine if more than 1 of the words in each of the low and high quadwords
6292   // of the result come from the same quadword of one of the two inputs.  Undef
6293   // mask values count as coming from any quadword, for better codegen.
6294   unsigned LoQuad[] = { 0, 0, 0, 0 };
6295   unsigned HiQuad[] = { 0, 0, 0, 0 };
6296   std::bitset<4> InputQuads;
6297   for (unsigned i = 0; i < 8; ++i) {
6298     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6299     int EltIdx = SVOp->getMaskElt(i);
6300     MaskVals.push_back(EltIdx);
6301     if (EltIdx < 0) {
6302       ++Quad[0];
6303       ++Quad[1];
6304       ++Quad[2];
6305       ++Quad[3];
6306       continue;
6307     }
6308     ++Quad[EltIdx / 4];
6309     InputQuads.set(EltIdx / 4);
6310   }
6311
6312   int BestLoQuad = -1;
6313   unsigned MaxQuad = 1;
6314   for (unsigned i = 0; i < 4; ++i) {
6315     if (LoQuad[i] > MaxQuad) {
6316       BestLoQuad = i;
6317       MaxQuad = LoQuad[i];
6318     }
6319   }
6320
6321   int BestHiQuad = -1;
6322   MaxQuad = 1;
6323   for (unsigned i = 0; i < 4; ++i) {
6324     if (HiQuad[i] > MaxQuad) {
6325       BestHiQuad = i;
6326       MaxQuad = HiQuad[i];
6327     }
6328   }
6329
6330   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6331   // of the two input vectors, shuffle them into one input vector so only a
6332   // single pshufb instruction is necessary. If There are more than 2 input
6333   // quads, disable the next transformation since it does not help SSSE3.
6334   bool V1Used = InputQuads[0] || InputQuads[1];
6335   bool V2Used = InputQuads[2] || InputQuads[3];
6336   if (Subtarget->hasSSSE3()) {
6337     if (InputQuads.count() == 2 && V1Used && V2Used) {
6338       BestLoQuad = InputQuads[0] ? 0 : 1;
6339       BestHiQuad = InputQuads[2] ? 2 : 3;
6340     }
6341     if (InputQuads.count() > 2) {
6342       BestLoQuad = -1;
6343       BestHiQuad = -1;
6344     }
6345   }
6346
6347   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6348   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6349   // words from all 4 input quadwords.
6350   SDValue NewV;
6351   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6352     int MaskV[] = {
6353       BestLoQuad < 0 ? 0 : BestLoQuad,
6354       BestHiQuad < 0 ? 1 : BestHiQuad
6355     };
6356     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6357                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6358                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6359     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6360
6361     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6362     // source words for the shuffle, to aid later transformations.
6363     bool AllWordsInNewV = true;
6364     bool InOrder[2] = { true, true };
6365     for (unsigned i = 0; i != 8; ++i) {
6366       int idx = MaskVals[i];
6367       if (idx != (int)i)
6368         InOrder[i/4] = false;
6369       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6370         continue;
6371       AllWordsInNewV = false;
6372       break;
6373     }
6374
6375     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6376     if (AllWordsInNewV) {
6377       for (int i = 0; i != 8; ++i) {
6378         int idx = MaskVals[i];
6379         if (idx < 0)
6380           continue;
6381         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6382         if ((idx != i) && idx < 4)
6383           pshufhw = false;
6384         if ((idx != i) && idx > 3)
6385           pshuflw = false;
6386       }
6387       V1 = NewV;
6388       V2Used = false;
6389       BestLoQuad = 0;
6390       BestHiQuad = 1;
6391     }
6392
6393     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6394     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6395     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6396       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6397       unsigned TargetMask = 0;
6398       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6399                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6400       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6401       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6402                              getShufflePSHUFLWImmediate(SVOp);
6403       V1 = NewV.getOperand(0);
6404       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6405     }
6406   }
6407
6408   // Promote splats to a larger type which usually leads to more efficient code.
6409   // FIXME: Is this true if pshufb is available?
6410   if (SVOp->isSplat())
6411     return PromoteSplat(SVOp, DAG);
6412
6413   // If we have SSSE3, and all words of the result are from 1 input vector,
6414   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6415   // is present, fall back to case 4.
6416   if (Subtarget->hasSSSE3()) {
6417     SmallVector<SDValue,16> pshufbMask;
6418
6419     // If we have elements from both input vectors, set the high bit of the
6420     // shuffle mask element to zero out elements that come from V2 in the V1
6421     // mask, and elements that come from V1 in the V2 mask, so that the two
6422     // results can be OR'd together.
6423     bool TwoInputs = V1Used && V2Used;
6424     for (unsigned i = 0; i != 8; ++i) {
6425       int EltIdx = MaskVals[i] * 2;
6426       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6427       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6428       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6429       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6430     }
6431     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6432     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6433                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6434                                  MVT::v16i8, &pshufbMask[0], 16));
6435     if (!TwoInputs)
6436       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6437
6438     // Calculate the shuffle mask for the second input, shuffle it, and
6439     // OR it with the first shuffled input.
6440     pshufbMask.clear();
6441     for (unsigned i = 0; i != 8; ++i) {
6442       int EltIdx = MaskVals[i] * 2;
6443       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6444       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6445       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6446       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6447     }
6448     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6449     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6450                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6451                                  MVT::v16i8, &pshufbMask[0], 16));
6452     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6453     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6454   }
6455
6456   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6457   // and update MaskVals with new element order.
6458   std::bitset<8> InOrder;
6459   if (BestLoQuad >= 0) {
6460     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6461     for (int i = 0; i != 4; ++i) {
6462       int idx = MaskVals[i];
6463       if (idx < 0) {
6464         InOrder.set(i);
6465       } else if ((idx / 4) == BestLoQuad) {
6466         MaskV[i] = idx & 3;
6467         InOrder.set(i);
6468       }
6469     }
6470     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6471                                 &MaskV[0]);
6472
6473     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6474       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6475       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6476                                   NewV.getOperand(0),
6477                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6478     }
6479   }
6480
6481   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6482   // and update MaskVals with the new element order.
6483   if (BestHiQuad >= 0) {
6484     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6485     for (unsigned i = 4; i != 8; ++i) {
6486       int idx = MaskVals[i];
6487       if (idx < 0) {
6488         InOrder.set(i);
6489       } else if ((idx / 4) == BestHiQuad) {
6490         MaskV[i] = (idx & 3) + 4;
6491         InOrder.set(i);
6492       }
6493     }
6494     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6495                                 &MaskV[0]);
6496
6497     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6498       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6499       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6500                                   NewV.getOperand(0),
6501                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6502     }
6503   }
6504
6505   // In case BestHi & BestLo were both -1, which means each quadword has a word
6506   // from each of the four input quadwords, calculate the InOrder bitvector now
6507   // before falling through to the insert/extract cleanup.
6508   if (BestLoQuad == -1 && BestHiQuad == -1) {
6509     NewV = V1;
6510     for (int i = 0; i != 8; ++i)
6511       if (MaskVals[i] < 0 || MaskVals[i] == i)
6512         InOrder.set(i);
6513   }
6514
6515   // The other elements are put in the right place using pextrw and pinsrw.
6516   for (unsigned i = 0; i != 8; ++i) {
6517     if (InOrder[i])
6518       continue;
6519     int EltIdx = MaskVals[i];
6520     if (EltIdx < 0)
6521       continue;
6522     SDValue ExtOp = (EltIdx < 8) ?
6523       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6524                   DAG.getIntPtrConstant(EltIdx)) :
6525       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6526                   DAG.getIntPtrConstant(EltIdx - 8));
6527     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6528                        DAG.getIntPtrConstant(i));
6529   }
6530   return NewV;
6531 }
6532
6533 // v16i8 shuffles - Prefer shuffles in the following order:
6534 // 1. [ssse3] 1 x pshufb
6535 // 2. [ssse3] 2 x pshufb + 1 x por
6536 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6537 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6538                                         const X86Subtarget* Subtarget,
6539                                         SelectionDAG &DAG) {
6540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6541   SDValue V1 = SVOp->getOperand(0);
6542   SDValue V2 = SVOp->getOperand(1);
6543   SDLoc dl(SVOp);
6544   ArrayRef<int> MaskVals = SVOp->getMask();
6545
6546   // Promote splats to a larger type which usually leads to more efficient code.
6547   // FIXME: Is this true if pshufb is available?
6548   if (SVOp->isSplat())
6549     return PromoteSplat(SVOp, DAG);
6550
6551   // If we have SSSE3, case 1 is generated when all result bytes come from
6552   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6553   // present, fall back to case 3.
6554
6555   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6556   if (Subtarget->hasSSSE3()) {
6557     SmallVector<SDValue,16> pshufbMask;
6558
6559     // If all result elements are from one input vector, then only translate
6560     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6561     //
6562     // Otherwise, we have elements from both input vectors, and must zero out
6563     // elements that come from V2 in the first mask, and V1 in the second mask
6564     // so that we can OR them together.
6565     for (unsigned i = 0; i != 16; ++i) {
6566       int EltIdx = MaskVals[i];
6567       if (EltIdx < 0 || EltIdx >= 16)
6568         EltIdx = 0x80;
6569       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6570     }
6571     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6572                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6573                                  MVT::v16i8, &pshufbMask[0], 16));
6574
6575     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6576     // the 2nd operand if it's undefined or zero.
6577     if (V2.getOpcode() == ISD::UNDEF ||
6578         ISD::isBuildVectorAllZeros(V2.getNode()))
6579       return V1;
6580
6581     // Calculate the shuffle mask for the second input, shuffle it, and
6582     // OR it with the first shuffled input.
6583     pshufbMask.clear();
6584     for (unsigned i = 0; i != 16; ++i) {
6585       int EltIdx = MaskVals[i];
6586       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6587       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6588     }
6589     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6590                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6591                                  MVT::v16i8, &pshufbMask[0], 16));
6592     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6593   }
6594
6595   // No SSSE3 - Calculate in place words and then fix all out of place words
6596   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6597   // the 16 different words that comprise the two doublequadword input vectors.
6598   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6599   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6600   SDValue NewV = V1;
6601   for (int i = 0; i != 8; ++i) {
6602     int Elt0 = MaskVals[i*2];
6603     int Elt1 = MaskVals[i*2+1];
6604
6605     // This word of the result is all undef, skip it.
6606     if (Elt0 < 0 && Elt1 < 0)
6607       continue;
6608
6609     // This word of the result is already in the correct place, skip it.
6610     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6611       continue;
6612
6613     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6614     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6615     SDValue InsElt;
6616
6617     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6618     // using a single extract together, load it and store it.
6619     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6620       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6621                            DAG.getIntPtrConstant(Elt1 / 2));
6622       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6623                         DAG.getIntPtrConstant(i));
6624       continue;
6625     }
6626
6627     // If Elt1 is defined, extract it from the appropriate source.  If the
6628     // source byte is not also odd, shift the extracted word left 8 bits
6629     // otherwise clear the bottom 8 bits if we need to do an or.
6630     if (Elt1 >= 0) {
6631       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6632                            DAG.getIntPtrConstant(Elt1 / 2));
6633       if ((Elt1 & 1) == 0)
6634         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6635                              DAG.getConstant(8,
6636                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6637       else if (Elt0 >= 0)
6638         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6639                              DAG.getConstant(0xFF00, MVT::i16));
6640     }
6641     // If Elt0 is defined, extract it from the appropriate source.  If the
6642     // source byte is not also even, shift the extracted word right 8 bits. If
6643     // Elt1 was also defined, OR the extracted values together before
6644     // inserting them in the result.
6645     if (Elt0 >= 0) {
6646       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6647                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6648       if ((Elt0 & 1) != 0)
6649         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6650                               DAG.getConstant(8,
6651                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6652       else if (Elt1 >= 0)
6653         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6654                              DAG.getConstant(0x00FF, MVT::i16));
6655       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6656                          : InsElt0;
6657     }
6658     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6659                        DAG.getIntPtrConstant(i));
6660   }
6661   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6662 }
6663
6664 // v32i8 shuffles - Translate to VPSHUFB if possible.
6665 static
6666 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6667                                  const X86Subtarget *Subtarget,
6668                                  SelectionDAG &DAG) {
6669   MVT VT = SVOp->getSimpleValueType(0);
6670   SDValue V1 = SVOp->getOperand(0);
6671   SDValue V2 = SVOp->getOperand(1);
6672   SDLoc dl(SVOp);
6673   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6674
6675   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6676   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6677   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6678
6679   // VPSHUFB may be generated if
6680   // (1) one of input vector is undefined or zeroinitializer.
6681   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6682   // And (2) the mask indexes don't cross the 128-bit lane.
6683   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6684       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6685     return SDValue();
6686
6687   if (V1IsAllZero && !V2IsAllZero) {
6688     CommuteVectorShuffleMask(MaskVals, 32);
6689     V1 = V2;
6690   }
6691   SmallVector<SDValue, 32> pshufbMask;
6692   for (unsigned i = 0; i != 32; i++) {
6693     int EltIdx = MaskVals[i];
6694     if (EltIdx < 0 || EltIdx >= 32)
6695       EltIdx = 0x80;
6696     else {
6697       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6698         // Cross lane is not allowed.
6699         return SDValue();
6700       EltIdx &= 0xf;
6701     }
6702     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6703   }
6704   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6705                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6706                                   MVT::v32i8, &pshufbMask[0], 32));
6707 }
6708
6709 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6710 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6711 /// done when every pair / quad of shuffle mask elements point to elements in
6712 /// the right sequence. e.g.
6713 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6714 static
6715 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6716                                  SelectionDAG &DAG) {
6717   MVT VT = SVOp->getSimpleValueType(0);
6718   SDLoc dl(SVOp);
6719   unsigned NumElems = VT.getVectorNumElements();
6720   MVT NewVT;
6721   unsigned Scale;
6722   switch (VT.SimpleTy) {
6723   default: llvm_unreachable("Unexpected!");
6724   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6725   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6726   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6727   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6728   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6729   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6730   }
6731
6732   SmallVector<int, 8> MaskVec;
6733   for (unsigned i = 0; i != NumElems; i += Scale) {
6734     int StartIdx = -1;
6735     for (unsigned j = 0; j != Scale; ++j) {
6736       int EltIdx = SVOp->getMaskElt(i+j);
6737       if (EltIdx < 0)
6738         continue;
6739       if (StartIdx < 0)
6740         StartIdx = (EltIdx / Scale);
6741       if (EltIdx != (int)(StartIdx*Scale + j))
6742         return SDValue();
6743     }
6744     MaskVec.push_back(StartIdx);
6745   }
6746
6747   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6748   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6749   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6750 }
6751
6752 /// getVZextMovL - Return a zero-extending vector move low node.
6753 ///
6754 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6755                             SDValue SrcOp, SelectionDAG &DAG,
6756                             const X86Subtarget *Subtarget, SDLoc dl) {
6757   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6758     LoadSDNode *LD = NULL;
6759     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6760       LD = dyn_cast<LoadSDNode>(SrcOp);
6761     if (!LD) {
6762       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6763       // instead.
6764       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6765       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6766           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6767           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6768           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6769         // PR2108
6770         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6771         return DAG.getNode(ISD::BITCAST, dl, VT,
6772                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6773                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6774                                                    OpVT,
6775                                                    SrcOp.getOperand(0)
6776                                                           .getOperand(0))));
6777       }
6778     }
6779   }
6780
6781   return DAG.getNode(ISD::BITCAST, dl, VT,
6782                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6783                                  DAG.getNode(ISD::BITCAST, dl,
6784                                              OpVT, SrcOp)));
6785 }
6786
6787 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6788 /// which could not be matched by any known target speficic shuffle
6789 static SDValue
6790 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6791
6792   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6793   if (NewOp.getNode())
6794     return NewOp;
6795
6796   MVT VT = SVOp->getSimpleValueType(0);
6797
6798   unsigned NumElems = VT.getVectorNumElements();
6799   unsigned NumLaneElems = NumElems / 2;
6800
6801   SDLoc dl(SVOp);
6802   MVT EltVT = VT.getVectorElementType();
6803   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6804   SDValue Output[2];
6805
6806   SmallVector<int, 16> Mask;
6807   for (unsigned l = 0; l < 2; ++l) {
6808     // Build a shuffle mask for the output, discovering on the fly which
6809     // input vectors to use as shuffle operands (recorded in InputUsed).
6810     // If building a suitable shuffle vector proves too hard, then bail
6811     // out with UseBuildVector set.
6812     bool UseBuildVector = false;
6813     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6814     unsigned LaneStart = l * NumLaneElems;
6815     for (unsigned i = 0; i != NumLaneElems; ++i) {
6816       // The mask element.  This indexes into the input.
6817       int Idx = SVOp->getMaskElt(i+LaneStart);
6818       if (Idx < 0) {
6819         // the mask element does not index into any input vector.
6820         Mask.push_back(-1);
6821         continue;
6822       }
6823
6824       // The input vector this mask element indexes into.
6825       int Input = Idx / NumLaneElems;
6826
6827       // Turn the index into an offset from the start of the input vector.
6828       Idx -= Input * NumLaneElems;
6829
6830       // Find or create a shuffle vector operand to hold this input.
6831       unsigned OpNo;
6832       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6833         if (InputUsed[OpNo] == Input)
6834           // This input vector is already an operand.
6835           break;
6836         if (InputUsed[OpNo] < 0) {
6837           // Create a new operand for this input vector.
6838           InputUsed[OpNo] = Input;
6839           break;
6840         }
6841       }
6842
6843       if (OpNo >= array_lengthof(InputUsed)) {
6844         // More than two input vectors used!  Give up on trying to create a
6845         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6846         UseBuildVector = true;
6847         break;
6848       }
6849
6850       // Add the mask index for the new shuffle vector.
6851       Mask.push_back(Idx + OpNo * NumLaneElems);
6852     }
6853
6854     if (UseBuildVector) {
6855       SmallVector<SDValue, 16> SVOps;
6856       for (unsigned i = 0; i != NumLaneElems; ++i) {
6857         // The mask element.  This indexes into the input.
6858         int Idx = SVOp->getMaskElt(i+LaneStart);
6859         if (Idx < 0) {
6860           SVOps.push_back(DAG.getUNDEF(EltVT));
6861           continue;
6862         }
6863
6864         // The input vector this mask element indexes into.
6865         int Input = Idx / NumElems;
6866
6867         // Turn the index into an offset from the start of the input vector.
6868         Idx -= Input * NumElems;
6869
6870         // Extract the vector element by hand.
6871         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6872                                     SVOp->getOperand(Input),
6873                                     DAG.getIntPtrConstant(Idx)));
6874       }
6875
6876       // Construct the output using a BUILD_VECTOR.
6877       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6878                               SVOps.size());
6879     } else if (InputUsed[0] < 0) {
6880       // No input vectors were used! The result is undefined.
6881       Output[l] = DAG.getUNDEF(NVT);
6882     } else {
6883       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6884                                         (InputUsed[0] % 2) * NumLaneElems,
6885                                         DAG, dl);
6886       // If only one input was used, use an undefined vector for the other.
6887       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6888         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6889                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6890       // At least one input vector was used. Create a new shuffle vector.
6891       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6892     }
6893
6894     Mask.clear();
6895   }
6896
6897   // Concatenate the result back
6898   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6899 }
6900
6901 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6902 /// 4 elements, and match them with several different shuffle types.
6903 static SDValue
6904 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6905   SDValue V1 = SVOp->getOperand(0);
6906   SDValue V2 = SVOp->getOperand(1);
6907   SDLoc dl(SVOp);
6908   MVT VT = SVOp->getSimpleValueType(0);
6909
6910   assert(VT.is128BitVector() && "Unsupported vector size");
6911
6912   std::pair<int, int> Locs[4];
6913   int Mask1[] = { -1, -1, -1, -1 };
6914   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6915
6916   unsigned NumHi = 0;
6917   unsigned NumLo = 0;
6918   for (unsigned i = 0; i != 4; ++i) {
6919     int Idx = PermMask[i];
6920     if (Idx < 0) {
6921       Locs[i] = std::make_pair(-1, -1);
6922     } else {
6923       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6924       if (Idx < 4) {
6925         Locs[i] = std::make_pair(0, NumLo);
6926         Mask1[NumLo] = Idx;
6927         NumLo++;
6928       } else {
6929         Locs[i] = std::make_pair(1, NumHi);
6930         if (2+NumHi < 4)
6931           Mask1[2+NumHi] = Idx;
6932         NumHi++;
6933       }
6934     }
6935   }
6936
6937   if (NumLo <= 2 && NumHi <= 2) {
6938     // If no more than two elements come from either vector. This can be
6939     // implemented with two shuffles. First shuffle gather the elements.
6940     // The second shuffle, which takes the first shuffle as both of its
6941     // vector operands, put the elements into the right order.
6942     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6943
6944     int Mask2[] = { -1, -1, -1, -1 };
6945
6946     for (unsigned i = 0; i != 4; ++i)
6947       if (Locs[i].first != -1) {
6948         unsigned Idx = (i < 2) ? 0 : 4;
6949         Idx += Locs[i].first * 2 + Locs[i].second;
6950         Mask2[i] = Idx;
6951       }
6952
6953     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6954   }
6955
6956   if (NumLo == 3 || NumHi == 3) {
6957     // Otherwise, we must have three elements from one vector, call it X, and
6958     // one element from the other, call it Y.  First, use a shufps to build an
6959     // intermediate vector with the one element from Y and the element from X
6960     // that will be in the same half in the final destination (the indexes don't
6961     // matter). Then, use a shufps to build the final vector, taking the half
6962     // containing the element from Y from the intermediate, and the other half
6963     // from X.
6964     if (NumHi == 3) {
6965       // Normalize it so the 3 elements come from V1.
6966       CommuteVectorShuffleMask(PermMask, 4);
6967       std::swap(V1, V2);
6968     }
6969
6970     // Find the element from V2.
6971     unsigned HiIndex;
6972     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6973       int Val = PermMask[HiIndex];
6974       if (Val < 0)
6975         continue;
6976       if (Val >= 4)
6977         break;
6978     }
6979
6980     Mask1[0] = PermMask[HiIndex];
6981     Mask1[1] = -1;
6982     Mask1[2] = PermMask[HiIndex^1];
6983     Mask1[3] = -1;
6984     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6985
6986     if (HiIndex >= 2) {
6987       Mask1[0] = PermMask[0];
6988       Mask1[1] = PermMask[1];
6989       Mask1[2] = HiIndex & 1 ? 6 : 4;
6990       Mask1[3] = HiIndex & 1 ? 4 : 6;
6991       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6992     }
6993
6994     Mask1[0] = HiIndex & 1 ? 2 : 0;
6995     Mask1[1] = HiIndex & 1 ? 0 : 2;
6996     Mask1[2] = PermMask[2];
6997     Mask1[3] = PermMask[3];
6998     if (Mask1[2] >= 0)
6999       Mask1[2] += 4;
7000     if (Mask1[3] >= 0)
7001       Mask1[3] += 4;
7002     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7003   }
7004
7005   // Break it into (shuffle shuffle_hi, shuffle_lo).
7006   int LoMask[] = { -1, -1, -1, -1 };
7007   int HiMask[] = { -1, -1, -1, -1 };
7008
7009   int *MaskPtr = LoMask;
7010   unsigned MaskIdx = 0;
7011   unsigned LoIdx = 0;
7012   unsigned HiIdx = 2;
7013   for (unsigned i = 0; i != 4; ++i) {
7014     if (i == 2) {
7015       MaskPtr = HiMask;
7016       MaskIdx = 1;
7017       LoIdx = 0;
7018       HiIdx = 2;
7019     }
7020     int Idx = PermMask[i];
7021     if (Idx < 0) {
7022       Locs[i] = std::make_pair(-1, -1);
7023     } else if (Idx < 4) {
7024       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7025       MaskPtr[LoIdx] = Idx;
7026       LoIdx++;
7027     } else {
7028       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7029       MaskPtr[HiIdx] = Idx;
7030       HiIdx++;
7031     }
7032   }
7033
7034   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7035   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7036   int MaskOps[] = { -1, -1, -1, -1 };
7037   for (unsigned i = 0; i != 4; ++i)
7038     if (Locs[i].first != -1)
7039       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7040   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7041 }
7042
7043 static bool MayFoldVectorLoad(SDValue V) {
7044   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7045     V = V.getOperand(0);
7046
7047   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7048     V = V.getOperand(0);
7049   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7050       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7051     // BUILD_VECTOR (load), undef
7052     V = V.getOperand(0);
7053
7054   return MayFoldLoad(V);
7055 }
7056
7057 static
7058 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7059   MVT VT = Op.getSimpleValueType();
7060
7061   // Canonizalize to v2f64.
7062   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7063   return DAG.getNode(ISD::BITCAST, dl, VT,
7064                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7065                                           V1, DAG));
7066 }
7067
7068 static
7069 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7070                         bool HasSSE2) {
7071   SDValue V1 = Op.getOperand(0);
7072   SDValue V2 = Op.getOperand(1);
7073   MVT VT = Op.getSimpleValueType();
7074
7075   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7076
7077   if (HasSSE2 && VT == MVT::v2f64)
7078     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7079
7080   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7081   return DAG.getNode(ISD::BITCAST, dl, VT,
7082                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7083                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7084                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7085 }
7086
7087 static
7088 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7089   SDValue V1 = Op.getOperand(0);
7090   SDValue V2 = Op.getOperand(1);
7091   MVT VT = Op.getSimpleValueType();
7092
7093   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7094          "unsupported shuffle type");
7095
7096   if (V2.getOpcode() == ISD::UNDEF)
7097     V2 = V1;
7098
7099   // v4i32 or v4f32
7100   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7101 }
7102
7103 static
7104 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7105   SDValue V1 = Op.getOperand(0);
7106   SDValue V2 = Op.getOperand(1);
7107   MVT VT = Op.getSimpleValueType();
7108   unsigned NumElems = VT.getVectorNumElements();
7109
7110   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7111   // operand of these instructions is only memory, so check if there's a
7112   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7113   // same masks.
7114   bool CanFoldLoad = false;
7115
7116   // Trivial case, when V2 comes from a load.
7117   if (MayFoldVectorLoad(V2))
7118     CanFoldLoad = true;
7119
7120   // When V1 is a load, it can be folded later into a store in isel, example:
7121   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7122   //    turns into:
7123   //  (MOVLPSmr addr:$src1, VR128:$src2)
7124   // So, recognize this potential and also use MOVLPS or MOVLPD
7125   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7126     CanFoldLoad = true;
7127
7128   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7129   if (CanFoldLoad) {
7130     if (HasSSE2 && NumElems == 2)
7131       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7132
7133     if (NumElems == 4)
7134       // If we don't care about the second element, proceed to use movss.
7135       if (SVOp->getMaskElt(1) != -1)
7136         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7137   }
7138
7139   // movl and movlp will both match v2i64, but v2i64 is never matched by
7140   // movl earlier because we make it strict to avoid messing with the movlp load
7141   // folding logic (see the code above getMOVLP call). Match it here then,
7142   // this is horrible, but will stay like this until we move all shuffle
7143   // matching to x86 specific nodes. Note that for the 1st condition all
7144   // types are matched with movsd.
7145   if (HasSSE2) {
7146     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7147     // as to remove this logic from here, as much as possible
7148     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7149       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7150     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7151   }
7152
7153   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7154
7155   // Invert the operand order and use SHUFPS to match it.
7156   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7157                               getShuffleSHUFImmediate(SVOp), DAG);
7158 }
7159
7160 // Reduce a vector shuffle to zext.
7161 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7162                                     SelectionDAG &DAG) {
7163   // PMOVZX is only available from SSE41.
7164   if (!Subtarget->hasSSE41())
7165     return SDValue();
7166
7167   MVT VT = Op.getSimpleValueType();
7168
7169   // Only AVX2 support 256-bit vector integer extending.
7170   if (!Subtarget->hasInt256() && VT.is256BitVector())
7171     return SDValue();
7172
7173   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7174   SDLoc DL(Op);
7175   SDValue V1 = Op.getOperand(0);
7176   SDValue V2 = Op.getOperand(1);
7177   unsigned NumElems = VT.getVectorNumElements();
7178
7179   // Extending is an unary operation and the element type of the source vector
7180   // won't be equal to or larger than i64.
7181   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7182       VT.getVectorElementType() == MVT::i64)
7183     return SDValue();
7184
7185   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7186   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7187   while ((1U << Shift) < NumElems) {
7188     if (SVOp->getMaskElt(1U << Shift) == 1)
7189       break;
7190     Shift += 1;
7191     // The maximal ratio is 8, i.e. from i8 to i64.
7192     if (Shift > 3)
7193       return SDValue();
7194   }
7195
7196   // Check the shuffle mask.
7197   unsigned Mask = (1U << Shift) - 1;
7198   for (unsigned i = 0; i != NumElems; ++i) {
7199     int EltIdx = SVOp->getMaskElt(i);
7200     if ((i & Mask) != 0 && EltIdx != -1)
7201       return SDValue();
7202     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7203       return SDValue();
7204   }
7205
7206   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7207   MVT NeVT = MVT::getIntegerVT(NBits);
7208   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7209
7210   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7211     return SDValue();
7212
7213   // Simplify the operand as it's prepared to be fed into shuffle.
7214   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7215   if (V1.getOpcode() == ISD::BITCAST &&
7216       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7217       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7218       V1.getOperand(0).getOperand(0)
7219         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7220     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7221     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7222     ConstantSDNode *CIdx =
7223       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7224     // If it's foldable, i.e. normal load with single use, we will let code
7225     // selection to fold it. Otherwise, we will short the conversion sequence.
7226     if (CIdx && CIdx->getZExtValue() == 0 &&
7227         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7228       MVT FullVT = V.getSimpleValueType();
7229       MVT V1VT = V1.getSimpleValueType();
7230       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7231         // The "ext_vec_elt" node is wider than the result node.
7232         // In this case we should extract subvector from V.
7233         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7234         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7235         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7236                                         FullVT.getVectorNumElements()/Ratio);
7237         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7238                         DAG.getIntPtrConstant(0));
7239       }
7240       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7241     }
7242   }
7243
7244   return DAG.getNode(ISD::BITCAST, DL, VT,
7245                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7246 }
7247
7248 static SDValue
7249 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7250                        SelectionDAG &DAG) {
7251   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7252   MVT VT = Op.getSimpleValueType();
7253   SDLoc dl(Op);
7254   SDValue V1 = Op.getOperand(0);
7255   SDValue V2 = Op.getOperand(1);
7256
7257   if (isZeroShuffle(SVOp))
7258     return getZeroVector(VT, Subtarget, DAG, dl);
7259
7260   // Handle splat operations
7261   if (SVOp->isSplat()) {
7262     // Use vbroadcast whenever the splat comes from a foldable load
7263     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7264     if (Broadcast.getNode())
7265       return Broadcast;
7266   }
7267
7268   // Check integer expanding shuffles.
7269   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7270   if (NewOp.getNode())
7271     return NewOp;
7272
7273   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7274   // do it!
7275   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7276       VT == MVT::v16i16 || VT == MVT::v32i8) {
7277     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7278     if (NewOp.getNode())
7279       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7280   } else if ((VT == MVT::v4i32 ||
7281              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7282     // FIXME: Figure out a cleaner way to do this.
7283     // Try to make use of movq to zero out the top part.
7284     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7285       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7286       if (NewOp.getNode()) {
7287         MVT NewVT = NewOp.getSimpleValueType();
7288         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7289                                NewVT, true, false))
7290           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7291                               DAG, Subtarget, dl);
7292       }
7293     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7294       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7295       if (NewOp.getNode()) {
7296         MVT NewVT = NewOp.getSimpleValueType();
7297         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7298           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7299                               DAG, Subtarget, dl);
7300       }
7301     }
7302   }
7303   return SDValue();
7304 }
7305
7306 SDValue
7307 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7308   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7309   SDValue V1 = Op.getOperand(0);
7310   SDValue V2 = Op.getOperand(1);
7311   MVT VT = Op.getSimpleValueType();
7312   SDLoc dl(Op);
7313   unsigned NumElems = VT.getVectorNumElements();
7314   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7315   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7316   bool V1IsSplat = false;
7317   bool V2IsSplat = false;
7318   bool HasSSE2 = Subtarget->hasSSE2();
7319   bool HasFp256    = Subtarget->hasFp256();
7320   bool HasInt256   = Subtarget->hasInt256();
7321   MachineFunction &MF = DAG.getMachineFunction();
7322   bool OptForSize = MF.getFunction()->getAttributes().
7323     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7324
7325   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7326
7327   if (V1IsUndef && V2IsUndef)
7328     return DAG.getUNDEF(VT);
7329
7330   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7331
7332   // Vector shuffle lowering takes 3 steps:
7333   //
7334   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7335   //    narrowing and commutation of operands should be handled.
7336   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7337   //    shuffle nodes.
7338   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7339   //    so the shuffle can be broken into other shuffles and the legalizer can
7340   //    try the lowering again.
7341   //
7342   // The general idea is that no vector_shuffle operation should be left to
7343   // be matched during isel, all of them must be converted to a target specific
7344   // node here.
7345
7346   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7347   // narrowing and commutation of operands should be handled. The actual code
7348   // doesn't include all of those, work in progress...
7349   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7350   if (NewOp.getNode())
7351     return NewOp;
7352
7353   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7354
7355   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7356   // unpckh_undef). Only use pshufd if speed is more important than size.
7357   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7358     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7359   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7360     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7361
7362   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7363       V2IsUndef && MayFoldVectorLoad(V1))
7364     return getMOVDDup(Op, dl, V1, DAG);
7365
7366   if (isMOVHLPS_v_undef_Mask(M, VT))
7367     return getMOVHighToLow(Op, dl, DAG);
7368
7369   // Use to match splats
7370   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7371       (VT == MVT::v2f64 || VT == MVT::v2i64))
7372     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7373
7374   if (isPSHUFDMask(M, VT)) {
7375     // The actual implementation will match the mask in the if above and then
7376     // during isel it can match several different instructions, not only pshufd
7377     // as its name says, sad but true, emulate the behavior for now...
7378     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7379       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7380
7381     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7382
7383     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7384       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7385
7386     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7387       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7388                                   DAG);
7389
7390     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7391                                 TargetMask, DAG);
7392   }
7393
7394   if (isPALIGNRMask(M, VT, Subtarget))
7395     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7396                                 getShufflePALIGNRImmediate(SVOp),
7397                                 DAG);
7398
7399   // Check if this can be converted into a logical shift.
7400   bool isLeft = false;
7401   unsigned ShAmt = 0;
7402   SDValue ShVal;
7403   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7404   if (isShift && ShVal.hasOneUse()) {
7405     // If the shifted value has multiple uses, it may be cheaper to use
7406     // v_set0 + movlhps or movhlps, etc.
7407     MVT EltVT = VT.getVectorElementType();
7408     ShAmt *= EltVT.getSizeInBits();
7409     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7410   }
7411
7412   if (isMOVLMask(M, VT)) {
7413     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7414       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7415     if (!isMOVLPMask(M, VT)) {
7416       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7417         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7418
7419       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7420         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7421     }
7422   }
7423
7424   // FIXME: fold these into legal mask.
7425   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7426     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7427
7428   if (isMOVHLPSMask(M, VT))
7429     return getMOVHighToLow(Op, dl, DAG);
7430
7431   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7432     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7433
7434   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7435     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7436
7437   if (isMOVLPMask(M, VT))
7438     return getMOVLP(Op, dl, DAG, HasSSE2);
7439
7440   if (ShouldXformToMOVHLPS(M, VT) ||
7441       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7442     return CommuteVectorShuffle(SVOp, DAG);
7443
7444   if (isShift) {
7445     // No better options. Use a vshldq / vsrldq.
7446     MVT EltVT = VT.getVectorElementType();
7447     ShAmt *= EltVT.getSizeInBits();
7448     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7449   }
7450
7451   bool Commuted = false;
7452   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7453   // 1,1,1,1 -> v8i16 though.
7454   V1IsSplat = isSplatVector(V1.getNode());
7455   V2IsSplat = isSplatVector(V2.getNode());
7456
7457   // Canonicalize the splat or undef, if present, to be on the RHS.
7458   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7459     CommuteVectorShuffleMask(M, NumElems);
7460     std::swap(V1, V2);
7461     std::swap(V1IsSplat, V2IsSplat);
7462     Commuted = true;
7463   }
7464
7465   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7466     // Shuffling low element of v1 into undef, just return v1.
7467     if (V2IsUndef)
7468       return V1;
7469     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7470     // the instruction selector will not match, so get a canonical MOVL with
7471     // swapped operands to undo the commute.
7472     return getMOVL(DAG, dl, VT, V2, V1);
7473   }
7474
7475   if (isUNPCKLMask(M, VT, HasInt256))
7476     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7477
7478   if (isUNPCKHMask(M, VT, HasInt256))
7479     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7480
7481   if (V2IsSplat) {
7482     // Normalize mask so all entries that point to V2 points to its first
7483     // element then try to match unpck{h|l} again. If match, return a
7484     // new vector_shuffle with the corrected mask.p
7485     SmallVector<int, 8> NewMask(M.begin(), M.end());
7486     NormalizeMask(NewMask, NumElems);
7487     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7488       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7489     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7490       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7491   }
7492
7493   if (Commuted) {
7494     // Commute is back and try unpck* again.
7495     // FIXME: this seems wrong.
7496     CommuteVectorShuffleMask(M, NumElems);
7497     std::swap(V1, V2);
7498     std::swap(V1IsSplat, V2IsSplat);
7499     Commuted = false;
7500
7501     if (isUNPCKLMask(M, VT, HasInt256))
7502       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7503
7504     if (isUNPCKHMask(M, VT, HasInt256))
7505       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7506   }
7507
7508   // Normalize the node to match x86 shuffle ops if needed
7509   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7510     return CommuteVectorShuffle(SVOp, DAG);
7511
7512   // The checks below are all present in isShuffleMaskLegal, but they are
7513   // inlined here right now to enable us to directly emit target specific
7514   // nodes, and remove one by one until they don't return Op anymore.
7515
7516   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7517       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7518     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7519       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7520   }
7521
7522   if (isPSHUFHWMask(M, VT, HasInt256))
7523     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7524                                 getShufflePSHUFHWImmediate(SVOp),
7525                                 DAG);
7526
7527   if (isPSHUFLWMask(M, VT, HasInt256))
7528     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7529                                 getShufflePSHUFLWImmediate(SVOp),
7530                                 DAG);
7531
7532   if (isSHUFPMask(M, VT))
7533     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7534                                 getShuffleSHUFImmediate(SVOp), DAG);
7535
7536   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7537     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7538   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7539     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7540
7541   //===--------------------------------------------------------------------===//
7542   // Generate target specific nodes for 128 or 256-bit shuffles only
7543   // supported in the AVX instruction set.
7544   //
7545
7546   // Handle VMOVDDUPY permutations
7547   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7548     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7549
7550   // Handle VPERMILPS/D* permutations
7551   if (isVPERMILPMask(M, VT)) {
7552     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7553       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7554                                   getShuffleSHUFImmediate(SVOp), DAG);
7555     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7556                                 getShuffleSHUFImmediate(SVOp), DAG);
7557   }
7558
7559   // Handle VPERM2F128/VPERM2I128 permutations
7560   if (isVPERM2X128Mask(M, VT, HasFp256))
7561     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7562                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7563
7564   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7565   if (BlendOp.getNode())
7566     return BlendOp;
7567
7568   unsigned Imm8;
7569   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7570     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7571
7572   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7573       VT.is512BitVector()) {
7574     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7575     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7576     SmallVector<SDValue, 16> permclMask;
7577     for (unsigned i = 0; i != NumElems; ++i) {
7578       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7579     }
7580
7581     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7582                                 &permclMask[0], NumElems);
7583     if (V2IsUndef)
7584       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7585       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7586                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7587     return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7588                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7589   }
7590
7591   //===--------------------------------------------------------------------===//
7592   // Since no target specific shuffle was selected for this generic one,
7593   // lower it into other known shuffles. FIXME: this isn't true yet, but
7594   // this is the plan.
7595   //
7596
7597   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7598   if (VT == MVT::v8i16) {
7599     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7600     if (NewOp.getNode())
7601       return NewOp;
7602   }
7603
7604   if (VT == MVT::v16i8) {
7605     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7606     if (NewOp.getNode())
7607       return NewOp;
7608   }
7609
7610   if (VT == MVT::v32i8) {
7611     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7612     if (NewOp.getNode())
7613       return NewOp;
7614   }
7615
7616   // Handle all 128-bit wide vectors with 4 elements, and match them with
7617   // several different shuffle types.
7618   if (NumElems == 4 && VT.is128BitVector())
7619     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7620
7621   // Handle general 256-bit shuffles
7622   if (VT.is256BitVector())
7623     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7624
7625   return SDValue();
7626 }
7627
7628 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7629   MVT VT = Op.getSimpleValueType();
7630   SDLoc dl(Op);
7631
7632   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7633     return SDValue();
7634
7635   if (VT.getSizeInBits() == 8) {
7636     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7637                                   Op.getOperand(0), Op.getOperand(1));
7638     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7639                                   DAG.getValueType(VT));
7640     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7641   }
7642
7643   if (VT.getSizeInBits() == 16) {
7644     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7645     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7646     if (Idx == 0)
7647       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7648                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7649                                      DAG.getNode(ISD::BITCAST, dl,
7650                                                  MVT::v4i32,
7651                                                  Op.getOperand(0)),
7652                                      Op.getOperand(1)));
7653     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7654                                   Op.getOperand(0), Op.getOperand(1));
7655     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7656                                   DAG.getValueType(VT));
7657     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7658   }
7659
7660   if (VT == MVT::f32) {
7661     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7662     // the result back to FR32 register. It's only worth matching if the
7663     // result has a single use which is a store or a bitcast to i32.  And in
7664     // the case of a store, it's not worth it if the index is a constant 0,
7665     // because a MOVSSmr can be used instead, which is smaller and faster.
7666     if (!Op.hasOneUse())
7667       return SDValue();
7668     SDNode *User = *Op.getNode()->use_begin();
7669     if ((User->getOpcode() != ISD::STORE ||
7670          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7671           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7672         (User->getOpcode() != ISD::BITCAST ||
7673          User->getValueType(0) != MVT::i32))
7674       return SDValue();
7675     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7676                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7677                                               Op.getOperand(0)),
7678                                               Op.getOperand(1));
7679     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7680   }
7681
7682   if (VT == MVT::i32 || VT == MVT::i64) {
7683     // ExtractPS/pextrq works with constant index.
7684     if (isa<ConstantSDNode>(Op.getOperand(1)))
7685       return Op;
7686   }
7687   return SDValue();
7688 }
7689
7690 /// Extract one bit from mask vector, like v16i1 or v8i1.
7691 /// AVX-512 feature.
7692 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) {
7693   SDValue Vec = Op.getOperand(0);
7694   SDLoc dl(Vec);
7695   MVT VecVT = Vec.getSimpleValueType();
7696   SDValue Idx = Op.getOperand(1);
7697   MVT EltVT = Op.getSimpleValueType();
7698
7699   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7700
7701   // variable index can't be handled in mask registers,
7702   // extend vector to VR512
7703   if (!isa<ConstantSDNode>(Idx)) {
7704     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7705     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7706     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7707                               ExtVT.getVectorElementType(), Ext, Idx);
7708     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7709   }
7710
7711   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7712   if (IdxVal) {
7713     unsigned MaxSift = VecVT.getSizeInBits() - 1;
7714     Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7715                       DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7716     Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7717                       DAG.getConstant(MaxSift, MVT::i8));
7718   }
7719   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i1, Vec,
7720                        DAG.getIntPtrConstant(0));
7721 }
7722
7723 SDValue
7724 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7725                                            SelectionDAG &DAG) const {
7726   SDLoc dl(Op);
7727   SDValue Vec = Op.getOperand(0);
7728   MVT VecVT = Vec.getSimpleValueType();
7729   SDValue Idx = Op.getOperand(1);
7730
7731   if (Op.getSimpleValueType() == MVT::i1)
7732     return ExtractBitFromMaskVector(Op, DAG);
7733
7734   if (!isa<ConstantSDNode>(Idx)) {
7735     if (VecVT.is512BitVector() ||
7736         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7737          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7738
7739       MVT MaskEltVT =
7740         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7741       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7742                                     MaskEltVT.getSizeInBits());
7743
7744       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7745       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7746                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7747                                 Idx, DAG.getConstant(0, getPointerTy()));
7748       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7749       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7750                         Perm, DAG.getConstant(0, getPointerTy()));
7751     }
7752     return SDValue();
7753   }
7754
7755   // If this is a 256-bit vector result, first extract the 128-bit vector and
7756   // then extract the element from the 128-bit vector.
7757   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7758
7759     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7760     // Get the 128-bit vector.
7761     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7762     MVT EltVT = VecVT.getVectorElementType();
7763
7764     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7765
7766     //if (IdxVal >= NumElems/2)
7767     //  IdxVal -= NumElems/2;
7768     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7769     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7770                        DAG.getConstant(IdxVal, MVT::i32));
7771   }
7772
7773   assert(VecVT.is128BitVector() && "Unexpected vector length");
7774
7775   if (Subtarget->hasSSE41()) {
7776     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7777     if (Res.getNode())
7778       return Res;
7779   }
7780
7781   MVT VT = Op.getSimpleValueType();
7782   // TODO: handle v16i8.
7783   if (VT.getSizeInBits() == 16) {
7784     SDValue Vec = Op.getOperand(0);
7785     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7786     if (Idx == 0)
7787       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7788                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7789                                      DAG.getNode(ISD::BITCAST, dl,
7790                                                  MVT::v4i32, Vec),
7791                                      Op.getOperand(1)));
7792     // Transform it so it match pextrw which produces a 32-bit result.
7793     MVT EltVT = MVT::i32;
7794     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7795                                   Op.getOperand(0), Op.getOperand(1));
7796     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7797                                   DAG.getValueType(VT));
7798     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7799   }
7800
7801   if (VT.getSizeInBits() == 32) {
7802     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7803     if (Idx == 0)
7804       return Op;
7805
7806     // SHUFPS the element to the lowest double word, then movss.
7807     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7808     MVT VVT = Op.getOperand(0).getSimpleValueType();
7809     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7810                                        DAG.getUNDEF(VVT), Mask);
7811     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7812                        DAG.getIntPtrConstant(0));
7813   }
7814
7815   if (VT.getSizeInBits() == 64) {
7816     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7817     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7818     //        to match extract_elt for f64.
7819     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7820     if (Idx == 0)
7821       return Op;
7822
7823     // UNPCKHPD the element to the lowest double word, then movsd.
7824     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7825     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7826     int Mask[2] = { 1, -1 };
7827     MVT VVT = Op.getOperand(0).getSimpleValueType();
7828     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7829                                        DAG.getUNDEF(VVT), Mask);
7830     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7831                        DAG.getIntPtrConstant(0));
7832   }
7833
7834   return SDValue();
7835 }
7836
7837 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7838   MVT VT = Op.getSimpleValueType();
7839   MVT EltVT = VT.getVectorElementType();
7840   SDLoc dl(Op);
7841
7842   SDValue N0 = Op.getOperand(0);
7843   SDValue N1 = Op.getOperand(1);
7844   SDValue N2 = Op.getOperand(2);
7845
7846   if (!VT.is128BitVector())
7847     return SDValue();
7848
7849   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7850       isa<ConstantSDNode>(N2)) {
7851     unsigned Opc;
7852     if (VT == MVT::v8i16)
7853       Opc = X86ISD::PINSRW;
7854     else if (VT == MVT::v16i8)
7855       Opc = X86ISD::PINSRB;
7856     else
7857       Opc = X86ISD::PINSRB;
7858
7859     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7860     // argument.
7861     if (N1.getValueType() != MVT::i32)
7862       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7863     if (N2.getValueType() != MVT::i32)
7864       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7865     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7866   }
7867
7868   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7869     // Bits [7:6] of the constant are the source select.  This will always be
7870     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7871     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7872     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7873     // Bits [5:4] of the constant are the destination select.  This is the
7874     //  value of the incoming immediate.
7875     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7876     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7877     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7878     // Create this as a scalar to vector..
7879     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7880     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7881   }
7882
7883   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7884     // PINSR* works with constant index.
7885     return Op;
7886   }
7887   return SDValue();
7888 }
7889
7890 SDValue
7891 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7892   MVT VT = Op.getSimpleValueType();
7893   MVT EltVT = VT.getVectorElementType();
7894
7895   SDLoc dl(Op);
7896   SDValue N0 = Op.getOperand(0);
7897   SDValue N1 = Op.getOperand(1);
7898   SDValue N2 = Op.getOperand(2);
7899
7900   // If this is a 256-bit vector result, first extract the 128-bit vector,
7901   // insert the element into the extracted half and then place it back.
7902   if (VT.is256BitVector() || VT.is512BitVector()) {
7903     if (!isa<ConstantSDNode>(N2))
7904       return SDValue();
7905
7906     // Get the desired 128-bit vector half.
7907     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7908     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7909
7910     // Insert the element into the desired half.
7911     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7912     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7913
7914     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7915                     DAG.getConstant(IdxIn128, MVT::i32));
7916
7917     // Insert the changed part back to the 256-bit vector
7918     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7919   }
7920
7921   if (Subtarget->hasSSE41())
7922     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7923
7924   if (EltVT == MVT::i8)
7925     return SDValue();
7926
7927   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7928     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7929     // as its second argument.
7930     if (N1.getValueType() != MVT::i32)
7931       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7932     if (N2.getValueType() != MVT::i32)
7933       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7934     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7935   }
7936   return SDValue();
7937 }
7938
7939 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7940   SDLoc dl(Op);
7941   MVT OpVT = Op.getSimpleValueType();
7942
7943   // If this is a 256-bit vector result, first insert into a 128-bit
7944   // vector and then insert into the 256-bit vector.
7945   if (!OpVT.is128BitVector()) {
7946     // Insert into a 128-bit vector.
7947     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7948     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7949                                  OpVT.getVectorNumElements() / SizeFactor);
7950
7951     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7952
7953     // Insert the 128-bit vector.
7954     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7955   }
7956
7957   if (OpVT == MVT::v1i64 &&
7958       Op.getOperand(0).getValueType() == MVT::i64)
7959     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7960
7961   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7962   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7963   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7964                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7965 }
7966
7967 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7968 // a simple subregister reference or explicit instructions to grab
7969 // upper bits of a vector.
7970 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7971                                       SelectionDAG &DAG) {
7972   SDLoc dl(Op);
7973   SDValue In =  Op.getOperand(0);
7974   SDValue Idx = Op.getOperand(1);
7975   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7976   MVT ResVT   = Op.getSimpleValueType();
7977   MVT InVT    = In.getSimpleValueType();
7978
7979   if (Subtarget->hasFp256()) {
7980     if (ResVT.is128BitVector() &&
7981         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7982         isa<ConstantSDNode>(Idx)) {
7983       return Extract128BitVector(In, IdxVal, DAG, dl);
7984     }
7985     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7986         isa<ConstantSDNode>(Idx)) {
7987       return Extract256BitVector(In, IdxVal, DAG, dl);
7988     }
7989   }
7990   return SDValue();
7991 }
7992
7993 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7994 // simple superregister reference or explicit instructions to insert
7995 // the upper bits of a vector.
7996 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7997                                      SelectionDAG &DAG) {
7998   if (Subtarget->hasFp256()) {
7999     SDLoc dl(Op.getNode());
8000     SDValue Vec = Op.getNode()->getOperand(0);
8001     SDValue SubVec = Op.getNode()->getOperand(1);
8002     SDValue Idx = Op.getNode()->getOperand(2);
8003
8004     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8005          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8006         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8007         isa<ConstantSDNode>(Idx)) {
8008       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8009       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8010     }
8011
8012     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8013         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8014         isa<ConstantSDNode>(Idx)) {
8015       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8016       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8017     }
8018   }
8019   return SDValue();
8020 }
8021
8022 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8023 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8024 // one of the above mentioned nodes. It has to be wrapped because otherwise
8025 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8026 // be used to form addressing mode. These wrapped nodes will be selected
8027 // into MOV32ri.
8028 SDValue
8029 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8030   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8031
8032   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8033   // global base reg.
8034   unsigned char OpFlag = 0;
8035   unsigned WrapperKind = X86ISD::Wrapper;
8036   CodeModel::Model M = getTargetMachine().getCodeModel();
8037
8038   if (Subtarget->isPICStyleRIPRel() &&
8039       (M == CodeModel::Small || M == CodeModel::Kernel))
8040     WrapperKind = X86ISD::WrapperRIP;
8041   else if (Subtarget->isPICStyleGOT())
8042     OpFlag = X86II::MO_GOTOFF;
8043   else if (Subtarget->isPICStyleStubPIC())
8044     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8045
8046   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8047                                              CP->getAlignment(),
8048                                              CP->getOffset(), OpFlag);
8049   SDLoc DL(CP);
8050   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8051   // With PIC, the address is actually $g + Offset.
8052   if (OpFlag) {
8053     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8054                          DAG.getNode(X86ISD::GlobalBaseReg,
8055                                      SDLoc(), getPointerTy()),
8056                          Result);
8057   }
8058
8059   return Result;
8060 }
8061
8062 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8063   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8064
8065   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8066   // global base reg.
8067   unsigned char OpFlag = 0;
8068   unsigned WrapperKind = X86ISD::Wrapper;
8069   CodeModel::Model M = getTargetMachine().getCodeModel();
8070
8071   if (Subtarget->isPICStyleRIPRel() &&
8072       (M == CodeModel::Small || M == CodeModel::Kernel))
8073     WrapperKind = X86ISD::WrapperRIP;
8074   else if (Subtarget->isPICStyleGOT())
8075     OpFlag = X86II::MO_GOTOFF;
8076   else if (Subtarget->isPICStyleStubPIC())
8077     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8078
8079   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8080                                           OpFlag);
8081   SDLoc DL(JT);
8082   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8083
8084   // With PIC, the address is actually $g + Offset.
8085   if (OpFlag)
8086     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8087                          DAG.getNode(X86ISD::GlobalBaseReg,
8088                                      SDLoc(), getPointerTy()),
8089                          Result);
8090
8091   return Result;
8092 }
8093
8094 SDValue
8095 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8096   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8097
8098   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8099   // global base reg.
8100   unsigned char OpFlag = 0;
8101   unsigned WrapperKind = X86ISD::Wrapper;
8102   CodeModel::Model M = getTargetMachine().getCodeModel();
8103
8104   if (Subtarget->isPICStyleRIPRel() &&
8105       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8106     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8107       OpFlag = X86II::MO_GOTPCREL;
8108     WrapperKind = X86ISD::WrapperRIP;
8109   } else if (Subtarget->isPICStyleGOT()) {
8110     OpFlag = X86II::MO_GOT;
8111   } else if (Subtarget->isPICStyleStubPIC()) {
8112     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8113   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8114     OpFlag = X86II::MO_DARWIN_NONLAZY;
8115   }
8116
8117   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8118
8119   SDLoc DL(Op);
8120   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8121
8122   // With PIC, the address is actually $g + Offset.
8123   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8124       !Subtarget->is64Bit()) {
8125     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8126                          DAG.getNode(X86ISD::GlobalBaseReg,
8127                                      SDLoc(), getPointerTy()),
8128                          Result);
8129   }
8130
8131   // For symbols that require a load from a stub to get the address, emit the
8132   // load.
8133   if (isGlobalStubReference(OpFlag))
8134     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8135                          MachinePointerInfo::getGOT(), false, false, false, 0);
8136
8137   return Result;
8138 }
8139
8140 SDValue
8141 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8142   // Create the TargetBlockAddressAddress node.
8143   unsigned char OpFlags =
8144     Subtarget->ClassifyBlockAddressReference();
8145   CodeModel::Model M = getTargetMachine().getCodeModel();
8146   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8147   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8148   SDLoc dl(Op);
8149   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8150                                              OpFlags);
8151
8152   if (Subtarget->isPICStyleRIPRel() &&
8153       (M == CodeModel::Small || M == CodeModel::Kernel))
8154     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8155   else
8156     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8157
8158   // With PIC, the address is actually $g + Offset.
8159   if (isGlobalRelativeToPICBase(OpFlags)) {
8160     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8161                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8162                          Result);
8163   }
8164
8165   return Result;
8166 }
8167
8168 SDValue
8169 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8170                                       int64_t Offset, SelectionDAG &DAG) const {
8171   // Create the TargetGlobalAddress node, folding in the constant
8172   // offset if it is legal.
8173   unsigned char OpFlags =
8174     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8175   CodeModel::Model M = getTargetMachine().getCodeModel();
8176   SDValue Result;
8177   if (OpFlags == X86II::MO_NO_FLAG &&
8178       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8179     // A direct static reference to a global.
8180     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8181     Offset = 0;
8182   } else {
8183     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8184   }
8185
8186   if (Subtarget->isPICStyleRIPRel() &&
8187       (M == CodeModel::Small || M == CodeModel::Kernel))
8188     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8189   else
8190     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8191
8192   // With PIC, the address is actually $g + Offset.
8193   if (isGlobalRelativeToPICBase(OpFlags)) {
8194     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8195                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8196                          Result);
8197   }
8198
8199   // For globals that require a load from a stub to get the address, emit the
8200   // load.
8201   if (isGlobalStubReference(OpFlags))
8202     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8203                          MachinePointerInfo::getGOT(), false, false, false, 0);
8204
8205   // If there was a non-zero offset that we didn't fold, create an explicit
8206   // addition for it.
8207   if (Offset != 0)
8208     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8209                          DAG.getConstant(Offset, getPointerTy()));
8210
8211   return Result;
8212 }
8213
8214 SDValue
8215 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8216   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8217   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8218   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8219 }
8220
8221 static SDValue
8222 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8223            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8224            unsigned char OperandFlags, bool LocalDynamic = false) {
8225   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8226   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8227   SDLoc dl(GA);
8228   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8229                                            GA->getValueType(0),
8230                                            GA->getOffset(),
8231                                            OperandFlags);
8232
8233   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8234                                            : X86ISD::TLSADDR;
8235
8236   if (InFlag) {
8237     SDValue Ops[] = { Chain,  TGA, *InFlag };
8238     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8239   } else {
8240     SDValue Ops[]  = { Chain, TGA };
8241     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8242   }
8243
8244   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8245   MFI->setAdjustsStack(true);
8246
8247   SDValue Flag = Chain.getValue(1);
8248   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8249 }
8250
8251 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8252 static SDValue
8253 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8254                                 const EVT PtrVT) {
8255   SDValue InFlag;
8256   SDLoc dl(GA);  // ? function entry point might be better
8257   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8258                                    DAG.getNode(X86ISD::GlobalBaseReg,
8259                                                SDLoc(), PtrVT), InFlag);
8260   InFlag = Chain.getValue(1);
8261
8262   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8263 }
8264
8265 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8266 static SDValue
8267 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8268                                 const EVT PtrVT) {
8269   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8270                     X86::RAX, X86II::MO_TLSGD);
8271 }
8272
8273 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8274                                            SelectionDAG &DAG,
8275                                            const EVT PtrVT,
8276                                            bool is64Bit) {
8277   SDLoc dl(GA);
8278
8279   // Get the start address of the TLS block for this module.
8280   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8281       .getInfo<X86MachineFunctionInfo>();
8282   MFI->incNumLocalDynamicTLSAccesses();
8283
8284   SDValue Base;
8285   if (is64Bit) {
8286     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8287                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8288   } else {
8289     SDValue InFlag;
8290     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8291         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8292     InFlag = Chain.getValue(1);
8293     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8294                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8295   }
8296
8297   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8298   // of Base.
8299
8300   // Build x@dtpoff.
8301   unsigned char OperandFlags = X86II::MO_DTPOFF;
8302   unsigned WrapperKind = X86ISD::Wrapper;
8303   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8304                                            GA->getValueType(0),
8305                                            GA->getOffset(), OperandFlags);
8306   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8307
8308   // Add x@dtpoff with the base.
8309   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8310 }
8311
8312 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8313 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8314                                    const EVT PtrVT, TLSModel::Model model,
8315                                    bool is64Bit, bool isPIC) {
8316   SDLoc dl(GA);
8317
8318   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8319   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8320                                                          is64Bit ? 257 : 256));
8321
8322   SDValue ThreadPointer =
8323       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8324                   MachinePointerInfo(Ptr), false, false, false, 0);
8325
8326   unsigned char OperandFlags = 0;
8327   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8328   // initialexec.
8329   unsigned WrapperKind = X86ISD::Wrapper;
8330   if (model == TLSModel::LocalExec) {
8331     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8332   } else if (model == TLSModel::InitialExec) {
8333     if (is64Bit) {
8334       OperandFlags = X86II::MO_GOTTPOFF;
8335       WrapperKind = X86ISD::WrapperRIP;
8336     } else {
8337       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8338     }
8339   } else {
8340     llvm_unreachable("Unexpected model");
8341   }
8342
8343   // emit "addl x@ntpoff,%eax" (local exec)
8344   // or "addl x@indntpoff,%eax" (initial exec)
8345   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8346   SDValue TGA =
8347       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8348                                  GA->getOffset(), OperandFlags);
8349   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8350
8351   if (model == TLSModel::InitialExec) {
8352     if (isPIC && !is64Bit) {
8353       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8354                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8355                            Offset);
8356     }
8357
8358     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8359                          MachinePointerInfo::getGOT(), false, false, false, 0);
8360   }
8361
8362   // The address of the thread local variable is the add of the thread
8363   // pointer with the offset of the variable.
8364   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8365 }
8366
8367 SDValue
8368 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8369
8370   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8371   const GlobalValue *GV = GA->getGlobal();
8372
8373   if (Subtarget->isTargetELF()) {
8374     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8375
8376     switch (model) {
8377       case TLSModel::GeneralDynamic:
8378         if (Subtarget->is64Bit())
8379           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8380         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8381       case TLSModel::LocalDynamic:
8382         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8383                                            Subtarget->is64Bit());
8384       case TLSModel::InitialExec:
8385       case TLSModel::LocalExec:
8386         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8387                                    Subtarget->is64Bit(),
8388                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8389     }
8390     llvm_unreachable("Unknown TLS model.");
8391   }
8392
8393   if (Subtarget->isTargetDarwin()) {
8394     // Darwin only has one model of TLS.  Lower to that.
8395     unsigned char OpFlag = 0;
8396     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8397                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8398
8399     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8400     // global base reg.
8401     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8402                   !Subtarget->is64Bit();
8403     if (PIC32)
8404       OpFlag = X86II::MO_TLVP_PIC_BASE;
8405     else
8406       OpFlag = X86II::MO_TLVP;
8407     SDLoc DL(Op);
8408     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8409                                                 GA->getValueType(0),
8410                                                 GA->getOffset(), OpFlag);
8411     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8412
8413     // With PIC32, the address is actually $g + Offset.
8414     if (PIC32)
8415       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8416                            DAG.getNode(X86ISD::GlobalBaseReg,
8417                                        SDLoc(), getPointerTy()),
8418                            Offset);
8419
8420     // Lowering the machine isd will make sure everything is in the right
8421     // location.
8422     SDValue Chain = DAG.getEntryNode();
8423     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8424     SDValue Args[] = { Chain, Offset };
8425     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8426
8427     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8428     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8429     MFI->setAdjustsStack(true);
8430
8431     // And our return value (tls address) is in the standard call return value
8432     // location.
8433     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8434     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8435                               Chain.getValue(1));
8436   }
8437
8438   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8439     // Just use the implicit TLS architecture
8440     // Need to generate someting similar to:
8441     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8442     //                                  ; from TEB
8443     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8444     //   mov     rcx, qword [rdx+rcx*8]
8445     //   mov     eax, .tls$:tlsvar
8446     //   [rax+rcx] contains the address
8447     // Windows 64bit: gs:0x58
8448     // Windows 32bit: fs:__tls_array
8449
8450     // If GV is an alias then use the aliasee for determining
8451     // thread-localness.
8452     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8453       GV = GA->resolveAliasedGlobal(false);
8454     SDLoc dl(GA);
8455     SDValue Chain = DAG.getEntryNode();
8456
8457     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8458     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8459     // use its literal value of 0x2C.
8460     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8461                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8462                                                              256)
8463                                         : Type::getInt32PtrTy(*DAG.getContext(),
8464                                                               257));
8465
8466     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8467       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8468         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8469
8470     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8471                                         MachinePointerInfo(Ptr),
8472                                         false, false, false, 0);
8473
8474     // Load the _tls_index variable
8475     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8476     if (Subtarget->is64Bit())
8477       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8478                            IDX, MachinePointerInfo(), MVT::i32,
8479                            false, false, 0);
8480     else
8481       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8482                         false, false, false, 0);
8483
8484     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8485                                     getPointerTy());
8486     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8487
8488     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8489     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8490                       false, false, false, 0);
8491
8492     // Get the offset of start of .tls section
8493     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8494                                              GA->getValueType(0),
8495                                              GA->getOffset(), X86II::MO_SECREL);
8496     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8497
8498     // The address of the thread local variable is the add of the thread
8499     // pointer with the offset of the variable.
8500     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8501   }
8502
8503   llvm_unreachable("TLS not implemented for this target.");
8504 }
8505
8506 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8507 /// and take a 2 x i32 value to shift plus a shift amount.
8508 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8509   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8510   EVT VT = Op.getValueType();
8511   unsigned VTBits = VT.getSizeInBits();
8512   SDLoc dl(Op);
8513   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8514   SDValue ShOpLo = Op.getOperand(0);
8515   SDValue ShOpHi = Op.getOperand(1);
8516   SDValue ShAmt  = Op.getOperand(2);
8517   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8518   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8519   // during isel.
8520   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8521                                   DAG.getConstant(VTBits - 1, MVT::i8));
8522   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8523                                      DAG.getConstant(VTBits - 1, MVT::i8))
8524                        : DAG.getConstant(0, VT);
8525
8526   SDValue Tmp2, Tmp3;
8527   if (Op.getOpcode() == ISD::SHL_PARTS) {
8528     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8529     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8530   } else {
8531     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8532     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8533   }
8534
8535   // If the shift amount is larger or equal than the width of a part we can't
8536   // rely on the results of shld/shrd. Insert a test and select the appropriate
8537   // values for large shift amounts.
8538   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8539                                 DAG.getConstant(VTBits, MVT::i8));
8540   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8541                              AndNode, DAG.getConstant(0, MVT::i8));
8542
8543   SDValue Hi, Lo;
8544   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8545   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8546   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8547
8548   if (Op.getOpcode() == ISD::SHL_PARTS) {
8549     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8550     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8551   } else {
8552     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8553     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8554   }
8555
8556   SDValue Ops[2] = { Lo, Hi };
8557   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8558 }
8559
8560 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8561                                            SelectionDAG &DAG) const {
8562   EVT SrcVT = Op.getOperand(0).getValueType();
8563
8564   if (SrcVT.isVector())
8565     return SDValue();
8566
8567   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8568          "Unknown SINT_TO_FP to lower!");
8569
8570   // These are really Legal; return the operand so the caller accepts it as
8571   // Legal.
8572   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8573     return Op;
8574   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8575       Subtarget->is64Bit()) {
8576     return Op;
8577   }
8578
8579   SDLoc dl(Op);
8580   unsigned Size = SrcVT.getSizeInBits()/8;
8581   MachineFunction &MF = DAG.getMachineFunction();
8582   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8583   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8584   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8585                                StackSlot,
8586                                MachinePointerInfo::getFixedStack(SSFI),
8587                                false, false, 0);
8588   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8589 }
8590
8591 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8592                                      SDValue StackSlot,
8593                                      SelectionDAG &DAG) const {
8594   // Build the FILD
8595   SDLoc DL(Op);
8596   SDVTList Tys;
8597   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8598   if (useSSE)
8599     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8600   else
8601     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8602
8603   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8604
8605   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8606   MachineMemOperand *MMO;
8607   if (FI) {
8608     int SSFI = FI->getIndex();
8609     MMO =
8610       DAG.getMachineFunction()
8611       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8612                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8613   } else {
8614     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8615     StackSlot = StackSlot.getOperand(1);
8616   }
8617   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8618   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8619                                            X86ISD::FILD, DL,
8620                                            Tys, Ops, array_lengthof(Ops),
8621                                            SrcVT, MMO);
8622
8623   if (useSSE) {
8624     Chain = Result.getValue(1);
8625     SDValue InFlag = Result.getValue(2);
8626
8627     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8628     // shouldn't be necessary except that RFP cannot be live across
8629     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8630     MachineFunction &MF = DAG.getMachineFunction();
8631     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8632     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8633     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8634     Tys = DAG.getVTList(MVT::Other);
8635     SDValue Ops[] = {
8636       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8637     };
8638     MachineMemOperand *MMO =
8639       DAG.getMachineFunction()
8640       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8641                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8642
8643     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8644                                     Ops, array_lengthof(Ops),
8645                                     Op.getValueType(), MMO);
8646     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8647                          MachinePointerInfo::getFixedStack(SSFI),
8648                          false, false, false, 0);
8649   }
8650
8651   return Result;
8652 }
8653
8654 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8655 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8656                                                SelectionDAG &DAG) const {
8657   // This algorithm is not obvious. Here it is what we're trying to output:
8658   /*
8659      movq       %rax,  %xmm0
8660      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8661      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8662      #ifdef __SSE3__
8663        haddpd   %xmm0, %xmm0
8664      #else
8665        pshufd   $0x4e, %xmm0, %xmm1
8666        addpd    %xmm1, %xmm0
8667      #endif
8668   */
8669
8670   SDLoc dl(Op);
8671   LLVMContext *Context = DAG.getContext();
8672
8673   // Build some magic constants.
8674   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8675   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8676   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8677
8678   SmallVector<Constant*,2> CV1;
8679   CV1.push_back(
8680     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8681                                       APInt(64, 0x4330000000000000ULL))));
8682   CV1.push_back(
8683     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8684                                       APInt(64, 0x4530000000000000ULL))));
8685   Constant *C1 = ConstantVector::get(CV1);
8686   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8687
8688   // Load the 64-bit value into an XMM register.
8689   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8690                             Op.getOperand(0));
8691   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8692                               MachinePointerInfo::getConstantPool(),
8693                               false, false, false, 16);
8694   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8695                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8696                               CLod0);
8697
8698   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8699                               MachinePointerInfo::getConstantPool(),
8700                               false, false, false, 16);
8701   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8702   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8703   SDValue Result;
8704
8705   if (Subtarget->hasSSE3()) {
8706     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8707     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8708   } else {
8709     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8710     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8711                                            S2F, 0x4E, DAG);
8712     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8713                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8714                          Sub);
8715   }
8716
8717   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8718                      DAG.getIntPtrConstant(0));
8719 }
8720
8721 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8722 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8723                                                SelectionDAG &DAG) const {
8724   SDLoc dl(Op);
8725   // FP constant to bias correct the final result.
8726   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8727                                    MVT::f64);
8728
8729   // Load the 32-bit value into an XMM register.
8730   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8731                              Op.getOperand(0));
8732
8733   // Zero out the upper parts of the register.
8734   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8735
8736   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8737                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8738                      DAG.getIntPtrConstant(0));
8739
8740   // Or the load with the bias.
8741   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8742                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8743                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8744                                                    MVT::v2f64, Load)),
8745                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8746                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8747                                                    MVT::v2f64, Bias)));
8748   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8749                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8750                    DAG.getIntPtrConstant(0));
8751
8752   // Subtract the bias.
8753   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8754
8755   // Handle final rounding.
8756   EVT DestVT = Op.getValueType();
8757
8758   if (DestVT.bitsLT(MVT::f64))
8759     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8760                        DAG.getIntPtrConstant(0));
8761   if (DestVT.bitsGT(MVT::f64))
8762     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8763
8764   // Handle final rounding.
8765   return Sub;
8766 }
8767
8768 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8769                                                SelectionDAG &DAG) const {
8770   SDValue N0 = Op.getOperand(0);
8771   EVT SVT = N0.getValueType();
8772   SDLoc dl(Op);
8773
8774   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8775           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8776          "Custom UINT_TO_FP is not supported!");
8777
8778   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8779                              SVT.getVectorNumElements());
8780   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8781                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8782 }
8783
8784 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8785                                            SelectionDAG &DAG) const {
8786   SDValue N0 = Op.getOperand(0);
8787   SDLoc dl(Op);
8788
8789   if (Op.getValueType().isVector())
8790     return lowerUINT_TO_FP_vec(Op, DAG);
8791
8792   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8793   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8794   // the optimization here.
8795   if (DAG.SignBitIsZero(N0))
8796     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8797
8798   EVT SrcVT = N0.getValueType();
8799   EVT DstVT = Op.getValueType();
8800   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8801     return LowerUINT_TO_FP_i64(Op, DAG);
8802   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8803     return LowerUINT_TO_FP_i32(Op, DAG);
8804   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8805     return SDValue();
8806
8807   // Make a 64-bit buffer, and use it to build an FILD.
8808   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8809   if (SrcVT == MVT::i32) {
8810     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8811     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8812                                      getPointerTy(), StackSlot, WordOff);
8813     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8814                                   StackSlot, MachinePointerInfo(),
8815                                   false, false, 0);
8816     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8817                                   OffsetSlot, MachinePointerInfo(),
8818                                   false, false, 0);
8819     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8820     return Fild;
8821   }
8822
8823   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8824   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8825                                StackSlot, MachinePointerInfo(),
8826                                false, false, 0);
8827   // For i64 source, we need to add the appropriate power of 2 if the input
8828   // was negative.  This is the same as the optimization in
8829   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8830   // we must be careful to do the computation in x87 extended precision, not
8831   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8832   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8833   MachineMemOperand *MMO =
8834     DAG.getMachineFunction()
8835     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8836                           MachineMemOperand::MOLoad, 8, 8);
8837
8838   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8839   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8840   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8841                                          array_lengthof(Ops), MVT::i64, MMO);
8842
8843   APInt FF(32, 0x5F800000ULL);
8844
8845   // Check whether the sign bit is set.
8846   SDValue SignSet = DAG.getSetCC(dl,
8847                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8848                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8849                                  ISD::SETLT);
8850
8851   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8852   SDValue FudgePtr = DAG.getConstantPool(
8853                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8854                                          getPointerTy());
8855
8856   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8857   SDValue Zero = DAG.getIntPtrConstant(0);
8858   SDValue Four = DAG.getIntPtrConstant(4);
8859   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8860                                Zero, Four);
8861   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8862
8863   // Load the value out, extending it from f32 to f80.
8864   // FIXME: Avoid the extend by constructing the right constant pool?
8865   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8866                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8867                                  MVT::f32, false, false, 4);
8868   // Extend everything to 80 bits to force it to be done on x87.
8869   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8870   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8871 }
8872
8873 std::pair<SDValue,SDValue>
8874 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8875                                     bool IsSigned, bool IsReplace) const {
8876   SDLoc DL(Op);
8877
8878   EVT DstTy = Op.getValueType();
8879
8880   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8881     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8882     DstTy = MVT::i64;
8883   }
8884
8885   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8886          DstTy.getSimpleVT() >= MVT::i16 &&
8887          "Unknown FP_TO_INT to lower!");
8888
8889   // These are really Legal.
8890   if (DstTy == MVT::i32 &&
8891       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8892     return std::make_pair(SDValue(), SDValue());
8893   if (Subtarget->is64Bit() &&
8894       DstTy == MVT::i64 &&
8895       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8896     return std::make_pair(SDValue(), SDValue());
8897
8898   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8899   // stack slot, or into the FTOL runtime function.
8900   MachineFunction &MF = DAG.getMachineFunction();
8901   unsigned MemSize = DstTy.getSizeInBits()/8;
8902   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8903   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8904
8905   unsigned Opc;
8906   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8907     Opc = X86ISD::WIN_FTOL;
8908   else
8909     switch (DstTy.getSimpleVT().SimpleTy) {
8910     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8911     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8912     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8913     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8914     }
8915
8916   SDValue Chain = DAG.getEntryNode();
8917   SDValue Value = Op.getOperand(0);
8918   EVT TheVT = Op.getOperand(0).getValueType();
8919   // FIXME This causes a redundant load/store if the SSE-class value is already
8920   // in memory, such as if it is on the callstack.
8921   if (isScalarFPTypeInSSEReg(TheVT)) {
8922     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8923     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8924                          MachinePointerInfo::getFixedStack(SSFI),
8925                          false, false, 0);
8926     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8927     SDValue Ops[] = {
8928       Chain, StackSlot, DAG.getValueType(TheVT)
8929     };
8930
8931     MachineMemOperand *MMO =
8932       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8933                               MachineMemOperand::MOLoad, MemSize, MemSize);
8934     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8935                                     array_lengthof(Ops), DstTy, MMO);
8936     Chain = Value.getValue(1);
8937     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8938     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8939   }
8940
8941   MachineMemOperand *MMO =
8942     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8943                             MachineMemOperand::MOStore, MemSize, MemSize);
8944
8945   if (Opc != X86ISD::WIN_FTOL) {
8946     // Build the FP_TO_INT*_IN_MEM
8947     SDValue Ops[] = { Chain, Value, StackSlot };
8948     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8949                                            Ops, array_lengthof(Ops), DstTy,
8950                                            MMO);
8951     return std::make_pair(FIST, StackSlot);
8952   } else {
8953     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8954       DAG.getVTList(MVT::Other, MVT::Glue),
8955       Chain, Value);
8956     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8957       MVT::i32, ftol.getValue(1));
8958     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8959       MVT::i32, eax.getValue(2));
8960     SDValue Ops[] = { eax, edx };
8961     SDValue pair = IsReplace
8962       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8963       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8964     return std::make_pair(pair, SDValue());
8965   }
8966 }
8967
8968 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8969                               const X86Subtarget *Subtarget) {
8970   MVT VT = Op->getSimpleValueType(0);
8971   SDValue In = Op->getOperand(0);
8972   MVT InVT = In.getSimpleValueType();
8973   SDLoc dl(Op);
8974
8975   // Optimize vectors in AVX mode:
8976   //
8977   //   v8i16 -> v8i32
8978   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8979   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8980   //   Concat upper and lower parts.
8981   //
8982   //   v4i32 -> v4i64
8983   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8984   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8985   //   Concat upper and lower parts.
8986   //
8987
8988   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
8989       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8990       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8991     return SDValue();
8992
8993   if (Subtarget->hasInt256())
8994     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8995
8996   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8997   SDValue Undef = DAG.getUNDEF(InVT);
8998   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8999   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9000   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9001
9002   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9003                              VT.getVectorNumElements()/2);
9004
9005   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9006   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9007
9008   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9009 }
9010
9011 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9012                                         SelectionDAG &DAG) {
9013   MVT VT = Op->getValueType(0).getSimpleVT();
9014   SDValue In = Op->getOperand(0);
9015   MVT InVT = In.getValueType().getSimpleVT();
9016   SDLoc DL(Op);
9017   unsigned int NumElts = VT.getVectorNumElements();
9018   if (NumElts != 8 && NumElts != 16)
9019     return SDValue();
9020
9021   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9022     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9023
9024   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9025   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9026   // Now we have only mask extension
9027   assert(InVT.getVectorElementType() == MVT::i1);
9028   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9029   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9030   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9031   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9032   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9033                            MachinePointerInfo::getConstantPool(),
9034                            false, false, false, Alignment);
9035
9036   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9037   if (VT.is512BitVector())
9038     return Brcst;
9039   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9040 }
9041
9042 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9043                                SelectionDAG &DAG) {
9044   if (Subtarget->hasFp256()) {
9045     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9046     if (Res.getNode())
9047       return Res;
9048   }
9049
9050   return SDValue();
9051 }
9052
9053 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9054                                 SelectionDAG &DAG) {
9055   SDLoc DL(Op);
9056   MVT VT = Op.getSimpleValueType();
9057   SDValue In = Op.getOperand(0);
9058   MVT SVT = In.getSimpleValueType();
9059
9060   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9061     return LowerZERO_EXTEND_AVX512(Op, DAG);
9062
9063   if (Subtarget->hasFp256()) {
9064     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9065     if (Res.getNode())
9066       return Res;
9067   }
9068
9069   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9070          VT.getVectorNumElements() != SVT.getVectorNumElements());
9071   return SDValue();
9072 }
9073
9074 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9075   SDLoc DL(Op);
9076   MVT VT = Op.getSimpleValueType();
9077   SDValue In = Op.getOperand(0);
9078   MVT InVT = In.getSimpleValueType();
9079
9080   if (VT == MVT::i1) {
9081     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9082            "Invalid scalar TRUNCATE operation");
9083     if (InVT == MVT::i32)
9084       return SDValue();
9085     if (InVT.getSizeInBits() == 64)
9086       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9087     else if (InVT.getSizeInBits() < 32)
9088       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9089     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9090   }
9091   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9092          "Invalid TRUNCATE operation");
9093
9094   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9095     if (VT.getVectorElementType().getSizeInBits() >=8)
9096       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9097
9098     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9099     unsigned NumElts = InVT.getVectorNumElements();
9100     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9101     if (InVT.getSizeInBits() < 512) {
9102       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9103       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9104       InVT = ExtVT;
9105     }
9106     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9107     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9108     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9109     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9110     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9111                            MachinePointerInfo::getConstantPool(),
9112                            false, false, false, Alignment);
9113     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9114     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9115     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9116   }
9117
9118   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9119     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9120     if (Subtarget->hasInt256()) {
9121       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9122       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9123       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9124                                 ShufMask);
9125       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9126                          DAG.getIntPtrConstant(0));
9127     }
9128
9129     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
9130     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9131                                DAG.getIntPtrConstant(0));
9132     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9133                                DAG.getIntPtrConstant(2));
9134
9135     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9136     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9137
9138     // The PSHUFD mask:
9139     static const int ShufMask1[] = {0, 2, 0, 0};
9140     SDValue Undef = DAG.getUNDEF(VT);
9141     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
9142     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
9143
9144     // The MOVLHPS mask:
9145     static const int ShufMask2[] = {0, 1, 4, 5};
9146     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
9147   }
9148
9149   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9150     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9151     if (Subtarget->hasInt256()) {
9152       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9153
9154       SmallVector<SDValue,32> pshufbMask;
9155       for (unsigned i = 0; i < 2; ++i) {
9156         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9157         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9158         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9159         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9160         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9161         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9162         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9163         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9164         for (unsigned j = 0; j < 8; ++j)
9165           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9166       }
9167       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9168                                &pshufbMask[0], 32);
9169       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9170       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9171
9172       static const int ShufMask[] = {0,  2,  -1,  -1};
9173       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9174                                 &ShufMask[0]);
9175       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9176                        DAG.getIntPtrConstant(0));
9177       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9178     }
9179
9180     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9181                                DAG.getIntPtrConstant(0));
9182
9183     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9184                                DAG.getIntPtrConstant(4));
9185
9186     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9187     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9188
9189     // The PSHUFB mask:
9190     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9191                                    -1, -1, -1, -1, -1, -1, -1, -1};
9192
9193     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9194     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9195     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9196
9197     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9198     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9199
9200     // The MOVLHPS Mask:
9201     static const int ShufMask2[] = {0, 1, 4, 5};
9202     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9203     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9204   }
9205
9206   // Handle truncation of V256 to V128 using shuffles.
9207   if (!VT.is128BitVector() || !InVT.is256BitVector())
9208     return SDValue();
9209
9210   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9211
9212   unsigned NumElems = VT.getVectorNumElements();
9213   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9214                              NumElems * 2);
9215
9216   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9217   // Prepare truncation shuffle mask
9218   for (unsigned i = 0; i != NumElems; ++i)
9219     MaskVec[i] = i * 2;
9220   SDValue V = DAG.getVectorShuffle(NVT, DL,
9221                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9222                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9223   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9224                      DAG.getIntPtrConstant(0));
9225 }
9226
9227 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9228                                            SelectionDAG &DAG) const {
9229   MVT VT = Op.getSimpleValueType();
9230   if (VT.isVector()) {
9231     if (VT == MVT::v8i16)
9232       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9233                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9234                                      MVT::v8i32, Op.getOperand(0)));
9235     return SDValue();
9236   }
9237
9238   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9239     /*IsSigned=*/ true, /*IsReplace=*/ false);
9240   SDValue FIST = Vals.first, StackSlot = Vals.second;
9241   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9242   if (FIST.getNode() == 0) return Op;
9243
9244   if (StackSlot.getNode())
9245     // Load the result.
9246     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9247                        FIST, StackSlot, MachinePointerInfo(),
9248                        false, false, false, 0);
9249
9250   // The node is the result.
9251   return FIST;
9252 }
9253
9254 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9255                                            SelectionDAG &DAG) const {
9256   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9257     /*IsSigned=*/ false, /*IsReplace=*/ false);
9258   SDValue FIST = Vals.first, StackSlot = Vals.second;
9259   assert(FIST.getNode() && "Unexpected failure");
9260
9261   if (StackSlot.getNode())
9262     // Load the result.
9263     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9264                        FIST, StackSlot, MachinePointerInfo(),
9265                        false, false, false, 0);
9266
9267   // The node is the result.
9268   return FIST;
9269 }
9270
9271 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9272   SDLoc DL(Op);
9273   MVT VT = Op.getSimpleValueType();
9274   SDValue In = Op.getOperand(0);
9275   MVT SVT = In.getSimpleValueType();
9276
9277   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9278
9279   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9280                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9281                                  In, DAG.getUNDEF(SVT)));
9282 }
9283
9284 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9285   LLVMContext *Context = DAG.getContext();
9286   SDLoc dl(Op);
9287   MVT VT = Op.getSimpleValueType();
9288   MVT EltVT = VT;
9289   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9290   if (VT.isVector()) {
9291     EltVT = VT.getVectorElementType();
9292     NumElts = VT.getVectorNumElements();
9293   }
9294   Constant *C;
9295   if (EltVT == MVT::f64)
9296     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9297                                           APInt(64, ~(1ULL << 63))));
9298   else
9299     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9300                                           APInt(32, ~(1U << 31))));
9301   C = ConstantVector::getSplat(NumElts, C);
9302   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9303   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9304   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9305                              MachinePointerInfo::getConstantPool(),
9306                              false, false, false, Alignment);
9307   if (VT.isVector()) {
9308     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9309     return DAG.getNode(ISD::BITCAST, dl, VT,
9310                        DAG.getNode(ISD::AND, dl, ANDVT,
9311                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9312                                                Op.getOperand(0)),
9313                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9314   }
9315   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9316 }
9317
9318 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9319   LLVMContext *Context = DAG.getContext();
9320   SDLoc dl(Op);
9321   MVT VT = Op.getSimpleValueType();
9322   MVT EltVT = VT;
9323   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9324   if (VT.isVector()) {
9325     EltVT = VT.getVectorElementType();
9326     NumElts = VT.getVectorNumElements();
9327   }
9328   Constant *C;
9329   if (EltVT == MVT::f64)
9330     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9331                                           APInt(64, 1ULL << 63)));
9332   else
9333     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9334                                           APInt(32, 1U << 31)));
9335   C = ConstantVector::getSplat(NumElts, C);
9336   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9337   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9338   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9339                              MachinePointerInfo::getConstantPool(),
9340                              false, false, false, Alignment);
9341   if (VT.isVector()) {
9342     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9343     return DAG.getNode(ISD::BITCAST, dl, VT,
9344                        DAG.getNode(ISD::XOR, dl, XORVT,
9345                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9346                                                Op.getOperand(0)),
9347                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9348   }
9349
9350   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9351 }
9352
9353 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9354   LLVMContext *Context = DAG.getContext();
9355   SDValue Op0 = Op.getOperand(0);
9356   SDValue Op1 = Op.getOperand(1);
9357   SDLoc dl(Op);
9358   MVT VT = Op.getSimpleValueType();
9359   MVT SrcVT = Op1.getSimpleValueType();
9360
9361   // If second operand is smaller, extend it first.
9362   if (SrcVT.bitsLT(VT)) {
9363     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9364     SrcVT = VT;
9365   }
9366   // And if it is bigger, shrink it first.
9367   if (SrcVT.bitsGT(VT)) {
9368     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9369     SrcVT = VT;
9370   }
9371
9372   // At this point the operands and the result should have the same
9373   // type, and that won't be f80 since that is not custom lowered.
9374
9375   // First get the sign bit of second operand.
9376   SmallVector<Constant*,4> CV;
9377   if (SrcVT == MVT::f64) {
9378     const fltSemantics &Sem = APFloat::IEEEdouble;
9379     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9380     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9381   } else {
9382     const fltSemantics &Sem = APFloat::IEEEsingle;
9383     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9384     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9385     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9386     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9387   }
9388   Constant *C = ConstantVector::get(CV);
9389   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9390   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9391                               MachinePointerInfo::getConstantPool(),
9392                               false, false, false, 16);
9393   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9394
9395   // Shift sign bit right or left if the two operands have different types.
9396   if (SrcVT.bitsGT(VT)) {
9397     // Op0 is MVT::f32, Op1 is MVT::f64.
9398     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9399     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9400                           DAG.getConstant(32, MVT::i32));
9401     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9402     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9403                           DAG.getIntPtrConstant(0));
9404   }
9405
9406   // Clear first operand sign bit.
9407   CV.clear();
9408   if (VT == MVT::f64) {
9409     const fltSemantics &Sem = APFloat::IEEEdouble;
9410     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9411                                                    APInt(64, ~(1ULL << 63)))));
9412     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9413   } else {
9414     const fltSemantics &Sem = APFloat::IEEEsingle;
9415     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9416                                                    APInt(32, ~(1U << 31)))));
9417     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9418     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9419     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9420   }
9421   C = ConstantVector::get(CV);
9422   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9423   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9424                               MachinePointerInfo::getConstantPool(),
9425                               false, false, false, 16);
9426   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9427
9428   // Or the value with the sign bit.
9429   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9430 }
9431
9432 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9433   SDValue N0 = Op.getOperand(0);
9434   SDLoc dl(Op);
9435   MVT VT = Op.getSimpleValueType();
9436
9437   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9438   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9439                                   DAG.getConstant(1, VT));
9440   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9441 }
9442
9443 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9444 //
9445 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9446                                       SelectionDAG &DAG) {
9447   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9448
9449   if (!Subtarget->hasSSE41())
9450     return SDValue();
9451
9452   if (!Op->hasOneUse())
9453     return SDValue();
9454
9455   SDNode *N = Op.getNode();
9456   SDLoc DL(N);
9457
9458   SmallVector<SDValue, 8> Opnds;
9459   DenseMap<SDValue, unsigned> VecInMap;
9460   EVT VT = MVT::Other;
9461
9462   // Recognize a special case where a vector is casted into wide integer to
9463   // test all 0s.
9464   Opnds.push_back(N->getOperand(0));
9465   Opnds.push_back(N->getOperand(1));
9466
9467   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9468     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9469     // BFS traverse all OR'd operands.
9470     if (I->getOpcode() == ISD::OR) {
9471       Opnds.push_back(I->getOperand(0));
9472       Opnds.push_back(I->getOperand(1));
9473       // Re-evaluate the number of nodes to be traversed.
9474       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9475       continue;
9476     }
9477
9478     // Quit if a non-EXTRACT_VECTOR_ELT
9479     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9480       return SDValue();
9481
9482     // Quit if without a constant index.
9483     SDValue Idx = I->getOperand(1);
9484     if (!isa<ConstantSDNode>(Idx))
9485       return SDValue();
9486
9487     SDValue ExtractedFromVec = I->getOperand(0);
9488     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9489     if (M == VecInMap.end()) {
9490       VT = ExtractedFromVec.getValueType();
9491       // Quit if not 128/256-bit vector.
9492       if (!VT.is128BitVector() && !VT.is256BitVector())
9493         return SDValue();
9494       // Quit if not the same type.
9495       if (VecInMap.begin() != VecInMap.end() &&
9496           VT != VecInMap.begin()->first.getValueType())
9497         return SDValue();
9498       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9499     }
9500     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9501   }
9502
9503   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9504          "Not extracted from 128-/256-bit vector.");
9505
9506   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9507   SmallVector<SDValue, 8> VecIns;
9508
9509   for (DenseMap<SDValue, unsigned>::const_iterator
9510         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9511     // Quit if not all elements are used.
9512     if (I->second != FullMask)
9513       return SDValue();
9514     VecIns.push_back(I->first);
9515   }
9516
9517   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9518
9519   // Cast all vectors into TestVT for PTEST.
9520   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9521     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9522
9523   // If more than one full vectors are evaluated, OR them first before PTEST.
9524   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9525     // Each iteration will OR 2 nodes and append the result until there is only
9526     // 1 node left, i.e. the final OR'd value of all vectors.
9527     SDValue LHS = VecIns[Slot];
9528     SDValue RHS = VecIns[Slot + 1];
9529     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9530   }
9531
9532   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9533                      VecIns.back(), VecIns.back());
9534 }
9535
9536 /// Emit nodes that will be selected as "test Op0,Op0", or something
9537 /// equivalent.
9538 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9539                                     SelectionDAG &DAG) const {
9540   SDLoc dl(Op);
9541
9542   // CF and OF aren't always set the way we want. Determine which
9543   // of these we need.
9544   bool NeedCF = false;
9545   bool NeedOF = false;
9546   switch (X86CC) {
9547   default: break;
9548   case X86::COND_A: case X86::COND_AE:
9549   case X86::COND_B: case X86::COND_BE:
9550     NeedCF = true;
9551     break;
9552   case X86::COND_G: case X86::COND_GE:
9553   case X86::COND_L: case X86::COND_LE:
9554   case X86::COND_O: case X86::COND_NO:
9555     NeedOF = true;
9556     break;
9557   }
9558
9559   // See if we can use the EFLAGS value from the operand instead of
9560   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9561   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9562   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9563     // Emit a CMP with 0, which is the TEST pattern.
9564     if (Op.getValueType() == MVT::i1)
9565       return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9566                          DAG.getConstant(0, MVT::i1));
9567     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9568                        DAG.getConstant(0, Op.getValueType()));
9569   }
9570   unsigned Opcode = 0;
9571   unsigned NumOperands = 0;
9572
9573   // Truncate operations may prevent the merge of the SETCC instruction
9574   // and the arithmetic instruction before it. Attempt to truncate the operands
9575   // of the arithmetic instruction and use a reduced bit-width instruction.
9576   bool NeedTruncation = false;
9577   SDValue ArithOp = Op;
9578   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9579     SDValue Arith = Op->getOperand(0);
9580     // Both the trunc and the arithmetic op need to have one user each.
9581     if (Arith->hasOneUse())
9582       switch (Arith.getOpcode()) {
9583         default: break;
9584         case ISD::ADD:
9585         case ISD::SUB:
9586         case ISD::AND:
9587         case ISD::OR:
9588         case ISD::XOR: {
9589           NeedTruncation = true;
9590           ArithOp = Arith;
9591         }
9592       }
9593   }
9594
9595   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9596   // which may be the result of a CAST.  We use the variable 'Op', which is the
9597   // non-casted variable when we check for possible users.
9598   switch (ArithOp.getOpcode()) {
9599   case ISD::ADD:
9600     // Due to an isel shortcoming, be conservative if this add is likely to be
9601     // selected as part of a load-modify-store instruction. When the root node
9602     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9603     // uses of other nodes in the match, such as the ADD in this case. This
9604     // leads to the ADD being left around and reselected, with the result being
9605     // two adds in the output.  Alas, even if none our users are stores, that
9606     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9607     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9608     // climbing the DAG back to the root, and it doesn't seem to be worth the
9609     // effort.
9610     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9611          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9612       if (UI->getOpcode() != ISD::CopyToReg &&
9613           UI->getOpcode() != ISD::SETCC &&
9614           UI->getOpcode() != ISD::STORE)
9615         goto default_case;
9616
9617     if (ConstantSDNode *C =
9618         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9619       // An add of one will be selected as an INC.
9620       if (C->getAPIntValue() == 1) {
9621         Opcode = X86ISD::INC;
9622         NumOperands = 1;
9623         break;
9624       }
9625
9626       // An add of negative one (subtract of one) will be selected as a DEC.
9627       if (C->getAPIntValue().isAllOnesValue()) {
9628         Opcode = X86ISD::DEC;
9629         NumOperands = 1;
9630         break;
9631       }
9632     }
9633
9634     // Otherwise use a regular EFLAGS-setting add.
9635     Opcode = X86ISD::ADD;
9636     NumOperands = 2;
9637     break;
9638   case ISD::AND: {
9639     // If the primary and result isn't used, don't bother using X86ISD::AND,
9640     // because a TEST instruction will be better.
9641     bool NonFlagUse = false;
9642     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9643            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9644       SDNode *User = *UI;
9645       unsigned UOpNo = UI.getOperandNo();
9646       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9647         // Look pass truncate.
9648         UOpNo = User->use_begin().getOperandNo();
9649         User = *User->use_begin();
9650       }
9651
9652       if (User->getOpcode() != ISD::BRCOND &&
9653           User->getOpcode() != ISD::SETCC &&
9654           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9655         NonFlagUse = true;
9656         break;
9657       }
9658     }
9659
9660     if (!NonFlagUse)
9661       break;
9662   }
9663     // FALL THROUGH
9664   case ISD::SUB:
9665   case ISD::OR:
9666   case ISD::XOR:
9667     // Due to the ISEL shortcoming noted above, be conservative if this op is
9668     // likely to be selected as part of a load-modify-store instruction.
9669     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9670            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9671       if (UI->getOpcode() == ISD::STORE)
9672         goto default_case;
9673
9674     // Otherwise use a regular EFLAGS-setting instruction.
9675     switch (ArithOp.getOpcode()) {
9676     default: llvm_unreachable("unexpected operator!");
9677     case ISD::SUB: Opcode = X86ISD::SUB; break;
9678     case ISD::XOR: Opcode = X86ISD::XOR; break;
9679     case ISD::AND: Opcode = X86ISD::AND; break;
9680     case ISD::OR: {
9681       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9682         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9683         if (EFLAGS.getNode())
9684           return EFLAGS;
9685       }
9686       Opcode = X86ISD::OR;
9687       break;
9688     }
9689     }
9690
9691     NumOperands = 2;
9692     break;
9693   case X86ISD::ADD:
9694   case X86ISD::SUB:
9695   case X86ISD::INC:
9696   case X86ISD::DEC:
9697   case X86ISD::OR:
9698   case X86ISD::XOR:
9699   case X86ISD::AND:
9700     return SDValue(Op.getNode(), 1);
9701   default:
9702   default_case:
9703     break;
9704   }
9705
9706   // If we found that truncation is beneficial, perform the truncation and
9707   // update 'Op'.
9708   if (NeedTruncation) {
9709     EVT VT = Op.getValueType();
9710     SDValue WideVal = Op->getOperand(0);
9711     EVT WideVT = WideVal.getValueType();
9712     unsigned ConvertedOp = 0;
9713     // Use a target machine opcode to prevent further DAGCombine
9714     // optimizations that may separate the arithmetic operations
9715     // from the setcc node.
9716     switch (WideVal.getOpcode()) {
9717       default: break;
9718       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9719       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9720       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9721       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9722       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9723     }
9724
9725     if (ConvertedOp) {
9726       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9727       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9728         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9729         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9730         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9731       }
9732     }
9733   }
9734
9735   if (Opcode == 0)
9736     // Emit a CMP with 0, which is the TEST pattern.
9737     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9738                        DAG.getConstant(0, Op.getValueType()));
9739
9740   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9741   SmallVector<SDValue, 4> Ops;
9742   for (unsigned i = 0; i != NumOperands; ++i)
9743     Ops.push_back(Op.getOperand(i));
9744
9745   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9746   DAG.ReplaceAllUsesWith(Op, New);
9747   return SDValue(New.getNode(), 1);
9748 }
9749
9750 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9751 /// equivalent.
9752 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9753                                    SelectionDAG &DAG) const {
9754   SDLoc dl(Op0);
9755   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9756     if (C->getAPIntValue() == 0)
9757       return EmitTest(Op0, X86CC, DAG);
9758
9759      if (Op0.getValueType() == MVT::i1) {
9760       Op0 = DAG.getNode(ISD::XOR, dl, MVT::i1, Op0,
9761                         DAG.getConstant(-1, MVT::i1));
9762       return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op0,
9763                          DAG.getConstant(0, MVT::i1));
9764      }
9765   }
9766  
9767   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9768        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9769     // Do the comparison at i32 if it's smaller. This avoids subregister
9770     // aliasing issues. Keep the smaller reference if we're optimizing for
9771     // size, however, as that'll allow better folding of memory operations.
9772     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9773         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9774              AttributeSet::FunctionIndex, Attribute::MinSize)) {
9775       unsigned ExtendOp =
9776           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9777       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9778       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9779     }
9780     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9781     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9782     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9783                               Op0, Op1);
9784     return SDValue(Sub.getNode(), 1);
9785   }
9786   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9787 }
9788
9789 /// Convert a comparison if required by the subtarget.
9790 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9791                                                  SelectionDAG &DAG) const {
9792   // If the subtarget does not support the FUCOMI instruction, floating-point
9793   // comparisons have to be converted.
9794   if (Subtarget->hasCMov() ||
9795       Cmp.getOpcode() != X86ISD::CMP ||
9796       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9797       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9798     return Cmp;
9799
9800   // The instruction selector will select an FUCOM instruction instead of
9801   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9802   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9803   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9804   SDLoc dl(Cmp);
9805   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9806   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9807   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9808                             DAG.getConstant(8, MVT::i8));
9809   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9810   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9811 }
9812
9813 static bool isAllOnes(SDValue V) {
9814   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9815   return C && C->isAllOnesValue();
9816 }
9817
9818 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9819 /// if it's possible.
9820 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9821                                      SDLoc dl, SelectionDAG &DAG) const {
9822   SDValue Op0 = And.getOperand(0);
9823   SDValue Op1 = And.getOperand(1);
9824   if (Op0.getOpcode() == ISD::TRUNCATE)
9825     Op0 = Op0.getOperand(0);
9826   if (Op1.getOpcode() == ISD::TRUNCATE)
9827     Op1 = Op1.getOperand(0);
9828
9829   SDValue LHS, RHS;
9830   if (Op1.getOpcode() == ISD::SHL)
9831     std::swap(Op0, Op1);
9832   if (Op0.getOpcode() == ISD::SHL) {
9833     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9834       if (And00C->getZExtValue() == 1) {
9835         // If we looked past a truncate, check that it's only truncating away
9836         // known zeros.
9837         unsigned BitWidth = Op0.getValueSizeInBits();
9838         unsigned AndBitWidth = And.getValueSizeInBits();
9839         if (BitWidth > AndBitWidth) {
9840           APInt Zeros, Ones;
9841           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9842           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9843             return SDValue();
9844         }
9845         LHS = Op1;
9846         RHS = Op0.getOperand(1);
9847       }
9848   } else if (Op1.getOpcode() == ISD::Constant) {
9849     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9850     uint64_t AndRHSVal = AndRHS->getZExtValue();
9851     SDValue AndLHS = Op0;
9852
9853     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9854       LHS = AndLHS.getOperand(0);
9855       RHS = AndLHS.getOperand(1);
9856     }
9857
9858     // Use BT if the immediate can't be encoded in a TEST instruction.
9859     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9860       LHS = AndLHS;
9861       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9862     }
9863   }
9864
9865   if (LHS.getNode()) {
9866     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9867     // instruction.  Since the shift amount is in-range-or-undefined, we know
9868     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9869     // the encoding for the i16 version is larger than the i32 version.
9870     // Also promote i16 to i32 for performance / code size reason.
9871     if (LHS.getValueType() == MVT::i8 ||
9872         LHS.getValueType() == MVT::i16)
9873       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9874
9875     // If the operand types disagree, extend the shift amount to match.  Since
9876     // BT ignores high bits (like shifts) we can use anyextend.
9877     if (LHS.getValueType() != RHS.getValueType())
9878       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9879
9880     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9881     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9882     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9883                        DAG.getConstant(Cond, MVT::i8), BT);
9884   }
9885
9886   return SDValue();
9887 }
9888
9889 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9890 /// mask CMPs.
9891 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9892                               SDValue &Op1) {
9893   unsigned SSECC;
9894   bool Swap = false;
9895
9896   // SSE Condition code mapping:
9897   //  0 - EQ
9898   //  1 - LT
9899   //  2 - LE
9900   //  3 - UNORD
9901   //  4 - NEQ
9902   //  5 - NLT
9903   //  6 - NLE
9904   //  7 - ORD
9905   switch (SetCCOpcode) {
9906   default: llvm_unreachable("Unexpected SETCC condition");
9907   case ISD::SETOEQ:
9908   case ISD::SETEQ:  SSECC = 0; break;
9909   case ISD::SETOGT:
9910   case ISD::SETGT:  Swap = true; // Fallthrough
9911   case ISD::SETLT:
9912   case ISD::SETOLT: SSECC = 1; break;
9913   case ISD::SETOGE:
9914   case ISD::SETGE:  Swap = true; // Fallthrough
9915   case ISD::SETLE:
9916   case ISD::SETOLE: SSECC = 2; break;
9917   case ISD::SETUO:  SSECC = 3; break;
9918   case ISD::SETUNE:
9919   case ISD::SETNE:  SSECC = 4; break;
9920   case ISD::SETULE: Swap = true; // Fallthrough
9921   case ISD::SETUGE: SSECC = 5; break;
9922   case ISD::SETULT: Swap = true; // Fallthrough
9923   case ISD::SETUGT: SSECC = 6; break;
9924   case ISD::SETO:   SSECC = 7; break;
9925   case ISD::SETUEQ:
9926   case ISD::SETONE: SSECC = 8; break;
9927   }
9928   if (Swap)
9929     std::swap(Op0, Op1);
9930
9931   return SSECC;
9932 }
9933
9934 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9935 // ones, and then concatenate the result back.
9936 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9937   MVT VT = Op.getSimpleValueType();
9938
9939   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9940          "Unsupported value type for operation");
9941
9942   unsigned NumElems = VT.getVectorNumElements();
9943   SDLoc dl(Op);
9944   SDValue CC = Op.getOperand(2);
9945
9946   // Extract the LHS vectors
9947   SDValue LHS = Op.getOperand(0);
9948   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9949   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9950
9951   // Extract the RHS vectors
9952   SDValue RHS = Op.getOperand(1);
9953   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9954   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9955
9956   // Issue the operation on the smaller types and concatenate the result back
9957   MVT EltVT = VT.getVectorElementType();
9958   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9959   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9960                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9961                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9962 }
9963
9964 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9965   SDValue Op0 = Op.getOperand(0);
9966   SDValue Op1 = Op.getOperand(1);
9967   SDValue CC = Op.getOperand(2);
9968   MVT VT = Op.getSimpleValueType();
9969
9970   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9971          Op.getValueType().getScalarType() == MVT::i1 &&
9972          "Cannot set masked compare for this operation");
9973
9974   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9975   SDLoc dl(Op);
9976
9977   bool Unsigned = false;
9978   unsigned SSECC;
9979   switch (SetCCOpcode) {
9980   default: llvm_unreachable("Unexpected SETCC condition");
9981   case ISD::SETNE:  SSECC = 4; break;
9982   case ISD::SETEQ:  SSECC = 0; break;
9983   case ISD::SETUGT: Unsigned = true;
9984   case ISD::SETGT:  SSECC = 6; break; // NLE
9985   case ISD::SETULT: Unsigned = true;
9986   case ISD::SETLT:  SSECC = 1; break;
9987   case ISD::SETUGE: Unsigned = true;
9988   case ISD::SETGE:  SSECC = 5; break; // NLT
9989   case ISD::SETULE: Unsigned = true;
9990   case ISD::SETLE:  SSECC = 2; break;
9991   }
9992   unsigned  Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9993   return DAG.getNode(Opc, dl, VT, Op0, Op1,
9994                      DAG.getConstant(SSECC, MVT::i8));
9995
9996 }
9997
9998 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9999                            SelectionDAG &DAG) {
10000   SDValue Op0 = Op.getOperand(0);
10001   SDValue Op1 = Op.getOperand(1);
10002   SDValue CC = Op.getOperand(2);
10003   MVT VT = Op.getSimpleValueType();
10004   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10005   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10006   SDLoc dl(Op);
10007
10008   if (isFP) {
10009 #ifndef NDEBUG
10010     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10011     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10012 #endif
10013
10014     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10015     unsigned Opc = X86ISD::CMPP;
10016     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10017       assert(VT.getVectorNumElements() <= 16);
10018       Opc = X86ISD::CMPM;
10019     }
10020     // In the two special cases we can't handle, emit two comparisons.
10021     if (SSECC == 8) {
10022       unsigned CC0, CC1;
10023       unsigned CombineOpc;
10024       if (SetCCOpcode == ISD::SETUEQ) {
10025         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10026       } else {
10027         assert(SetCCOpcode == ISD::SETONE);
10028         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10029       }
10030
10031       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10032                                  DAG.getConstant(CC0, MVT::i8));
10033       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10034                                  DAG.getConstant(CC1, MVT::i8));
10035       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10036     }
10037     // Handle all other FP comparisons here.
10038     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10039                        DAG.getConstant(SSECC, MVT::i8));
10040   }
10041
10042   // Break 256-bit integer vector compare into smaller ones.
10043   if (VT.is256BitVector() && !Subtarget->hasInt256())
10044     return Lower256IntVSETCC(Op, DAG);
10045
10046   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10047   EVT OpVT = Op1.getValueType();
10048   if (Subtarget->hasAVX512()) {
10049     if (Op1.getValueType().is512BitVector() ||
10050         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10051       return LowerIntVSETCC_AVX512(Op, DAG);
10052
10053     // In AVX-512 architecture setcc returns mask with i1 elements,
10054     // But there is no compare instruction for i8 and i16 elements.
10055     // We are not talking about 512-bit operands in this case, these
10056     // types are illegal.
10057     if (MaskResult &&
10058         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10059          OpVT.getVectorElementType().getSizeInBits() >= 8))
10060       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10061                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10062   }
10063
10064   // We are handling one of the integer comparisons here.  Since SSE only has
10065   // GT and EQ comparisons for integer, swapping operands and multiple
10066   // operations may be required for some comparisons.
10067   unsigned Opc;
10068   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10069
10070   switch (SetCCOpcode) {
10071   default: llvm_unreachable("Unexpected SETCC condition");
10072   case ISD::SETNE:  Invert = true;
10073   case ISD::SETEQ:  Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
10074   case ISD::SETLT:  Swap = true;
10075   case ISD::SETGT:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
10076   case ISD::SETGE:  Swap = true;
10077   case ISD::SETLE:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10078                     Invert = true; break;
10079   case ISD::SETULT: Swap = true;
10080   case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10081                     FlipSigns = true; break;
10082   case ISD::SETUGE: Swap = true;
10083   case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10084                     FlipSigns = true; Invert = true; break;
10085   }
10086
10087   // Special case: Use min/max operations for SETULE/SETUGE
10088   MVT VET = VT.getVectorElementType();
10089   bool hasMinMax =
10090        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10091     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10092
10093   if (hasMinMax) {
10094     switch (SetCCOpcode) {
10095     default: break;
10096     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10097     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10098     }
10099
10100     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10101   }
10102
10103   if (Swap)
10104     std::swap(Op0, Op1);
10105
10106   // Check that the operation in question is available (most are plain SSE2,
10107   // but PCMPGTQ and PCMPEQQ have different requirements).
10108   if (VT == MVT::v2i64) {
10109     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10110       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10111
10112       // First cast everything to the right type.
10113       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10114       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10115
10116       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10117       // bits of the inputs before performing those operations. The lower
10118       // compare is always unsigned.
10119       SDValue SB;
10120       if (FlipSigns) {
10121         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10122       } else {
10123         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10124         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10125         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10126                          Sign, Zero, Sign, Zero);
10127       }
10128       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10129       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10130
10131       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10132       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10133       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10134
10135       // Create masks for only the low parts/high parts of the 64 bit integers.
10136       static const int MaskHi[] = { 1, 1, 3, 3 };
10137       static const int MaskLo[] = { 0, 0, 2, 2 };
10138       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10139       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10140       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10141
10142       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10143       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10144
10145       if (Invert)
10146         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10147
10148       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10149     }
10150
10151     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10152       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10153       // pcmpeqd + pshufd + pand.
10154       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10155
10156       // First cast everything to the right type.
10157       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10158       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10159
10160       // Do the compare.
10161       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10162
10163       // Make sure the lower and upper halves are both all-ones.
10164       static const int Mask[] = { 1, 0, 3, 2 };
10165       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10166       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10167
10168       if (Invert)
10169         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10170
10171       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10172     }
10173   }
10174
10175   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10176   // bits of the inputs before performing those operations.
10177   if (FlipSigns) {
10178     EVT EltVT = VT.getVectorElementType();
10179     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10180     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10181     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10182   }
10183
10184   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10185
10186   // If the logical-not of the result is required, perform that now.
10187   if (Invert)
10188     Result = DAG.getNOT(dl, Result, VT);
10189
10190   if (MinMax)
10191     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10192
10193   return Result;
10194 }
10195
10196 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10197
10198   MVT VT = Op.getSimpleValueType();
10199
10200   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10201
10202   assert((VT == MVT::i8 || (Subtarget->hasAVX512() && VT == MVT::i1))
10203          && "SetCC type must be 8-bit or 1-bit integer");
10204   SDValue Op0 = Op.getOperand(0);
10205   SDValue Op1 = Op.getOperand(1);
10206   SDLoc dl(Op);
10207   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10208
10209   // Optimize to BT if possible.
10210   // Lower (X & (1 << N)) == 0 to BT(X, N).
10211   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10212   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10213   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10214       Op1.getOpcode() == ISD::Constant &&
10215       cast<ConstantSDNode>(Op1)->isNullValue() &&
10216       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10217     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10218     if (NewSetCC.getNode())
10219       return NewSetCC;
10220   }
10221
10222   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10223   // these.
10224   if (Op1.getOpcode() == ISD::Constant &&
10225       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10226        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10227       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10228
10229     // If the input is a setcc, then reuse the input setcc or use a new one with
10230     // the inverted condition.
10231     if (Op0.getOpcode() == X86ISD::SETCC) {
10232       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10233       bool Invert = (CC == ISD::SETNE) ^
10234         cast<ConstantSDNode>(Op1)->isNullValue();
10235       if (!Invert) return Op0;
10236
10237       CCode = X86::GetOppositeBranchCondition(CCode);
10238       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10239                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
10240     }
10241   }
10242
10243   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10244   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10245   if (X86CC == X86::COND_INVALID)
10246     return SDValue();
10247
10248   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10249   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10250   MVT SetCCVT = Subtarget->hasAVX512() ? MVT::i1 : MVT::i8;
10251   return DAG.getNode(X86ISD::SETCC, dl, SetCCVT,
10252                       DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10253 }
10254
10255 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10256 static bool isX86LogicalCmp(SDValue Op) {
10257   unsigned Opc = Op.getNode()->getOpcode();
10258   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10259       Opc == X86ISD::SAHF)
10260     return true;
10261   if (Op.getResNo() == 1 &&
10262       (Opc == X86ISD::ADD ||
10263        Opc == X86ISD::SUB ||
10264        Opc == X86ISD::ADC ||
10265        Opc == X86ISD::SBB ||
10266        Opc == X86ISD::SMUL ||
10267        Opc == X86ISD::UMUL ||
10268        Opc == X86ISD::INC ||
10269        Opc == X86ISD::DEC ||
10270        Opc == X86ISD::OR ||
10271        Opc == X86ISD::XOR ||
10272        Opc == X86ISD::AND))
10273     return true;
10274
10275   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10276     return true;
10277
10278   return false;
10279 }
10280
10281 static bool isZero(SDValue V) {
10282   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10283   return C && C->isNullValue();
10284 }
10285
10286 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10287   if (V.getOpcode() != ISD::TRUNCATE)
10288     return false;
10289
10290   SDValue VOp0 = V.getOperand(0);
10291   unsigned InBits = VOp0.getValueSizeInBits();
10292   unsigned Bits = V.getValueSizeInBits();
10293   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10294 }
10295
10296 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10297   bool addTest = true;
10298   SDValue Cond  = Op.getOperand(0);
10299   SDValue Op1 = Op.getOperand(1);
10300   SDValue Op2 = Op.getOperand(2);
10301   SDLoc DL(Op);
10302   EVT VT = Op1.getValueType();
10303   SDValue CC;
10304
10305   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10306   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10307   // sequence later on.
10308   if (Cond.getOpcode() == ISD::SETCC &&
10309       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10310        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10311       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10312     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10313     int SSECC = translateX86FSETCC(
10314         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10315
10316     if (SSECC != 8) {
10317       if (Subtarget->hasAVX512()) {
10318         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10319                                   DAG.getConstant(SSECC, MVT::i8));
10320         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10321       }
10322       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10323                                 DAG.getConstant(SSECC, MVT::i8));
10324       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10325       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10326       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10327     }
10328   }
10329
10330   if (Cond.getOpcode() == ISD::SETCC) {
10331     SDValue NewCond = LowerSETCC(Cond, DAG);
10332     if (NewCond.getNode())
10333       Cond = NewCond;
10334   }
10335
10336   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10337   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10338   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10339   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10340   if (Cond.getOpcode() == X86ISD::SETCC &&
10341       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10342       isZero(Cond.getOperand(1).getOperand(1))) {
10343     SDValue Cmp = Cond.getOperand(1);
10344
10345     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10346
10347     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10348         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10349       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10350
10351       SDValue CmpOp0 = Cmp.getOperand(0);
10352       // Apply further optimizations for special cases
10353       // (select (x != 0), -1, 0) -> neg & sbb
10354       // (select (x == 0), 0, -1) -> neg & sbb
10355       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10356         if (YC->isNullValue() &&
10357             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10358           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10359           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10360                                     DAG.getConstant(0, CmpOp0.getValueType()),
10361                                     CmpOp0);
10362           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10363                                     DAG.getConstant(X86::COND_B, MVT::i8),
10364                                     SDValue(Neg.getNode(), 1));
10365           return Res;
10366         }
10367
10368       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10369                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10370       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10371
10372       SDValue Res =   // Res = 0 or -1.
10373         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10374                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10375
10376       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10377         Res = DAG.getNOT(DL, Res, Res.getValueType());
10378
10379       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10380       if (N2C == 0 || !N2C->isNullValue())
10381         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10382       return Res;
10383     }
10384   }
10385
10386   // Look past (and (setcc_carry (cmp ...)), 1).
10387   if (Cond.getOpcode() == ISD::AND &&
10388       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10389     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10390     if (C && C->getAPIntValue() == 1)
10391       Cond = Cond.getOperand(0);
10392   }
10393
10394   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10395   // setting operand in place of the X86ISD::SETCC.
10396   unsigned CondOpcode = Cond.getOpcode();
10397   if (CondOpcode == X86ISD::SETCC ||
10398       CondOpcode == X86ISD::SETCC_CARRY) {
10399     CC = Cond.getOperand(0);
10400
10401     SDValue Cmp = Cond.getOperand(1);
10402     unsigned Opc = Cmp.getOpcode();
10403     MVT VT = Op.getSimpleValueType();
10404
10405     bool IllegalFPCMov = false;
10406     if (VT.isFloatingPoint() && !VT.isVector() &&
10407         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10408       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10409
10410     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10411         Opc == X86ISD::BT) { // FIXME
10412       Cond = Cmp;
10413       addTest = false;
10414     }
10415   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10416              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10417              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10418               Cond.getOperand(0).getValueType() != MVT::i8)) {
10419     SDValue LHS = Cond.getOperand(0);
10420     SDValue RHS = Cond.getOperand(1);
10421     unsigned X86Opcode;
10422     unsigned X86Cond;
10423     SDVTList VTs;
10424     switch (CondOpcode) {
10425     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10426     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10427     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10428     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10429     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10430     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10431     default: llvm_unreachable("unexpected overflowing operator");
10432     }
10433     if (CondOpcode == ISD::UMULO)
10434       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10435                           MVT::i32);
10436     else
10437       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10438
10439     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10440
10441     if (CondOpcode == ISD::UMULO)
10442       Cond = X86Op.getValue(2);
10443     else
10444       Cond = X86Op.getValue(1);
10445
10446     CC = DAG.getConstant(X86Cond, MVT::i8);
10447     addTest = false;
10448   }
10449
10450   if (addTest) {
10451     // Look pass the truncate if the high bits are known zero.
10452     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10453         Cond = Cond.getOperand(0);
10454
10455     // We know the result of AND is compared against zero. Try to match
10456     // it to BT.
10457     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10458       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10459       if (NewSetCC.getNode()) {
10460         CC = NewSetCC.getOperand(0);
10461         Cond = NewSetCC.getOperand(1);
10462         addTest = false;
10463       }
10464     }
10465   }
10466
10467   if (addTest) {
10468     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10469     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10470   }
10471
10472   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10473   // a <  b ?  0 : -1 -> RES = setcc_carry
10474   // a >= b ? -1 :  0 -> RES = setcc_carry
10475   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10476   if (Cond.getOpcode() == X86ISD::SUB) {
10477     Cond = ConvertCmpIfNecessary(Cond, DAG);
10478     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10479
10480     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10481         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10482       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10483                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10484       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10485         return DAG.getNOT(DL, Res, Res.getValueType());
10486       return Res;
10487     }
10488   }
10489
10490   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10491   // widen the cmov and push the truncate through. This avoids introducing a new
10492   // branch during isel and doesn't add any extensions.
10493   if (Op.getValueType() == MVT::i8 &&
10494       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10495     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10496     if (T1.getValueType() == T2.getValueType() &&
10497         // Blacklist CopyFromReg to avoid partial register stalls.
10498         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10499       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10500       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10501       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10502     }
10503   }
10504
10505   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10506   // condition is true.
10507   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10508   SDValue Ops[] = { Op2, Op1, CC, Cond };
10509   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10510 }
10511
10512 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10513   MVT VT = Op->getSimpleValueType(0);
10514   SDValue In = Op->getOperand(0);
10515   MVT InVT = In.getSimpleValueType();
10516   SDLoc dl(Op);
10517
10518   unsigned int NumElts = VT.getVectorNumElements();
10519   if (NumElts != 8 && NumElts != 16)
10520     return SDValue();
10521
10522   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10523     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10524
10525   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10526   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10527
10528   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10529   Constant *C = ConstantInt::get(*DAG.getContext(),
10530     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10531
10532   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10533   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10534   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10535                           MachinePointerInfo::getConstantPool(),
10536                           false, false, false, Alignment);
10537   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10538   if (VT.is512BitVector())
10539     return Brcst;
10540   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10541 }
10542
10543 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10544                                 SelectionDAG &DAG) {
10545   MVT VT = Op->getSimpleValueType(0);
10546   SDValue In = Op->getOperand(0);
10547   MVT InVT = In.getSimpleValueType();
10548   SDLoc dl(Op);
10549
10550   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10551     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10552
10553   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10554       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10555       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10556     return SDValue();
10557
10558   if (Subtarget->hasInt256())
10559     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10560
10561   // Optimize vectors in AVX mode
10562   // Sign extend  v8i16 to v8i32 and
10563   //              v4i32 to v4i64
10564   //
10565   // Divide input vector into two parts
10566   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10567   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10568   // concat the vectors to original VT
10569
10570   unsigned NumElems = InVT.getVectorNumElements();
10571   SDValue Undef = DAG.getUNDEF(InVT);
10572
10573   SmallVector<int,8> ShufMask1(NumElems, -1);
10574   for (unsigned i = 0; i != NumElems/2; ++i)
10575     ShufMask1[i] = i;
10576
10577   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10578
10579   SmallVector<int,8> ShufMask2(NumElems, -1);
10580   for (unsigned i = 0; i != NumElems/2; ++i)
10581     ShufMask2[i] = i + NumElems/2;
10582
10583   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10584
10585   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10586                                 VT.getVectorNumElements()/2);
10587
10588   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10589   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10590
10591   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10592 }
10593
10594 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10595 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10596 // from the AND / OR.
10597 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10598   Opc = Op.getOpcode();
10599   if (Opc != ISD::OR && Opc != ISD::AND)
10600     return false;
10601   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10602           Op.getOperand(0).hasOneUse() &&
10603           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10604           Op.getOperand(1).hasOneUse());
10605 }
10606
10607 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10608 // 1 and that the SETCC node has a single use.
10609 static bool isXor1OfSetCC(SDValue Op) {
10610   if (Op.getOpcode() != ISD::XOR)
10611     return false;
10612   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10613   if (N1C && N1C->getAPIntValue() == 1) {
10614     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10615       Op.getOperand(0).hasOneUse();
10616   }
10617   return false;
10618 }
10619
10620 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10621   bool addTest = true;
10622   SDValue Chain = Op.getOperand(0);
10623   SDValue Cond  = Op.getOperand(1);
10624   SDValue Dest  = Op.getOperand(2);
10625   SDLoc dl(Op);
10626   SDValue CC;
10627   bool Inverted = false;
10628
10629   if (Cond.getOpcode() == ISD::SETCC) {
10630     // Check for setcc([su]{add,sub,mul}o == 0).
10631     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10632         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10633         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10634         Cond.getOperand(0).getResNo() == 1 &&
10635         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10636          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10637          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10638          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10639          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10640          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10641       Inverted = true;
10642       Cond = Cond.getOperand(0);
10643     } else {
10644       SDValue NewCond = LowerSETCC(Cond, DAG);
10645       if (NewCond.getNode())
10646         Cond = NewCond;
10647     }
10648   }
10649 #if 0
10650   // FIXME: LowerXALUO doesn't handle these!!
10651   else if (Cond.getOpcode() == X86ISD::ADD  ||
10652            Cond.getOpcode() == X86ISD::SUB  ||
10653            Cond.getOpcode() == X86ISD::SMUL ||
10654            Cond.getOpcode() == X86ISD::UMUL)
10655     Cond = LowerXALUO(Cond, DAG);
10656 #endif
10657
10658   // Look pass (and (setcc_carry (cmp ...)), 1).
10659   if (Cond.getOpcode() == ISD::AND &&
10660       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10661     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10662     if (C && C->getAPIntValue() == 1)
10663       Cond = Cond.getOperand(0);
10664   }
10665
10666   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10667   // setting operand in place of the X86ISD::SETCC.
10668   unsigned CondOpcode = Cond.getOpcode();
10669   if (CondOpcode == X86ISD::SETCC ||
10670       CondOpcode == X86ISD::SETCC_CARRY) {
10671     CC = Cond.getOperand(0);
10672
10673     SDValue Cmp = Cond.getOperand(1);
10674     unsigned Opc = Cmp.getOpcode();
10675     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10676     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10677       Cond = Cmp;
10678       addTest = false;
10679     } else {
10680       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10681       default: break;
10682       case X86::COND_O:
10683       case X86::COND_B:
10684         // These can only come from an arithmetic instruction with overflow,
10685         // e.g. SADDO, UADDO.
10686         Cond = Cond.getNode()->getOperand(1);
10687         addTest = false;
10688         break;
10689       }
10690     }
10691   }
10692   CondOpcode = Cond.getOpcode();
10693   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10694       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10695       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10696        Cond.getOperand(0).getValueType() != MVT::i8)) {
10697     SDValue LHS = Cond.getOperand(0);
10698     SDValue RHS = Cond.getOperand(1);
10699     unsigned X86Opcode;
10700     unsigned X86Cond;
10701     SDVTList VTs;
10702     switch (CondOpcode) {
10703     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10704     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10705     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10706     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10707     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10708     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10709     default: llvm_unreachable("unexpected overflowing operator");
10710     }
10711     if (Inverted)
10712       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10713     if (CondOpcode == ISD::UMULO)
10714       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10715                           MVT::i32);
10716     else
10717       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10718
10719     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10720
10721     if (CondOpcode == ISD::UMULO)
10722       Cond = X86Op.getValue(2);
10723     else
10724       Cond = X86Op.getValue(1);
10725
10726     CC = DAG.getConstant(X86Cond, MVT::i8);
10727     addTest = false;
10728   } else {
10729     unsigned CondOpc;
10730     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10731       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10732       if (CondOpc == ISD::OR) {
10733         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10734         // two branches instead of an explicit OR instruction with a
10735         // separate test.
10736         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10737             isX86LogicalCmp(Cmp)) {
10738           CC = Cond.getOperand(0).getOperand(0);
10739           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10740                               Chain, Dest, CC, Cmp);
10741           CC = Cond.getOperand(1).getOperand(0);
10742           Cond = Cmp;
10743           addTest = false;
10744         }
10745       } else { // ISD::AND
10746         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10747         // two branches instead of an explicit AND instruction with a
10748         // separate test. However, we only do this if this block doesn't
10749         // have a fall-through edge, because this requires an explicit
10750         // jmp when the condition is false.
10751         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10752             isX86LogicalCmp(Cmp) &&
10753             Op.getNode()->hasOneUse()) {
10754           X86::CondCode CCode =
10755             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10756           CCode = X86::GetOppositeBranchCondition(CCode);
10757           CC = DAG.getConstant(CCode, MVT::i8);
10758           SDNode *User = *Op.getNode()->use_begin();
10759           // Look for an unconditional branch following this conditional branch.
10760           // We need this because we need to reverse the successors in order
10761           // to implement FCMP_OEQ.
10762           if (User->getOpcode() == ISD::BR) {
10763             SDValue FalseBB = User->getOperand(1);
10764             SDNode *NewBR =
10765               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10766             assert(NewBR == User);
10767             (void)NewBR;
10768             Dest = FalseBB;
10769
10770             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10771                                 Chain, Dest, CC, Cmp);
10772             X86::CondCode CCode =
10773               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10774             CCode = X86::GetOppositeBranchCondition(CCode);
10775             CC = DAG.getConstant(CCode, MVT::i8);
10776             Cond = Cmp;
10777             addTest = false;
10778           }
10779         }
10780       }
10781     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10782       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10783       // It should be transformed during dag combiner except when the condition
10784       // is set by a arithmetics with overflow node.
10785       X86::CondCode CCode =
10786         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10787       CCode = X86::GetOppositeBranchCondition(CCode);
10788       CC = DAG.getConstant(CCode, MVT::i8);
10789       Cond = Cond.getOperand(0).getOperand(1);
10790       addTest = false;
10791     } else if (Cond.getOpcode() == ISD::SETCC &&
10792                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10793       // For FCMP_OEQ, we can emit
10794       // two branches instead of an explicit AND instruction with a
10795       // separate test. However, we only do this if this block doesn't
10796       // have a fall-through edge, because this requires an explicit
10797       // jmp when the condition is false.
10798       if (Op.getNode()->hasOneUse()) {
10799         SDNode *User = *Op.getNode()->use_begin();
10800         // Look for an unconditional branch following this conditional branch.
10801         // We need this because we need to reverse the successors in order
10802         // to implement FCMP_OEQ.
10803         if (User->getOpcode() == ISD::BR) {
10804           SDValue FalseBB = User->getOperand(1);
10805           SDNode *NewBR =
10806             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10807           assert(NewBR == User);
10808           (void)NewBR;
10809           Dest = FalseBB;
10810
10811           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10812                                     Cond.getOperand(0), Cond.getOperand(1));
10813           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10814           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10815           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10816                               Chain, Dest, CC, Cmp);
10817           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10818           Cond = Cmp;
10819           addTest = false;
10820         }
10821       }
10822     } else if (Cond.getOpcode() == ISD::SETCC &&
10823                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10824       // For FCMP_UNE, we can emit
10825       // two branches instead of an explicit AND instruction with a
10826       // separate test. However, we only do this if this block doesn't
10827       // have a fall-through edge, because this requires an explicit
10828       // jmp when the condition is false.
10829       if (Op.getNode()->hasOneUse()) {
10830         SDNode *User = *Op.getNode()->use_begin();
10831         // Look for an unconditional branch following this conditional branch.
10832         // We need this because we need to reverse the successors in order
10833         // to implement FCMP_UNE.
10834         if (User->getOpcode() == ISD::BR) {
10835           SDValue FalseBB = User->getOperand(1);
10836           SDNode *NewBR =
10837             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10838           assert(NewBR == User);
10839           (void)NewBR;
10840
10841           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10842                                     Cond.getOperand(0), Cond.getOperand(1));
10843           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10844           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10845           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10846                               Chain, Dest, CC, Cmp);
10847           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10848           Cond = Cmp;
10849           addTest = false;
10850           Dest = FalseBB;
10851         }
10852       }
10853     }
10854   }
10855
10856   if (addTest) {
10857     // Look pass the truncate if the high bits are known zero.
10858     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10859         Cond = Cond.getOperand(0);
10860
10861     // We know the result of AND is compared against zero. Try to match
10862     // it to BT.
10863     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10864       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10865       if (NewSetCC.getNode()) {
10866         CC = NewSetCC.getOperand(0);
10867         Cond = NewSetCC.getOperand(1);
10868         addTest = false;
10869       }
10870     }
10871   }
10872
10873   if (addTest) {
10874     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10875     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10876   }
10877   Cond = ConvertCmpIfNecessary(Cond, DAG);
10878   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10879                      Chain, Dest, CC, Cond);
10880 }
10881
10882 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10883 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10884 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10885 // that the guard pages used by the OS virtual memory manager are allocated in
10886 // correct sequence.
10887 SDValue
10888 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10889                                            SelectionDAG &DAG) const {
10890   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10891           getTargetMachine().Options.EnableSegmentedStacks) &&
10892          "This should be used only on Windows targets or when segmented stacks "
10893          "are being used");
10894   assert(!Subtarget->isTargetMacho() && "Not implemented");
10895   SDLoc dl(Op);
10896
10897   // Get the inputs.
10898   SDValue Chain = Op.getOperand(0);
10899   SDValue Size  = Op.getOperand(1);
10900   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10901   EVT VT = Op.getNode()->getValueType(0);
10902
10903   bool Is64Bit = Subtarget->is64Bit();
10904   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10905
10906   if (getTargetMachine().Options.EnableSegmentedStacks) {
10907     MachineFunction &MF = DAG.getMachineFunction();
10908     MachineRegisterInfo &MRI = MF.getRegInfo();
10909
10910     if (Is64Bit) {
10911       // The 64 bit implementation of segmented stacks needs to clobber both r10
10912       // r11. This makes it impossible to use it along with nested parameters.
10913       const Function *F = MF.getFunction();
10914
10915       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10916            I != E; ++I)
10917         if (I->hasNestAttr())
10918           report_fatal_error("Cannot use segmented stacks with functions that "
10919                              "have nested arguments.");
10920     }
10921
10922     const TargetRegisterClass *AddrRegClass =
10923       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10924     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10925     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10926     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10927                                 DAG.getRegister(Vreg, SPTy));
10928     SDValue Ops1[2] = { Value, Chain };
10929     return DAG.getMergeValues(Ops1, 2, dl);
10930   } else {
10931     SDValue Flag;
10932     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10933
10934     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10935     Flag = Chain.getValue(1);
10936     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10937
10938     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10939
10940     const X86RegisterInfo *RegInfo =
10941       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10942     unsigned SPReg = RegInfo->getStackRegister();
10943     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
10944     Chain = SP.getValue(1);
10945
10946     if (Align) {
10947       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10948                        DAG.getConstant(-(uint64_t)Align, VT));
10949       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
10950     }
10951
10952     SDValue Ops1[2] = { SP, Chain };
10953     return DAG.getMergeValues(Ops1, 2, dl);
10954   }
10955 }
10956
10957 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10958   MachineFunction &MF = DAG.getMachineFunction();
10959   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10960
10961   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10962   SDLoc DL(Op);
10963
10964   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10965     // vastart just stores the address of the VarArgsFrameIndex slot into the
10966     // memory location argument.
10967     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10968                                    getPointerTy());
10969     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10970                         MachinePointerInfo(SV), false, false, 0);
10971   }
10972
10973   // __va_list_tag:
10974   //   gp_offset         (0 - 6 * 8)
10975   //   fp_offset         (48 - 48 + 8 * 16)
10976   //   overflow_arg_area (point to parameters coming in memory).
10977   //   reg_save_area
10978   SmallVector<SDValue, 8> MemOps;
10979   SDValue FIN = Op.getOperand(1);
10980   // Store gp_offset
10981   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10982                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10983                                                MVT::i32),
10984                                FIN, MachinePointerInfo(SV), false, false, 0);
10985   MemOps.push_back(Store);
10986
10987   // Store fp_offset
10988   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10989                     FIN, DAG.getIntPtrConstant(4));
10990   Store = DAG.getStore(Op.getOperand(0), DL,
10991                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10992                                        MVT::i32),
10993                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10994   MemOps.push_back(Store);
10995
10996   // Store ptr to overflow_arg_area
10997   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10998                     FIN, DAG.getIntPtrConstant(4));
10999   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11000                                     getPointerTy());
11001   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11002                        MachinePointerInfo(SV, 8),
11003                        false, false, 0);
11004   MemOps.push_back(Store);
11005
11006   // Store ptr to reg_save_area.
11007   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11008                     FIN, DAG.getIntPtrConstant(8));
11009   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11010                                     getPointerTy());
11011   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11012                        MachinePointerInfo(SV, 16), false, false, 0);
11013   MemOps.push_back(Store);
11014   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11015                      &MemOps[0], MemOps.size());
11016 }
11017
11018 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11019   assert(Subtarget->is64Bit() &&
11020          "LowerVAARG only handles 64-bit va_arg!");
11021   assert((Subtarget->isTargetLinux() ||
11022           Subtarget->isTargetDarwin()) &&
11023           "Unhandled target in LowerVAARG");
11024   assert(Op.getNode()->getNumOperands() == 4);
11025   SDValue Chain = Op.getOperand(0);
11026   SDValue SrcPtr = Op.getOperand(1);
11027   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11028   unsigned Align = Op.getConstantOperandVal(3);
11029   SDLoc dl(Op);
11030
11031   EVT ArgVT = Op.getNode()->getValueType(0);
11032   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11033   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11034   uint8_t ArgMode;
11035
11036   // Decide which area this value should be read from.
11037   // TODO: Implement the AMD64 ABI in its entirety. This simple
11038   // selection mechanism works only for the basic types.
11039   if (ArgVT == MVT::f80) {
11040     llvm_unreachable("va_arg for f80 not yet implemented");
11041   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11042     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11043   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11044     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11045   } else {
11046     llvm_unreachable("Unhandled argument type in LowerVAARG");
11047   }
11048
11049   if (ArgMode == 2) {
11050     // Sanity Check: Make sure using fp_offset makes sense.
11051     assert(!getTargetMachine().Options.UseSoftFloat &&
11052            !(DAG.getMachineFunction()
11053                 .getFunction()->getAttributes()
11054                 .hasAttribute(AttributeSet::FunctionIndex,
11055                               Attribute::NoImplicitFloat)) &&
11056            Subtarget->hasSSE1());
11057   }
11058
11059   // Insert VAARG_64 node into the DAG
11060   // VAARG_64 returns two values: Variable Argument Address, Chain
11061   SmallVector<SDValue, 11> InstOps;
11062   InstOps.push_back(Chain);
11063   InstOps.push_back(SrcPtr);
11064   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11065   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11066   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11067   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11068   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11069                                           VTs, &InstOps[0], InstOps.size(),
11070                                           MVT::i64,
11071                                           MachinePointerInfo(SV),
11072                                           /*Align=*/0,
11073                                           /*Volatile=*/false,
11074                                           /*ReadMem=*/true,
11075                                           /*WriteMem=*/true);
11076   Chain = VAARG.getValue(1);
11077
11078   // Load the next argument and return it
11079   return DAG.getLoad(ArgVT, dl,
11080                      Chain,
11081                      VAARG,
11082                      MachinePointerInfo(),
11083                      false, false, false, 0);
11084 }
11085
11086 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11087                            SelectionDAG &DAG) {
11088   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11089   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11090   SDValue Chain = Op.getOperand(0);
11091   SDValue DstPtr = Op.getOperand(1);
11092   SDValue SrcPtr = Op.getOperand(2);
11093   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11094   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11095   SDLoc DL(Op);
11096
11097   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11098                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11099                        false,
11100                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11101 }
11102
11103 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11104 // amount is a constant. Takes immediate version of shift as input.
11105 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, EVT VT,
11106                                           SDValue SrcOp, uint64_t ShiftAmt,
11107                                           SelectionDAG &DAG) {
11108
11109   // Check for ShiftAmt >= element width
11110   if (ShiftAmt >= VT.getVectorElementType().getSizeInBits()) {
11111     if (Opc == X86ISD::VSRAI)
11112       ShiftAmt = VT.getVectorElementType().getSizeInBits() - 1;
11113     else
11114       return DAG.getConstant(0, VT);
11115   }
11116
11117   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11118          && "Unknown target vector shift-by-constant node");
11119
11120   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11121 }
11122
11123 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11124 // may or may not be a constant. Takes immediate version of shift as input.
11125 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
11126                                    SDValue SrcOp, SDValue ShAmt,
11127                                    SelectionDAG &DAG) {
11128   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11129
11130   // Catch shift-by-constant.
11131   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11132     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11133                                       CShAmt->getZExtValue(), DAG);
11134
11135   // Change opcode to non-immediate version
11136   switch (Opc) {
11137     default: llvm_unreachable("Unknown target vector shift node");
11138     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11139     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11140     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11141   }
11142
11143   // Need to build a vector containing shift amount
11144   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11145   SDValue ShOps[4];
11146   ShOps[0] = ShAmt;
11147   ShOps[1] = DAG.getConstant(0, MVT::i32);
11148   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11149   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11150
11151   // The return type has to be a 128-bit type with the same element
11152   // type as the input type.
11153   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11154   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11155
11156   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11157   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11158 }
11159
11160 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11161   SDLoc dl(Op);
11162   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11163   switch (IntNo) {
11164   default: return SDValue();    // Don't custom lower most intrinsics.
11165   // Comparison intrinsics.
11166   case Intrinsic::x86_sse_comieq_ss:
11167   case Intrinsic::x86_sse_comilt_ss:
11168   case Intrinsic::x86_sse_comile_ss:
11169   case Intrinsic::x86_sse_comigt_ss:
11170   case Intrinsic::x86_sse_comige_ss:
11171   case Intrinsic::x86_sse_comineq_ss:
11172   case Intrinsic::x86_sse_ucomieq_ss:
11173   case Intrinsic::x86_sse_ucomilt_ss:
11174   case Intrinsic::x86_sse_ucomile_ss:
11175   case Intrinsic::x86_sse_ucomigt_ss:
11176   case Intrinsic::x86_sse_ucomige_ss:
11177   case Intrinsic::x86_sse_ucomineq_ss:
11178   case Intrinsic::x86_sse2_comieq_sd:
11179   case Intrinsic::x86_sse2_comilt_sd:
11180   case Intrinsic::x86_sse2_comile_sd:
11181   case Intrinsic::x86_sse2_comigt_sd:
11182   case Intrinsic::x86_sse2_comige_sd:
11183   case Intrinsic::x86_sse2_comineq_sd:
11184   case Intrinsic::x86_sse2_ucomieq_sd:
11185   case Intrinsic::x86_sse2_ucomilt_sd:
11186   case Intrinsic::x86_sse2_ucomile_sd:
11187   case Intrinsic::x86_sse2_ucomigt_sd:
11188   case Intrinsic::x86_sse2_ucomige_sd:
11189   case Intrinsic::x86_sse2_ucomineq_sd: {
11190     unsigned Opc;
11191     ISD::CondCode CC;
11192     switch (IntNo) {
11193     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11194     case Intrinsic::x86_sse_comieq_ss:
11195     case Intrinsic::x86_sse2_comieq_sd:
11196       Opc = X86ISD::COMI;
11197       CC = ISD::SETEQ;
11198       break;
11199     case Intrinsic::x86_sse_comilt_ss:
11200     case Intrinsic::x86_sse2_comilt_sd:
11201       Opc = X86ISD::COMI;
11202       CC = ISD::SETLT;
11203       break;
11204     case Intrinsic::x86_sse_comile_ss:
11205     case Intrinsic::x86_sse2_comile_sd:
11206       Opc = X86ISD::COMI;
11207       CC = ISD::SETLE;
11208       break;
11209     case Intrinsic::x86_sse_comigt_ss:
11210     case Intrinsic::x86_sse2_comigt_sd:
11211       Opc = X86ISD::COMI;
11212       CC = ISD::SETGT;
11213       break;
11214     case Intrinsic::x86_sse_comige_ss:
11215     case Intrinsic::x86_sse2_comige_sd:
11216       Opc = X86ISD::COMI;
11217       CC = ISD::SETGE;
11218       break;
11219     case Intrinsic::x86_sse_comineq_ss:
11220     case Intrinsic::x86_sse2_comineq_sd:
11221       Opc = X86ISD::COMI;
11222       CC = ISD::SETNE;
11223       break;
11224     case Intrinsic::x86_sse_ucomieq_ss:
11225     case Intrinsic::x86_sse2_ucomieq_sd:
11226       Opc = X86ISD::UCOMI;
11227       CC = ISD::SETEQ;
11228       break;
11229     case Intrinsic::x86_sse_ucomilt_ss:
11230     case Intrinsic::x86_sse2_ucomilt_sd:
11231       Opc = X86ISD::UCOMI;
11232       CC = ISD::SETLT;
11233       break;
11234     case Intrinsic::x86_sse_ucomile_ss:
11235     case Intrinsic::x86_sse2_ucomile_sd:
11236       Opc = X86ISD::UCOMI;
11237       CC = ISD::SETLE;
11238       break;
11239     case Intrinsic::x86_sse_ucomigt_ss:
11240     case Intrinsic::x86_sse2_ucomigt_sd:
11241       Opc = X86ISD::UCOMI;
11242       CC = ISD::SETGT;
11243       break;
11244     case Intrinsic::x86_sse_ucomige_ss:
11245     case Intrinsic::x86_sse2_ucomige_sd:
11246       Opc = X86ISD::UCOMI;
11247       CC = ISD::SETGE;
11248       break;
11249     case Intrinsic::x86_sse_ucomineq_ss:
11250     case Intrinsic::x86_sse2_ucomineq_sd:
11251       Opc = X86ISD::UCOMI;
11252       CC = ISD::SETNE;
11253       break;
11254     }
11255
11256     SDValue LHS = Op.getOperand(1);
11257     SDValue RHS = Op.getOperand(2);
11258     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11259     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11260     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11261     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11262                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11263     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11264   }
11265
11266   // Arithmetic intrinsics.
11267   case Intrinsic::x86_sse2_pmulu_dq:
11268   case Intrinsic::x86_avx2_pmulu_dq:
11269     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11270                        Op.getOperand(1), Op.getOperand(2));
11271
11272   // SSE2/AVX2 sub with unsigned saturation intrinsics
11273   case Intrinsic::x86_sse2_psubus_b:
11274   case Intrinsic::x86_sse2_psubus_w:
11275   case Intrinsic::x86_avx2_psubus_b:
11276   case Intrinsic::x86_avx2_psubus_w:
11277     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11278                        Op.getOperand(1), Op.getOperand(2));
11279
11280   // SSE3/AVX horizontal add/sub intrinsics
11281   case Intrinsic::x86_sse3_hadd_ps:
11282   case Intrinsic::x86_sse3_hadd_pd:
11283   case Intrinsic::x86_avx_hadd_ps_256:
11284   case Intrinsic::x86_avx_hadd_pd_256:
11285   case Intrinsic::x86_sse3_hsub_ps:
11286   case Intrinsic::x86_sse3_hsub_pd:
11287   case Intrinsic::x86_avx_hsub_ps_256:
11288   case Intrinsic::x86_avx_hsub_pd_256:
11289   case Intrinsic::x86_ssse3_phadd_w_128:
11290   case Intrinsic::x86_ssse3_phadd_d_128:
11291   case Intrinsic::x86_avx2_phadd_w:
11292   case Intrinsic::x86_avx2_phadd_d:
11293   case Intrinsic::x86_ssse3_phsub_w_128:
11294   case Intrinsic::x86_ssse3_phsub_d_128:
11295   case Intrinsic::x86_avx2_phsub_w:
11296   case Intrinsic::x86_avx2_phsub_d: {
11297     unsigned Opcode;
11298     switch (IntNo) {
11299     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11300     case Intrinsic::x86_sse3_hadd_ps:
11301     case Intrinsic::x86_sse3_hadd_pd:
11302     case Intrinsic::x86_avx_hadd_ps_256:
11303     case Intrinsic::x86_avx_hadd_pd_256:
11304       Opcode = X86ISD::FHADD;
11305       break;
11306     case Intrinsic::x86_sse3_hsub_ps:
11307     case Intrinsic::x86_sse3_hsub_pd:
11308     case Intrinsic::x86_avx_hsub_ps_256:
11309     case Intrinsic::x86_avx_hsub_pd_256:
11310       Opcode = X86ISD::FHSUB;
11311       break;
11312     case Intrinsic::x86_ssse3_phadd_w_128:
11313     case Intrinsic::x86_ssse3_phadd_d_128:
11314     case Intrinsic::x86_avx2_phadd_w:
11315     case Intrinsic::x86_avx2_phadd_d:
11316       Opcode = X86ISD::HADD;
11317       break;
11318     case Intrinsic::x86_ssse3_phsub_w_128:
11319     case Intrinsic::x86_ssse3_phsub_d_128:
11320     case Intrinsic::x86_avx2_phsub_w:
11321     case Intrinsic::x86_avx2_phsub_d:
11322       Opcode = X86ISD::HSUB;
11323       break;
11324     }
11325     return DAG.getNode(Opcode, dl, Op.getValueType(),
11326                        Op.getOperand(1), Op.getOperand(2));
11327   }
11328
11329   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11330   case Intrinsic::x86_sse2_pmaxu_b:
11331   case Intrinsic::x86_sse41_pmaxuw:
11332   case Intrinsic::x86_sse41_pmaxud:
11333   case Intrinsic::x86_avx2_pmaxu_b:
11334   case Intrinsic::x86_avx2_pmaxu_w:
11335   case Intrinsic::x86_avx2_pmaxu_d:
11336   case Intrinsic::x86_avx512_pmaxu_d:
11337   case Intrinsic::x86_avx512_pmaxu_q:
11338   case Intrinsic::x86_sse2_pminu_b:
11339   case Intrinsic::x86_sse41_pminuw:
11340   case Intrinsic::x86_sse41_pminud:
11341   case Intrinsic::x86_avx2_pminu_b:
11342   case Intrinsic::x86_avx2_pminu_w:
11343   case Intrinsic::x86_avx2_pminu_d:
11344   case Intrinsic::x86_avx512_pminu_d:
11345   case Intrinsic::x86_avx512_pminu_q:
11346   case Intrinsic::x86_sse41_pmaxsb:
11347   case Intrinsic::x86_sse2_pmaxs_w:
11348   case Intrinsic::x86_sse41_pmaxsd:
11349   case Intrinsic::x86_avx2_pmaxs_b:
11350   case Intrinsic::x86_avx2_pmaxs_w:
11351   case Intrinsic::x86_avx2_pmaxs_d:
11352   case Intrinsic::x86_avx512_pmaxs_d:
11353   case Intrinsic::x86_avx512_pmaxs_q:
11354   case Intrinsic::x86_sse41_pminsb:
11355   case Intrinsic::x86_sse2_pmins_w:
11356   case Intrinsic::x86_sse41_pminsd:
11357   case Intrinsic::x86_avx2_pmins_b:
11358   case Intrinsic::x86_avx2_pmins_w:
11359   case Intrinsic::x86_avx2_pmins_d:
11360   case Intrinsic::x86_avx512_pmins_d:
11361   case Intrinsic::x86_avx512_pmins_q: {
11362     unsigned Opcode;
11363     switch (IntNo) {
11364     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11365     case Intrinsic::x86_sse2_pmaxu_b:
11366     case Intrinsic::x86_sse41_pmaxuw:
11367     case Intrinsic::x86_sse41_pmaxud:
11368     case Intrinsic::x86_avx2_pmaxu_b:
11369     case Intrinsic::x86_avx2_pmaxu_w:
11370     case Intrinsic::x86_avx2_pmaxu_d:
11371     case Intrinsic::x86_avx512_pmaxu_d:
11372     case Intrinsic::x86_avx512_pmaxu_q:
11373       Opcode = X86ISD::UMAX;
11374       break;
11375     case Intrinsic::x86_sse2_pminu_b:
11376     case Intrinsic::x86_sse41_pminuw:
11377     case Intrinsic::x86_sse41_pminud:
11378     case Intrinsic::x86_avx2_pminu_b:
11379     case Intrinsic::x86_avx2_pminu_w:
11380     case Intrinsic::x86_avx2_pminu_d:
11381     case Intrinsic::x86_avx512_pminu_d:
11382     case Intrinsic::x86_avx512_pminu_q:
11383       Opcode = X86ISD::UMIN;
11384       break;
11385     case Intrinsic::x86_sse41_pmaxsb:
11386     case Intrinsic::x86_sse2_pmaxs_w:
11387     case Intrinsic::x86_sse41_pmaxsd:
11388     case Intrinsic::x86_avx2_pmaxs_b:
11389     case Intrinsic::x86_avx2_pmaxs_w:
11390     case Intrinsic::x86_avx2_pmaxs_d:
11391     case Intrinsic::x86_avx512_pmaxs_d:
11392     case Intrinsic::x86_avx512_pmaxs_q:
11393       Opcode = X86ISD::SMAX;
11394       break;
11395     case Intrinsic::x86_sse41_pminsb:
11396     case Intrinsic::x86_sse2_pmins_w:
11397     case Intrinsic::x86_sse41_pminsd:
11398     case Intrinsic::x86_avx2_pmins_b:
11399     case Intrinsic::x86_avx2_pmins_w:
11400     case Intrinsic::x86_avx2_pmins_d:
11401     case Intrinsic::x86_avx512_pmins_d:
11402     case Intrinsic::x86_avx512_pmins_q:
11403       Opcode = X86ISD::SMIN;
11404       break;
11405     }
11406     return DAG.getNode(Opcode, dl, Op.getValueType(),
11407                        Op.getOperand(1), Op.getOperand(2));
11408   }
11409
11410   // SSE/SSE2/AVX floating point max/min intrinsics.
11411   case Intrinsic::x86_sse_max_ps:
11412   case Intrinsic::x86_sse2_max_pd:
11413   case Intrinsic::x86_avx_max_ps_256:
11414   case Intrinsic::x86_avx_max_pd_256:
11415   case Intrinsic::x86_avx512_max_ps_512:
11416   case Intrinsic::x86_avx512_max_pd_512:
11417   case Intrinsic::x86_sse_min_ps:
11418   case Intrinsic::x86_sse2_min_pd:
11419   case Intrinsic::x86_avx_min_ps_256:
11420   case Intrinsic::x86_avx_min_pd_256:
11421   case Intrinsic::x86_avx512_min_ps_512:
11422   case Intrinsic::x86_avx512_min_pd_512:  {
11423     unsigned Opcode;
11424     switch (IntNo) {
11425     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11426     case Intrinsic::x86_sse_max_ps:
11427     case Intrinsic::x86_sse2_max_pd:
11428     case Intrinsic::x86_avx_max_ps_256:
11429     case Intrinsic::x86_avx_max_pd_256:
11430     case Intrinsic::x86_avx512_max_ps_512:
11431     case Intrinsic::x86_avx512_max_pd_512:
11432       Opcode = X86ISD::FMAX;
11433       break;
11434     case Intrinsic::x86_sse_min_ps:
11435     case Intrinsic::x86_sse2_min_pd:
11436     case Intrinsic::x86_avx_min_ps_256:
11437     case Intrinsic::x86_avx_min_pd_256:
11438     case Intrinsic::x86_avx512_min_ps_512:
11439     case Intrinsic::x86_avx512_min_pd_512:
11440       Opcode = X86ISD::FMIN;
11441       break;
11442     }
11443     return DAG.getNode(Opcode, dl, Op.getValueType(),
11444                        Op.getOperand(1), Op.getOperand(2));
11445   }
11446
11447   // AVX2 variable shift intrinsics
11448   case Intrinsic::x86_avx2_psllv_d:
11449   case Intrinsic::x86_avx2_psllv_q:
11450   case Intrinsic::x86_avx2_psllv_d_256:
11451   case Intrinsic::x86_avx2_psllv_q_256:
11452   case Intrinsic::x86_avx2_psrlv_d:
11453   case Intrinsic::x86_avx2_psrlv_q:
11454   case Intrinsic::x86_avx2_psrlv_d_256:
11455   case Intrinsic::x86_avx2_psrlv_q_256:
11456   case Intrinsic::x86_avx2_psrav_d:
11457   case Intrinsic::x86_avx2_psrav_d_256: {
11458     unsigned Opcode;
11459     switch (IntNo) {
11460     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11461     case Intrinsic::x86_avx2_psllv_d:
11462     case Intrinsic::x86_avx2_psllv_q:
11463     case Intrinsic::x86_avx2_psllv_d_256:
11464     case Intrinsic::x86_avx2_psllv_q_256:
11465       Opcode = ISD::SHL;
11466       break;
11467     case Intrinsic::x86_avx2_psrlv_d:
11468     case Intrinsic::x86_avx2_psrlv_q:
11469     case Intrinsic::x86_avx2_psrlv_d_256:
11470     case Intrinsic::x86_avx2_psrlv_q_256:
11471       Opcode = ISD::SRL;
11472       break;
11473     case Intrinsic::x86_avx2_psrav_d:
11474     case Intrinsic::x86_avx2_psrav_d_256:
11475       Opcode = ISD::SRA;
11476       break;
11477     }
11478     return DAG.getNode(Opcode, dl, Op.getValueType(),
11479                        Op.getOperand(1), Op.getOperand(2));
11480   }
11481
11482   case Intrinsic::x86_ssse3_pshuf_b_128:
11483   case Intrinsic::x86_avx2_pshuf_b:
11484     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11485                        Op.getOperand(1), Op.getOperand(2));
11486
11487   case Intrinsic::x86_ssse3_psign_b_128:
11488   case Intrinsic::x86_ssse3_psign_w_128:
11489   case Intrinsic::x86_ssse3_psign_d_128:
11490   case Intrinsic::x86_avx2_psign_b:
11491   case Intrinsic::x86_avx2_psign_w:
11492   case Intrinsic::x86_avx2_psign_d:
11493     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11494                        Op.getOperand(1), Op.getOperand(2));
11495
11496   case Intrinsic::x86_sse41_insertps:
11497     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11498                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11499
11500   case Intrinsic::x86_avx_vperm2f128_ps_256:
11501   case Intrinsic::x86_avx_vperm2f128_pd_256:
11502   case Intrinsic::x86_avx_vperm2f128_si_256:
11503   case Intrinsic::x86_avx2_vperm2i128:
11504     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11505                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11506
11507   case Intrinsic::x86_avx2_permd:
11508   case Intrinsic::x86_avx2_permps:
11509     // Operands intentionally swapped. Mask is last operand to intrinsic,
11510     // but second operand for node/instruction.
11511     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11512                        Op.getOperand(2), Op.getOperand(1));
11513
11514   case Intrinsic::x86_sse_sqrt_ps:
11515   case Intrinsic::x86_sse2_sqrt_pd:
11516   case Intrinsic::x86_avx_sqrt_ps_256:
11517   case Intrinsic::x86_avx_sqrt_pd_256:
11518     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11519
11520   // ptest and testp intrinsics. The intrinsic these come from are designed to
11521   // return an integer value, not just an instruction so lower it to the ptest
11522   // or testp pattern and a setcc for the result.
11523   case Intrinsic::x86_sse41_ptestz:
11524   case Intrinsic::x86_sse41_ptestc:
11525   case Intrinsic::x86_sse41_ptestnzc:
11526   case Intrinsic::x86_avx_ptestz_256:
11527   case Intrinsic::x86_avx_ptestc_256:
11528   case Intrinsic::x86_avx_ptestnzc_256:
11529   case Intrinsic::x86_avx_vtestz_ps:
11530   case Intrinsic::x86_avx_vtestc_ps:
11531   case Intrinsic::x86_avx_vtestnzc_ps:
11532   case Intrinsic::x86_avx_vtestz_pd:
11533   case Intrinsic::x86_avx_vtestc_pd:
11534   case Intrinsic::x86_avx_vtestnzc_pd:
11535   case Intrinsic::x86_avx_vtestz_ps_256:
11536   case Intrinsic::x86_avx_vtestc_ps_256:
11537   case Intrinsic::x86_avx_vtestnzc_ps_256:
11538   case Intrinsic::x86_avx_vtestz_pd_256:
11539   case Intrinsic::x86_avx_vtestc_pd_256:
11540   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11541     bool IsTestPacked = false;
11542     unsigned X86CC;
11543     switch (IntNo) {
11544     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11545     case Intrinsic::x86_avx_vtestz_ps:
11546     case Intrinsic::x86_avx_vtestz_pd:
11547     case Intrinsic::x86_avx_vtestz_ps_256:
11548     case Intrinsic::x86_avx_vtestz_pd_256:
11549       IsTestPacked = true; // Fallthrough
11550     case Intrinsic::x86_sse41_ptestz:
11551     case Intrinsic::x86_avx_ptestz_256:
11552       // ZF = 1
11553       X86CC = X86::COND_E;
11554       break;
11555     case Intrinsic::x86_avx_vtestc_ps:
11556     case Intrinsic::x86_avx_vtestc_pd:
11557     case Intrinsic::x86_avx_vtestc_ps_256:
11558     case Intrinsic::x86_avx_vtestc_pd_256:
11559       IsTestPacked = true; // Fallthrough
11560     case Intrinsic::x86_sse41_ptestc:
11561     case Intrinsic::x86_avx_ptestc_256:
11562       // CF = 1
11563       X86CC = X86::COND_B;
11564       break;
11565     case Intrinsic::x86_avx_vtestnzc_ps:
11566     case Intrinsic::x86_avx_vtestnzc_pd:
11567     case Intrinsic::x86_avx_vtestnzc_ps_256:
11568     case Intrinsic::x86_avx_vtestnzc_pd_256:
11569       IsTestPacked = true; // Fallthrough
11570     case Intrinsic::x86_sse41_ptestnzc:
11571     case Intrinsic::x86_avx_ptestnzc_256:
11572       // ZF and CF = 0
11573       X86CC = X86::COND_A;
11574       break;
11575     }
11576
11577     SDValue LHS = Op.getOperand(1);
11578     SDValue RHS = Op.getOperand(2);
11579     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11580     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11581     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11582     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11583     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11584   }
11585   case Intrinsic::x86_avx512_kortestz_w:
11586   case Intrinsic::x86_avx512_kortestc_w: {
11587     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11588     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11589     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11590     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11591     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11592     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11593     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11594   }
11595
11596   // SSE/AVX shift intrinsics
11597   case Intrinsic::x86_sse2_psll_w:
11598   case Intrinsic::x86_sse2_psll_d:
11599   case Intrinsic::x86_sse2_psll_q:
11600   case Intrinsic::x86_avx2_psll_w:
11601   case Intrinsic::x86_avx2_psll_d:
11602   case Intrinsic::x86_avx2_psll_q:
11603   case Intrinsic::x86_sse2_psrl_w:
11604   case Intrinsic::x86_sse2_psrl_d:
11605   case Intrinsic::x86_sse2_psrl_q:
11606   case Intrinsic::x86_avx2_psrl_w:
11607   case Intrinsic::x86_avx2_psrl_d:
11608   case Intrinsic::x86_avx2_psrl_q:
11609   case Intrinsic::x86_sse2_psra_w:
11610   case Intrinsic::x86_sse2_psra_d:
11611   case Intrinsic::x86_avx2_psra_w:
11612   case Intrinsic::x86_avx2_psra_d: {
11613     unsigned Opcode;
11614     switch (IntNo) {
11615     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11616     case Intrinsic::x86_sse2_psll_w:
11617     case Intrinsic::x86_sse2_psll_d:
11618     case Intrinsic::x86_sse2_psll_q:
11619     case Intrinsic::x86_avx2_psll_w:
11620     case Intrinsic::x86_avx2_psll_d:
11621     case Intrinsic::x86_avx2_psll_q:
11622       Opcode = X86ISD::VSHL;
11623       break;
11624     case Intrinsic::x86_sse2_psrl_w:
11625     case Intrinsic::x86_sse2_psrl_d:
11626     case Intrinsic::x86_sse2_psrl_q:
11627     case Intrinsic::x86_avx2_psrl_w:
11628     case Intrinsic::x86_avx2_psrl_d:
11629     case Intrinsic::x86_avx2_psrl_q:
11630       Opcode = X86ISD::VSRL;
11631       break;
11632     case Intrinsic::x86_sse2_psra_w:
11633     case Intrinsic::x86_sse2_psra_d:
11634     case Intrinsic::x86_avx2_psra_w:
11635     case Intrinsic::x86_avx2_psra_d:
11636       Opcode = X86ISD::VSRA;
11637       break;
11638     }
11639     return DAG.getNode(Opcode, dl, Op.getValueType(),
11640                        Op.getOperand(1), Op.getOperand(2));
11641   }
11642
11643   // SSE/AVX immediate shift intrinsics
11644   case Intrinsic::x86_sse2_pslli_w:
11645   case Intrinsic::x86_sse2_pslli_d:
11646   case Intrinsic::x86_sse2_pslli_q:
11647   case Intrinsic::x86_avx2_pslli_w:
11648   case Intrinsic::x86_avx2_pslli_d:
11649   case Intrinsic::x86_avx2_pslli_q:
11650   case Intrinsic::x86_sse2_psrli_w:
11651   case Intrinsic::x86_sse2_psrli_d:
11652   case Intrinsic::x86_sse2_psrli_q:
11653   case Intrinsic::x86_avx2_psrli_w:
11654   case Intrinsic::x86_avx2_psrli_d:
11655   case Intrinsic::x86_avx2_psrli_q:
11656   case Intrinsic::x86_sse2_psrai_w:
11657   case Intrinsic::x86_sse2_psrai_d:
11658   case Intrinsic::x86_avx2_psrai_w:
11659   case Intrinsic::x86_avx2_psrai_d: {
11660     unsigned Opcode;
11661     switch (IntNo) {
11662     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11663     case Intrinsic::x86_sse2_pslli_w:
11664     case Intrinsic::x86_sse2_pslli_d:
11665     case Intrinsic::x86_sse2_pslli_q:
11666     case Intrinsic::x86_avx2_pslli_w:
11667     case Intrinsic::x86_avx2_pslli_d:
11668     case Intrinsic::x86_avx2_pslli_q:
11669       Opcode = X86ISD::VSHLI;
11670       break;
11671     case Intrinsic::x86_sse2_psrli_w:
11672     case Intrinsic::x86_sse2_psrli_d:
11673     case Intrinsic::x86_sse2_psrli_q:
11674     case Intrinsic::x86_avx2_psrli_w:
11675     case Intrinsic::x86_avx2_psrli_d:
11676     case Intrinsic::x86_avx2_psrli_q:
11677       Opcode = X86ISD::VSRLI;
11678       break;
11679     case Intrinsic::x86_sse2_psrai_w:
11680     case Intrinsic::x86_sse2_psrai_d:
11681     case Intrinsic::x86_avx2_psrai_w:
11682     case Intrinsic::x86_avx2_psrai_d:
11683       Opcode = X86ISD::VSRAI;
11684       break;
11685     }
11686     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11687                                Op.getOperand(1), Op.getOperand(2), DAG);
11688   }
11689
11690   case Intrinsic::x86_sse42_pcmpistria128:
11691   case Intrinsic::x86_sse42_pcmpestria128:
11692   case Intrinsic::x86_sse42_pcmpistric128:
11693   case Intrinsic::x86_sse42_pcmpestric128:
11694   case Intrinsic::x86_sse42_pcmpistrio128:
11695   case Intrinsic::x86_sse42_pcmpestrio128:
11696   case Intrinsic::x86_sse42_pcmpistris128:
11697   case Intrinsic::x86_sse42_pcmpestris128:
11698   case Intrinsic::x86_sse42_pcmpistriz128:
11699   case Intrinsic::x86_sse42_pcmpestriz128: {
11700     unsigned Opcode;
11701     unsigned X86CC;
11702     switch (IntNo) {
11703     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11704     case Intrinsic::x86_sse42_pcmpistria128:
11705       Opcode = X86ISD::PCMPISTRI;
11706       X86CC = X86::COND_A;
11707       break;
11708     case Intrinsic::x86_sse42_pcmpestria128:
11709       Opcode = X86ISD::PCMPESTRI;
11710       X86CC = X86::COND_A;
11711       break;
11712     case Intrinsic::x86_sse42_pcmpistric128:
11713       Opcode = X86ISD::PCMPISTRI;
11714       X86CC = X86::COND_B;
11715       break;
11716     case Intrinsic::x86_sse42_pcmpestric128:
11717       Opcode = X86ISD::PCMPESTRI;
11718       X86CC = X86::COND_B;
11719       break;
11720     case Intrinsic::x86_sse42_pcmpistrio128:
11721       Opcode = X86ISD::PCMPISTRI;
11722       X86CC = X86::COND_O;
11723       break;
11724     case Intrinsic::x86_sse42_pcmpestrio128:
11725       Opcode = X86ISD::PCMPESTRI;
11726       X86CC = X86::COND_O;
11727       break;
11728     case Intrinsic::x86_sse42_pcmpistris128:
11729       Opcode = X86ISD::PCMPISTRI;
11730       X86CC = X86::COND_S;
11731       break;
11732     case Intrinsic::x86_sse42_pcmpestris128:
11733       Opcode = X86ISD::PCMPESTRI;
11734       X86CC = X86::COND_S;
11735       break;
11736     case Intrinsic::x86_sse42_pcmpistriz128:
11737       Opcode = X86ISD::PCMPISTRI;
11738       X86CC = X86::COND_E;
11739       break;
11740     case Intrinsic::x86_sse42_pcmpestriz128:
11741       Opcode = X86ISD::PCMPESTRI;
11742       X86CC = X86::COND_E;
11743       break;
11744     }
11745     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11746     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11747     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11748     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11749                                 DAG.getConstant(X86CC, MVT::i8),
11750                                 SDValue(PCMP.getNode(), 1));
11751     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11752   }
11753
11754   case Intrinsic::x86_sse42_pcmpistri128:
11755   case Intrinsic::x86_sse42_pcmpestri128: {
11756     unsigned Opcode;
11757     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11758       Opcode = X86ISD::PCMPISTRI;
11759     else
11760       Opcode = X86ISD::PCMPESTRI;
11761
11762     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11763     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11764     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11765   }
11766   case Intrinsic::x86_fma_vfmadd_ps:
11767   case Intrinsic::x86_fma_vfmadd_pd:
11768   case Intrinsic::x86_fma_vfmsub_ps:
11769   case Intrinsic::x86_fma_vfmsub_pd:
11770   case Intrinsic::x86_fma_vfnmadd_ps:
11771   case Intrinsic::x86_fma_vfnmadd_pd:
11772   case Intrinsic::x86_fma_vfnmsub_ps:
11773   case Intrinsic::x86_fma_vfnmsub_pd:
11774   case Intrinsic::x86_fma_vfmaddsub_ps:
11775   case Intrinsic::x86_fma_vfmaddsub_pd:
11776   case Intrinsic::x86_fma_vfmsubadd_ps:
11777   case Intrinsic::x86_fma_vfmsubadd_pd:
11778   case Intrinsic::x86_fma_vfmadd_ps_256:
11779   case Intrinsic::x86_fma_vfmadd_pd_256:
11780   case Intrinsic::x86_fma_vfmsub_ps_256:
11781   case Intrinsic::x86_fma_vfmsub_pd_256:
11782   case Intrinsic::x86_fma_vfnmadd_ps_256:
11783   case Intrinsic::x86_fma_vfnmadd_pd_256:
11784   case Intrinsic::x86_fma_vfnmsub_ps_256:
11785   case Intrinsic::x86_fma_vfnmsub_pd_256:
11786   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11787   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11788   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11789   case Intrinsic::x86_fma_vfmsubadd_pd_256:
11790   case Intrinsic::x86_fma_vfmadd_ps_512:
11791   case Intrinsic::x86_fma_vfmadd_pd_512:
11792   case Intrinsic::x86_fma_vfmsub_ps_512:
11793   case Intrinsic::x86_fma_vfmsub_pd_512:
11794   case Intrinsic::x86_fma_vfnmadd_ps_512:
11795   case Intrinsic::x86_fma_vfnmadd_pd_512:
11796   case Intrinsic::x86_fma_vfnmsub_ps_512:
11797   case Intrinsic::x86_fma_vfnmsub_pd_512:
11798   case Intrinsic::x86_fma_vfmaddsub_ps_512:
11799   case Intrinsic::x86_fma_vfmaddsub_pd_512:
11800   case Intrinsic::x86_fma_vfmsubadd_ps_512:
11801   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11802     unsigned Opc;
11803     switch (IntNo) {
11804     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11805     case Intrinsic::x86_fma_vfmadd_ps:
11806     case Intrinsic::x86_fma_vfmadd_pd:
11807     case Intrinsic::x86_fma_vfmadd_ps_256:
11808     case Intrinsic::x86_fma_vfmadd_pd_256:
11809     case Intrinsic::x86_fma_vfmadd_ps_512:
11810     case Intrinsic::x86_fma_vfmadd_pd_512:
11811       Opc = X86ISD::FMADD;
11812       break;
11813     case Intrinsic::x86_fma_vfmsub_ps:
11814     case Intrinsic::x86_fma_vfmsub_pd:
11815     case Intrinsic::x86_fma_vfmsub_ps_256:
11816     case Intrinsic::x86_fma_vfmsub_pd_256:
11817     case Intrinsic::x86_fma_vfmsub_ps_512:
11818     case Intrinsic::x86_fma_vfmsub_pd_512:
11819       Opc = X86ISD::FMSUB;
11820       break;
11821     case Intrinsic::x86_fma_vfnmadd_ps:
11822     case Intrinsic::x86_fma_vfnmadd_pd:
11823     case Intrinsic::x86_fma_vfnmadd_ps_256:
11824     case Intrinsic::x86_fma_vfnmadd_pd_256:
11825     case Intrinsic::x86_fma_vfnmadd_ps_512:
11826     case Intrinsic::x86_fma_vfnmadd_pd_512:
11827       Opc = X86ISD::FNMADD;
11828       break;
11829     case Intrinsic::x86_fma_vfnmsub_ps:
11830     case Intrinsic::x86_fma_vfnmsub_pd:
11831     case Intrinsic::x86_fma_vfnmsub_ps_256:
11832     case Intrinsic::x86_fma_vfnmsub_pd_256:
11833     case Intrinsic::x86_fma_vfnmsub_ps_512:
11834     case Intrinsic::x86_fma_vfnmsub_pd_512:
11835       Opc = X86ISD::FNMSUB;
11836       break;
11837     case Intrinsic::x86_fma_vfmaddsub_ps:
11838     case Intrinsic::x86_fma_vfmaddsub_pd:
11839     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11840     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11841     case Intrinsic::x86_fma_vfmaddsub_ps_512:
11842     case Intrinsic::x86_fma_vfmaddsub_pd_512:
11843       Opc = X86ISD::FMADDSUB;
11844       break;
11845     case Intrinsic::x86_fma_vfmsubadd_ps:
11846     case Intrinsic::x86_fma_vfmsubadd_pd:
11847     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11848     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11849     case Intrinsic::x86_fma_vfmsubadd_ps_512:
11850     case Intrinsic::x86_fma_vfmsubadd_pd_512:
11851       Opc = X86ISD::FMSUBADD;
11852       break;
11853     }
11854
11855     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11856                        Op.getOperand(2), Op.getOperand(3));
11857   }
11858   }
11859 }
11860
11861 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11862                              SDValue Base, SDValue Index,
11863                              SDValue ScaleOp, SDValue Chain,
11864                              const X86Subtarget * Subtarget) {
11865   SDLoc dl(Op);
11866   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11867   assert(C && "Invalid scale type");
11868   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11869   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11870   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11871                                 Index.getValueType().getVectorNumElements());
11872   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11873   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11874   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11875   SDValue Segment = DAG.getRegister(0, MVT::i32);
11876   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11877   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11878   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11879   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11880 }
11881
11882 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11883                               SDValue Src, SDValue Mask, SDValue Base,
11884                               SDValue Index, SDValue ScaleOp, SDValue Chain,
11885                               const X86Subtarget * Subtarget) {
11886   SDLoc dl(Op);
11887   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11888   assert(C && "Invalid scale type");
11889   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11890   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11891                                 Index.getValueType().getVectorNumElements());
11892   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11893   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11894   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11895   SDValue Segment = DAG.getRegister(0, MVT::i32);
11896   if (Src.getOpcode() == ISD::UNDEF)
11897     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11898   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11899   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11900   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11901   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11902 }
11903
11904 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11905                               SDValue Src, SDValue Base, SDValue Index,
11906                               SDValue ScaleOp, SDValue Chain) {
11907   SDLoc dl(Op);
11908   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11909   assert(C && "Invalid scale type");
11910   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11911   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11912   SDValue Segment = DAG.getRegister(0, MVT::i32);
11913   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11914                                 Index.getValueType().getVectorNumElements());
11915   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11916   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11917   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11918   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11919   return SDValue(Res, 1);
11920 }
11921
11922 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11923                                SDValue Src, SDValue Mask, SDValue Base,
11924                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
11925   SDLoc dl(Op);
11926   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11927   assert(C && "Invalid scale type");
11928   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11929   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11930   SDValue Segment = DAG.getRegister(0, MVT::i32);
11931   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11932                                 Index.getValueType().getVectorNumElements());
11933   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11934   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11935   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11936   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11937   return SDValue(Res, 1);
11938 }
11939
11940 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
11941                                       SelectionDAG &DAG) {
11942   SDLoc dl(Op);
11943   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11944   switch (IntNo) {
11945   default: return SDValue();    // Don't custom lower most intrinsics.
11946
11947   // RDRAND/RDSEED intrinsics.
11948   case Intrinsic::x86_rdrand_16:
11949   case Intrinsic::x86_rdrand_32:
11950   case Intrinsic::x86_rdrand_64:
11951   case Intrinsic::x86_rdseed_16:
11952   case Intrinsic::x86_rdseed_32:
11953   case Intrinsic::x86_rdseed_64: {
11954     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11955                        IntNo == Intrinsic::x86_rdseed_32 ||
11956                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11957                                                             X86ISD::RDRAND;
11958     // Emit the node with the right value type.
11959     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11960     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11961
11962     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11963     // Otherwise return the value from Rand, which is always 0, casted to i32.
11964     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11965                       DAG.getConstant(1, Op->getValueType(1)),
11966                       DAG.getConstant(X86::COND_B, MVT::i32),
11967                       SDValue(Result.getNode(), 1) };
11968     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11969                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11970                                   Ops, array_lengthof(Ops));
11971
11972     // Return { result, isValid, chain }.
11973     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11974                        SDValue(Result.getNode(), 2));
11975   }
11976   //int_gather(index, base, scale);
11977   case Intrinsic::x86_avx512_gather_qpd_512:
11978   case Intrinsic::x86_avx512_gather_qps_512:
11979   case Intrinsic::x86_avx512_gather_dpd_512:
11980   case Intrinsic::x86_avx512_gather_qpi_512:
11981   case Intrinsic::x86_avx512_gather_qpq_512:
11982   case Intrinsic::x86_avx512_gather_dpq_512:
11983   case Intrinsic::x86_avx512_gather_dps_512:
11984   case Intrinsic::x86_avx512_gather_dpi_512: {
11985     unsigned Opc;
11986     switch (IntNo) {
11987       default: llvm_unreachable("Unexpected intrinsic!");
11988       case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
11989       case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
11990       case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
11991       case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
11992       case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
11993       case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
11994       case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
11995       case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
11996     }
11997     SDValue Chain = Op.getOperand(0);
11998     SDValue Index = Op.getOperand(2);
11999     SDValue Base  = Op.getOperand(3);
12000     SDValue Scale = Op.getOperand(4);
12001     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12002   }
12003   //int_gather_mask(v1, mask, index, base, scale);
12004   case Intrinsic::x86_avx512_gather_qps_mask_512:
12005   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12006   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12007   case Intrinsic::x86_avx512_gather_dps_mask_512:
12008   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12009   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12010   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12011   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12012     unsigned Opc;
12013     switch (IntNo) {
12014       default: llvm_unreachable("Unexpected intrinsic!");
12015       case Intrinsic::x86_avx512_gather_qps_mask_512:
12016         Opc = X86::VGATHERQPSZrm; break;
12017       case Intrinsic::x86_avx512_gather_qpd_mask_512:
12018         Opc = X86::VGATHERQPDZrm; break;
12019       case Intrinsic::x86_avx512_gather_dpd_mask_512:
12020         Opc = X86::VGATHERDPDZrm; break;
12021       case Intrinsic::x86_avx512_gather_dps_mask_512:
12022         Opc = X86::VGATHERDPSZrm; break;
12023       case Intrinsic::x86_avx512_gather_qpi_mask_512:
12024         Opc = X86::VPGATHERQDZrm; break;
12025       case Intrinsic::x86_avx512_gather_qpq_mask_512:
12026         Opc = X86::VPGATHERQQZrm; break;
12027       case Intrinsic::x86_avx512_gather_dpi_mask_512:
12028         Opc = X86::VPGATHERDDZrm; break;
12029       case Intrinsic::x86_avx512_gather_dpq_mask_512:
12030         Opc = X86::VPGATHERDQZrm; break;
12031     }
12032     SDValue Chain = Op.getOperand(0);
12033     SDValue Src   = Op.getOperand(2);
12034     SDValue Mask  = Op.getOperand(3);
12035     SDValue Index = Op.getOperand(4);
12036     SDValue Base  = Op.getOperand(5);
12037     SDValue Scale = Op.getOperand(6);
12038     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12039                           Subtarget);
12040   }
12041   //int_scatter(base, index, v1, scale);
12042   case Intrinsic::x86_avx512_scatter_qpd_512:
12043   case Intrinsic::x86_avx512_scatter_qps_512:
12044   case Intrinsic::x86_avx512_scatter_dpd_512:
12045   case Intrinsic::x86_avx512_scatter_qpi_512:
12046   case Intrinsic::x86_avx512_scatter_qpq_512:
12047   case Intrinsic::x86_avx512_scatter_dpq_512:
12048   case Intrinsic::x86_avx512_scatter_dps_512:
12049   case Intrinsic::x86_avx512_scatter_dpi_512: {
12050     unsigned Opc;
12051     switch (IntNo) {
12052       default: llvm_unreachable("Unexpected intrinsic!");
12053       case Intrinsic::x86_avx512_scatter_qpd_512:
12054         Opc = X86::VSCATTERQPDZmr; break;
12055       case Intrinsic::x86_avx512_scatter_qps_512:
12056         Opc = X86::VSCATTERQPSZmr; break;
12057       case Intrinsic::x86_avx512_scatter_dpd_512:
12058         Opc = X86::VSCATTERDPDZmr; break;
12059       case Intrinsic::x86_avx512_scatter_dps_512:
12060         Opc = X86::VSCATTERDPSZmr; break;
12061       case Intrinsic::x86_avx512_scatter_qpi_512:
12062         Opc = X86::VPSCATTERQDZmr; break;
12063       case Intrinsic::x86_avx512_scatter_qpq_512:
12064         Opc = X86::VPSCATTERQQZmr; break;
12065       case Intrinsic::x86_avx512_scatter_dpq_512:
12066         Opc = X86::VPSCATTERDQZmr; break;
12067       case Intrinsic::x86_avx512_scatter_dpi_512:
12068         Opc = X86::VPSCATTERDDZmr; break;
12069     }
12070     SDValue Chain = Op.getOperand(0);
12071     SDValue Base  = Op.getOperand(2);
12072     SDValue Index = Op.getOperand(3);
12073     SDValue Src   = Op.getOperand(4);
12074     SDValue Scale = Op.getOperand(5);
12075     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12076   }
12077   //int_scatter_mask(base, mask, index, v1, scale);
12078   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12079   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12080   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12081   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12082   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12083   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12084   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12085   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12086     unsigned Opc;
12087     switch (IntNo) {
12088       default: llvm_unreachable("Unexpected intrinsic!");
12089       case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12090         Opc = X86::VSCATTERQPDZmr; break;
12091       case Intrinsic::x86_avx512_scatter_qps_mask_512:
12092         Opc = X86::VSCATTERQPSZmr; break;
12093       case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12094         Opc = X86::VSCATTERDPDZmr; break;
12095       case Intrinsic::x86_avx512_scatter_dps_mask_512:
12096         Opc = X86::VSCATTERDPSZmr; break;
12097       case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12098         Opc = X86::VPSCATTERQDZmr; break;
12099       case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12100         Opc = X86::VPSCATTERQQZmr; break;
12101       case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12102         Opc = X86::VPSCATTERDQZmr; break;
12103       case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12104         Opc = X86::VPSCATTERDDZmr; break;
12105     }
12106     SDValue Chain = Op.getOperand(0);
12107     SDValue Base  = Op.getOperand(2);
12108     SDValue Mask  = Op.getOperand(3);
12109     SDValue Index = Op.getOperand(4);
12110     SDValue Src   = Op.getOperand(5);
12111     SDValue Scale = Op.getOperand(6);
12112     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12113   }
12114   // XTEST intrinsics.
12115   case Intrinsic::x86_xtest: {
12116     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12117     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12118     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12119                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12120                                 InTrans);
12121     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12122     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12123                        Ret, SDValue(InTrans.getNode(), 1));
12124   }
12125   }
12126 }
12127
12128 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12129                                            SelectionDAG &DAG) const {
12130   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12131   MFI->setReturnAddressIsTaken(true);
12132
12133   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12134   SDLoc dl(Op);
12135   EVT PtrVT = getPointerTy();
12136
12137   if (Depth > 0) {
12138     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12139     const X86RegisterInfo *RegInfo =
12140       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12141     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12142     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12143                        DAG.getNode(ISD::ADD, dl, PtrVT,
12144                                    FrameAddr, Offset),
12145                        MachinePointerInfo(), false, false, false, 0);
12146   }
12147
12148   // Just load the return address.
12149   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12150   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12151                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12152 }
12153
12154 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12155   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12156   MFI->setFrameAddressIsTaken(true);
12157
12158   EVT VT = Op.getValueType();
12159   SDLoc dl(Op);  // FIXME probably not meaningful
12160   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12161   const X86RegisterInfo *RegInfo =
12162     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12163   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12164   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12165           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12166          "Invalid Frame Register!");
12167   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12168   while (Depth--)
12169     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12170                             MachinePointerInfo(),
12171                             false, false, false, 0);
12172   return FrameAddr;
12173 }
12174
12175 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12176                                                      SelectionDAG &DAG) const {
12177   const X86RegisterInfo *RegInfo =
12178     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12179   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12180 }
12181
12182 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12183   SDValue Chain     = Op.getOperand(0);
12184   SDValue Offset    = Op.getOperand(1);
12185   SDValue Handler   = Op.getOperand(2);
12186   SDLoc dl      (Op);
12187
12188   EVT PtrVT = getPointerTy();
12189   const X86RegisterInfo *RegInfo =
12190     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12191   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12192   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12193           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12194          "Invalid Frame Register!");
12195   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12196   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12197
12198   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12199                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12200   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12201   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12202                        false, false, 0);
12203   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12204
12205   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12206                      DAG.getRegister(StoreAddrReg, PtrVT));
12207 }
12208
12209 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12210                                                SelectionDAG &DAG) const {
12211   SDLoc DL(Op);
12212   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12213                      DAG.getVTList(MVT::i32, MVT::Other),
12214                      Op.getOperand(0), Op.getOperand(1));
12215 }
12216
12217 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12218                                                 SelectionDAG &DAG) const {
12219   SDLoc DL(Op);
12220   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12221                      Op.getOperand(0), Op.getOperand(1));
12222 }
12223
12224 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12225   return Op.getOperand(0);
12226 }
12227
12228 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12229                                                 SelectionDAG &DAG) const {
12230   SDValue Root = Op.getOperand(0);
12231   SDValue Trmp = Op.getOperand(1); // trampoline
12232   SDValue FPtr = Op.getOperand(2); // nested function
12233   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12234   SDLoc dl (Op);
12235
12236   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12237   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12238
12239   if (Subtarget->is64Bit()) {
12240     SDValue OutChains[6];
12241
12242     // Large code-model.
12243     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12244     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12245
12246     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12247     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12248
12249     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12250
12251     // Load the pointer to the nested function into R11.
12252     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12253     SDValue Addr = Trmp;
12254     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12255                                 Addr, MachinePointerInfo(TrmpAddr),
12256                                 false, false, 0);
12257
12258     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12259                        DAG.getConstant(2, MVT::i64));
12260     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12261                                 MachinePointerInfo(TrmpAddr, 2),
12262                                 false, false, 2);
12263
12264     // Load the 'nest' parameter value into R10.
12265     // R10 is specified in X86CallingConv.td
12266     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12267     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12268                        DAG.getConstant(10, MVT::i64));
12269     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12270                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12271                                 false, false, 0);
12272
12273     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12274                        DAG.getConstant(12, MVT::i64));
12275     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12276                                 MachinePointerInfo(TrmpAddr, 12),
12277                                 false, false, 2);
12278
12279     // Jump to the nested function.
12280     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12281     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12282                        DAG.getConstant(20, MVT::i64));
12283     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12284                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12285                                 false, false, 0);
12286
12287     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12288     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12289                        DAG.getConstant(22, MVT::i64));
12290     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12291                                 MachinePointerInfo(TrmpAddr, 22),
12292                                 false, false, 0);
12293
12294     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12295   } else {
12296     const Function *Func =
12297       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12298     CallingConv::ID CC = Func->getCallingConv();
12299     unsigned NestReg;
12300
12301     switch (CC) {
12302     default:
12303       llvm_unreachable("Unsupported calling convention");
12304     case CallingConv::C:
12305     case CallingConv::X86_StdCall: {
12306       // Pass 'nest' parameter in ECX.
12307       // Must be kept in sync with X86CallingConv.td
12308       NestReg = X86::ECX;
12309
12310       // Check that ECX wasn't needed by an 'inreg' parameter.
12311       FunctionType *FTy = Func->getFunctionType();
12312       const AttributeSet &Attrs = Func->getAttributes();
12313
12314       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12315         unsigned InRegCount = 0;
12316         unsigned Idx = 1;
12317
12318         for (FunctionType::param_iterator I = FTy->param_begin(),
12319              E = FTy->param_end(); I != E; ++I, ++Idx)
12320           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12321             // FIXME: should only count parameters that are lowered to integers.
12322             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12323
12324         if (InRegCount > 2) {
12325           report_fatal_error("Nest register in use - reduce number of inreg"
12326                              " parameters!");
12327         }
12328       }
12329       break;
12330     }
12331     case CallingConv::X86_FastCall:
12332     case CallingConv::X86_ThisCall:
12333     case CallingConv::Fast:
12334       // Pass 'nest' parameter in EAX.
12335       // Must be kept in sync with X86CallingConv.td
12336       NestReg = X86::EAX;
12337       break;
12338     }
12339
12340     SDValue OutChains[4];
12341     SDValue Addr, Disp;
12342
12343     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12344                        DAG.getConstant(10, MVT::i32));
12345     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12346
12347     // This is storing the opcode for MOV32ri.
12348     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12349     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12350     OutChains[0] = DAG.getStore(Root, dl,
12351                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12352                                 Trmp, MachinePointerInfo(TrmpAddr),
12353                                 false, false, 0);
12354
12355     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12356                        DAG.getConstant(1, MVT::i32));
12357     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12358                                 MachinePointerInfo(TrmpAddr, 1),
12359                                 false, false, 1);
12360
12361     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12362     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12363                        DAG.getConstant(5, MVT::i32));
12364     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12365                                 MachinePointerInfo(TrmpAddr, 5),
12366                                 false, false, 1);
12367
12368     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12369                        DAG.getConstant(6, MVT::i32));
12370     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12371                                 MachinePointerInfo(TrmpAddr, 6),
12372                                 false, false, 1);
12373
12374     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12375   }
12376 }
12377
12378 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12379                                             SelectionDAG &DAG) const {
12380   /*
12381    The rounding mode is in bits 11:10 of FPSR, and has the following
12382    settings:
12383      00 Round to nearest
12384      01 Round to -inf
12385      10 Round to +inf
12386      11 Round to 0
12387
12388   FLT_ROUNDS, on the other hand, expects the following:
12389     -1 Undefined
12390      0 Round to 0
12391      1 Round to nearest
12392      2 Round to +inf
12393      3 Round to -inf
12394
12395   To perform the conversion, we do:
12396     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12397   */
12398
12399   MachineFunction &MF = DAG.getMachineFunction();
12400   const TargetMachine &TM = MF.getTarget();
12401   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12402   unsigned StackAlignment = TFI.getStackAlignment();
12403   EVT VT = Op.getValueType();
12404   SDLoc DL(Op);
12405
12406   // Save FP Control Word to stack slot
12407   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12408   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12409
12410   MachineMemOperand *MMO =
12411    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12412                            MachineMemOperand::MOStore, 2, 2);
12413
12414   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12415   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12416                                           DAG.getVTList(MVT::Other),
12417                                           Ops, array_lengthof(Ops), MVT::i16,
12418                                           MMO);
12419
12420   // Load FP Control Word from stack slot
12421   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12422                             MachinePointerInfo(), false, false, false, 0);
12423
12424   // Transform as necessary
12425   SDValue CWD1 =
12426     DAG.getNode(ISD::SRL, DL, MVT::i16,
12427                 DAG.getNode(ISD::AND, DL, MVT::i16,
12428                             CWD, DAG.getConstant(0x800, MVT::i16)),
12429                 DAG.getConstant(11, MVT::i8));
12430   SDValue CWD2 =
12431     DAG.getNode(ISD::SRL, DL, MVT::i16,
12432                 DAG.getNode(ISD::AND, DL, MVT::i16,
12433                             CWD, DAG.getConstant(0x400, MVT::i16)),
12434                 DAG.getConstant(9, MVT::i8));
12435
12436   SDValue RetVal =
12437     DAG.getNode(ISD::AND, DL, MVT::i16,
12438                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12439                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12440                             DAG.getConstant(1, MVT::i16)),
12441                 DAG.getConstant(3, MVT::i16));
12442
12443   return DAG.getNode((VT.getSizeInBits() < 16 ?
12444                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12445 }
12446
12447 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12448   EVT VT = Op.getValueType();
12449   EVT OpVT = VT;
12450   unsigned NumBits = VT.getSizeInBits();
12451   SDLoc dl(Op);
12452
12453   Op = Op.getOperand(0);
12454   if (VT == MVT::i8) {
12455     // Zero extend to i32 since there is not an i8 bsr.
12456     OpVT = MVT::i32;
12457     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12458   }
12459
12460   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12461   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12462   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12463
12464   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12465   SDValue Ops[] = {
12466     Op,
12467     DAG.getConstant(NumBits+NumBits-1, OpVT),
12468     DAG.getConstant(X86::COND_E, MVT::i8),
12469     Op.getValue(1)
12470   };
12471   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12472
12473   // Finally xor with NumBits-1.
12474   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12475
12476   if (VT == MVT::i8)
12477     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12478   return Op;
12479 }
12480
12481 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12482   EVT VT = Op.getValueType();
12483   EVT OpVT = VT;
12484   unsigned NumBits = VT.getSizeInBits();
12485   SDLoc dl(Op);
12486
12487   Op = Op.getOperand(0);
12488   if (VT == MVT::i8) {
12489     // Zero extend to i32 since there is not an i8 bsr.
12490     OpVT = MVT::i32;
12491     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12492   }
12493
12494   // Issue a bsr (scan bits in reverse).
12495   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12496   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12497
12498   // And xor with NumBits-1.
12499   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12500
12501   if (VT == MVT::i8)
12502     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12503   return Op;
12504 }
12505
12506 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12507   EVT VT = Op.getValueType();
12508   unsigned NumBits = VT.getSizeInBits();
12509   SDLoc dl(Op);
12510   Op = Op.getOperand(0);
12511
12512   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12513   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12514   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12515
12516   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12517   SDValue Ops[] = {
12518     Op,
12519     DAG.getConstant(NumBits, VT),
12520     DAG.getConstant(X86::COND_E, MVT::i8),
12521     Op.getValue(1)
12522   };
12523   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12524 }
12525
12526 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12527 // ones, and then concatenate the result back.
12528 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12529   EVT VT = Op.getValueType();
12530
12531   assert(VT.is256BitVector() && VT.isInteger() &&
12532          "Unsupported value type for operation");
12533
12534   unsigned NumElems = VT.getVectorNumElements();
12535   SDLoc dl(Op);
12536
12537   // Extract the LHS vectors
12538   SDValue LHS = Op.getOperand(0);
12539   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12540   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12541
12542   // Extract the RHS vectors
12543   SDValue RHS = Op.getOperand(1);
12544   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12545   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12546
12547   MVT EltVT = VT.getVectorElementType().getSimpleVT();
12548   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12549
12550   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12551                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12552                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12553 }
12554
12555 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12556   assert(Op.getValueType().is256BitVector() &&
12557          Op.getValueType().isInteger() &&
12558          "Only handle AVX 256-bit vector integer operation");
12559   return Lower256IntArith(Op, DAG);
12560 }
12561
12562 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12563   assert(Op.getValueType().is256BitVector() &&
12564          Op.getValueType().isInteger() &&
12565          "Only handle AVX 256-bit vector integer operation");
12566   return Lower256IntArith(Op, DAG);
12567 }
12568
12569 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12570                         SelectionDAG &DAG) {
12571   SDLoc dl(Op);
12572   EVT VT = Op.getValueType();
12573
12574   // Decompose 256-bit ops into smaller 128-bit ops.
12575   if (VT.is256BitVector() && !Subtarget->hasInt256())
12576     return Lower256IntArith(Op, DAG);
12577
12578   SDValue A = Op.getOperand(0);
12579   SDValue B = Op.getOperand(1);
12580
12581   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12582   if (VT == MVT::v4i32) {
12583     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12584            "Should not custom lower when pmuldq is available!");
12585
12586     // Extract the odd parts.
12587     static const int UnpackMask[] = { 1, -1, 3, -1 };
12588     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12589     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12590
12591     // Multiply the even parts.
12592     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12593     // Now multiply odd parts.
12594     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12595
12596     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12597     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12598
12599     // Merge the two vectors back together with a shuffle. This expands into 2
12600     // shuffles.
12601     static const int ShufMask[] = { 0, 4, 2, 6 };
12602     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12603   }
12604
12605   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12606          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12607
12608   //  Ahi = psrlqi(a, 32);
12609   //  Bhi = psrlqi(b, 32);
12610   //
12611   //  AloBlo = pmuludq(a, b);
12612   //  AloBhi = pmuludq(a, Bhi);
12613   //  AhiBlo = pmuludq(Ahi, b);
12614
12615   //  AloBhi = psllqi(AloBhi, 32);
12616   //  AhiBlo = psllqi(AhiBlo, 32);
12617   //  return AloBlo + AloBhi + AhiBlo;
12618
12619   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12620   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12621
12622   // Bit cast to 32-bit vectors for MULUDQ
12623   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12624                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12625   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12626   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12627   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12628   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12629
12630   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12631   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12632   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12633
12634   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12635   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12636
12637   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12638   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12639 }
12640
12641 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12642   EVT VT = Op.getValueType();
12643   EVT EltTy = VT.getVectorElementType();
12644   unsigned NumElts = VT.getVectorNumElements();
12645   SDValue N0 = Op.getOperand(0);
12646   SDLoc dl(Op);
12647
12648   // Lower sdiv X, pow2-const.
12649   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12650   if (!C)
12651     return SDValue();
12652
12653   APInt SplatValue, SplatUndef;
12654   unsigned SplatBitSize;
12655   bool HasAnyUndefs;
12656   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12657                           HasAnyUndefs) ||
12658       EltTy.getSizeInBits() < SplatBitSize)
12659     return SDValue();
12660
12661   if ((SplatValue != 0) &&
12662       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12663     unsigned Lg2 = SplatValue.countTrailingZeros();
12664     // Splat the sign bit.
12665     SmallVector<SDValue, 16> Sz(NumElts,
12666                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12667                                                 EltTy));
12668     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12669                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12670                                           NumElts));
12671     // Add (N0 < 0) ? abs2 - 1 : 0;
12672     SmallVector<SDValue, 16> Amt(NumElts,
12673                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12674                                                  EltTy));
12675     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12676                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12677                                           NumElts));
12678     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12679     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12680     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12681                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12682                                           NumElts));
12683
12684     // If we're dividing by a positive value, we're done.  Otherwise, we must
12685     // negate the result.
12686     if (SplatValue.isNonNegative())
12687       return SRA;
12688
12689     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12690     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12691     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12692   }
12693   return SDValue();
12694 }
12695
12696 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12697                                          const X86Subtarget *Subtarget) {
12698   EVT VT = Op.getValueType();
12699   SDLoc dl(Op);
12700   SDValue R = Op.getOperand(0);
12701   SDValue Amt = Op.getOperand(1);
12702
12703   // Optimize shl/srl/sra with constant shift amount.
12704   if (isSplatVector(Amt.getNode())) {
12705     SDValue SclrAmt = Amt->getOperand(0);
12706     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12707       uint64_t ShiftAmt = C->getZExtValue();
12708
12709       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12710           (Subtarget->hasInt256() &&
12711            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12712           (Subtarget->hasAVX512() &&
12713            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12714         if (Op.getOpcode() == ISD::SHL)
12715           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12716                                             DAG);
12717         if (Op.getOpcode() == ISD::SRL)
12718           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12719                                             DAG);
12720         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12721           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12722                                             DAG);
12723       }
12724
12725       if (VT == MVT::v16i8) {
12726         if (Op.getOpcode() == ISD::SHL) {
12727           // Make a large shift.
12728           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12729                                                    MVT::v8i16, R, ShiftAmt,
12730                                                    DAG);
12731           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12732           // Zero out the rightmost bits.
12733           SmallVector<SDValue, 16> V(16,
12734                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12735                                                      MVT::i8));
12736           return DAG.getNode(ISD::AND, dl, VT, SHL,
12737                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12738         }
12739         if (Op.getOpcode() == ISD::SRL) {
12740           // Make a large shift.
12741           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12742                                                    MVT::v8i16, R, ShiftAmt,
12743                                                    DAG);
12744           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12745           // Zero out the leftmost bits.
12746           SmallVector<SDValue, 16> V(16,
12747                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12748                                                      MVT::i8));
12749           return DAG.getNode(ISD::AND, dl, VT, SRL,
12750                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12751         }
12752         if (Op.getOpcode() == ISD::SRA) {
12753           if (ShiftAmt == 7) {
12754             // R s>> 7  ===  R s< 0
12755             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12756             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12757           }
12758
12759           // R s>> a === ((R u>> a) ^ m) - m
12760           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12761           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12762                                                          MVT::i8));
12763           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12764           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12765           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12766           return Res;
12767         }
12768         llvm_unreachable("Unknown shift opcode.");
12769       }
12770
12771       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12772         if (Op.getOpcode() == ISD::SHL) {
12773           // Make a large shift.
12774           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12775                                                    MVT::v16i16, R, ShiftAmt,
12776                                                    DAG);
12777           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12778           // Zero out the rightmost bits.
12779           SmallVector<SDValue, 32> V(32,
12780                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12781                                                      MVT::i8));
12782           return DAG.getNode(ISD::AND, dl, VT, SHL,
12783                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12784         }
12785         if (Op.getOpcode() == ISD::SRL) {
12786           // Make a large shift.
12787           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12788                                                    MVT::v16i16, R, ShiftAmt,
12789                                                    DAG);
12790           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12791           // Zero out the leftmost bits.
12792           SmallVector<SDValue, 32> V(32,
12793                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12794                                                      MVT::i8));
12795           return DAG.getNode(ISD::AND, dl, VT, SRL,
12796                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12797         }
12798         if (Op.getOpcode() == ISD::SRA) {
12799           if (ShiftAmt == 7) {
12800             // R s>> 7  ===  R s< 0
12801             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12802             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12803           }
12804
12805           // R s>> a === ((R u>> a) ^ m) - m
12806           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12807           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12808                                                          MVT::i8));
12809           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12810           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12811           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12812           return Res;
12813         }
12814         llvm_unreachable("Unknown shift opcode.");
12815       }
12816     }
12817   }
12818
12819   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12820   if (!Subtarget->is64Bit() &&
12821       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12822       Amt.getOpcode() == ISD::BITCAST &&
12823       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12824     Amt = Amt.getOperand(0);
12825     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12826                      VT.getVectorNumElements();
12827     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12828     uint64_t ShiftAmt = 0;
12829     for (unsigned i = 0; i != Ratio; ++i) {
12830       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12831       if (C == 0)
12832         return SDValue();
12833       // 6 == Log2(64)
12834       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12835     }
12836     // Check remaining shift amounts.
12837     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12838       uint64_t ShAmt = 0;
12839       for (unsigned j = 0; j != Ratio; ++j) {
12840         ConstantSDNode *C =
12841           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12842         if (C == 0)
12843           return SDValue();
12844         // 6 == Log2(64)
12845         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12846       }
12847       if (ShAmt != ShiftAmt)
12848         return SDValue();
12849     }
12850     switch (Op.getOpcode()) {
12851     default:
12852       llvm_unreachable("Unknown shift opcode!");
12853     case ISD::SHL:
12854       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12855                                         DAG);
12856     case ISD::SRL:
12857       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12858                                         DAG);
12859     case ISD::SRA:
12860       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12861                                         DAG);
12862     }
12863   }
12864
12865   return SDValue();
12866 }
12867
12868 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12869                                         const X86Subtarget* Subtarget) {
12870   EVT VT = Op.getValueType();
12871   SDLoc dl(Op);
12872   SDValue R = Op.getOperand(0);
12873   SDValue Amt = Op.getOperand(1);
12874
12875   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12876       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12877       (Subtarget->hasInt256() &&
12878        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12879         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12880        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12881     SDValue BaseShAmt;
12882     EVT EltVT = VT.getVectorElementType();
12883
12884     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12885       unsigned NumElts = VT.getVectorNumElements();
12886       unsigned i, j;
12887       for (i = 0; i != NumElts; ++i) {
12888         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12889           continue;
12890         break;
12891       }
12892       for (j = i; j != NumElts; ++j) {
12893         SDValue Arg = Amt.getOperand(j);
12894         if (Arg.getOpcode() == ISD::UNDEF) continue;
12895         if (Arg != Amt.getOperand(i))
12896           break;
12897       }
12898       if (i != NumElts && j == NumElts)
12899         BaseShAmt = Amt.getOperand(i);
12900     } else {
12901       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12902         Amt = Amt.getOperand(0);
12903       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12904                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12905         SDValue InVec = Amt.getOperand(0);
12906         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12907           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12908           unsigned i = 0;
12909           for (; i != NumElts; ++i) {
12910             SDValue Arg = InVec.getOperand(i);
12911             if (Arg.getOpcode() == ISD::UNDEF) continue;
12912             BaseShAmt = Arg;
12913             break;
12914           }
12915         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12916            if (ConstantSDNode *C =
12917                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12918              unsigned SplatIdx =
12919                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12920              if (C->getZExtValue() == SplatIdx)
12921                BaseShAmt = InVec.getOperand(1);
12922            }
12923         }
12924         if (BaseShAmt.getNode() == 0)
12925           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12926                                   DAG.getIntPtrConstant(0));
12927       }
12928     }
12929
12930     if (BaseShAmt.getNode()) {
12931       if (EltVT.bitsGT(MVT::i32))
12932         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12933       else if (EltVT.bitsLT(MVT::i32))
12934         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12935
12936       switch (Op.getOpcode()) {
12937       default:
12938         llvm_unreachable("Unknown shift opcode!");
12939       case ISD::SHL:
12940         switch (VT.getSimpleVT().SimpleTy) {
12941         default: return SDValue();
12942         case MVT::v2i64:
12943         case MVT::v4i32:
12944         case MVT::v8i16:
12945         case MVT::v4i64:
12946         case MVT::v8i32:
12947         case MVT::v16i16:
12948         case MVT::v16i32:
12949         case MVT::v8i64:
12950           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12951         }
12952       case ISD::SRA:
12953         switch (VT.getSimpleVT().SimpleTy) {
12954         default: return SDValue();
12955         case MVT::v4i32:
12956         case MVT::v8i16:
12957         case MVT::v8i32:
12958         case MVT::v16i16:
12959         case MVT::v16i32:
12960         case MVT::v8i64:
12961           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12962         }
12963       case ISD::SRL:
12964         switch (VT.getSimpleVT().SimpleTy) {
12965         default: return SDValue();
12966         case MVT::v2i64:
12967         case MVT::v4i32:
12968         case MVT::v8i16:
12969         case MVT::v4i64:
12970         case MVT::v8i32:
12971         case MVT::v16i16:
12972         case MVT::v16i32:
12973         case MVT::v8i64:
12974           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12975         }
12976       }
12977     }
12978   }
12979
12980   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12981   if (!Subtarget->is64Bit() &&
12982       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
12983       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
12984       Amt.getOpcode() == ISD::BITCAST &&
12985       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12986     Amt = Amt.getOperand(0);
12987     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12988                      VT.getVectorNumElements();
12989     std::vector<SDValue> Vals(Ratio);
12990     for (unsigned i = 0; i != Ratio; ++i)
12991       Vals[i] = Amt.getOperand(i);
12992     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12993       for (unsigned j = 0; j != Ratio; ++j)
12994         if (Vals[j] != Amt.getOperand(i + j))
12995           return SDValue();
12996     }
12997     switch (Op.getOpcode()) {
12998     default:
12999       llvm_unreachable("Unknown shift opcode!");
13000     case ISD::SHL:
13001       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13002     case ISD::SRL:
13003       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13004     case ISD::SRA:
13005       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13006     }
13007   }
13008
13009   return SDValue();
13010 }
13011
13012 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13013                           SelectionDAG &DAG) {
13014
13015   EVT VT = Op.getValueType();
13016   SDLoc dl(Op);
13017   SDValue R = Op.getOperand(0);
13018   SDValue Amt = Op.getOperand(1);
13019   SDValue V;
13020
13021   if (!Subtarget->hasSSE2())
13022     return SDValue();
13023
13024   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13025   if (V.getNode())
13026     return V;
13027
13028   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13029   if (V.getNode())
13030       return V;
13031
13032   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13033     return Op;
13034   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13035   if (Subtarget->hasInt256()) {
13036     if (Op.getOpcode() == ISD::SRL &&
13037         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13038          VT == MVT::v4i64 || VT == MVT::v8i32))
13039       return Op;
13040     if (Op.getOpcode() == ISD::SHL &&
13041         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13042          VT == MVT::v4i64 || VT == MVT::v8i32))
13043       return Op;
13044     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13045       return Op;
13046   }
13047
13048   // Lower SHL with variable shift amount.
13049   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13050     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13051
13052     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13053     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13054     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13055     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13056   }
13057   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13058     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13059
13060     // a = a << 5;
13061     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13062     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13063
13064     // Turn 'a' into a mask suitable for VSELECT
13065     SDValue VSelM = DAG.getConstant(0x80, VT);
13066     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13067     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13068
13069     SDValue CM1 = DAG.getConstant(0x0f, VT);
13070     SDValue CM2 = DAG.getConstant(0x3f, VT);
13071
13072     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13073     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13074     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13075     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13076     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13077
13078     // a += a
13079     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13080     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13081     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13082
13083     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13084     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13085     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13086     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13087     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13088
13089     // a += a
13090     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13091     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13092     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13093
13094     // return VSELECT(r, r+r, a);
13095     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13096                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13097     return R;
13098   }
13099
13100   // Decompose 256-bit shifts into smaller 128-bit shifts.
13101   if (VT.is256BitVector()) {
13102     unsigned NumElems = VT.getVectorNumElements();
13103     MVT EltVT = VT.getVectorElementType().getSimpleVT();
13104     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13105
13106     // Extract the two vectors
13107     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13108     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13109
13110     // Recreate the shift amount vectors
13111     SDValue Amt1, Amt2;
13112     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13113       // Constant shift amount
13114       SmallVector<SDValue, 4> Amt1Csts;
13115       SmallVector<SDValue, 4> Amt2Csts;
13116       for (unsigned i = 0; i != NumElems/2; ++i)
13117         Amt1Csts.push_back(Amt->getOperand(i));
13118       for (unsigned i = NumElems/2; i != NumElems; ++i)
13119         Amt2Csts.push_back(Amt->getOperand(i));
13120
13121       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13122                                  &Amt1Csts[0], NumElems/2);
13123       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13124                                  &Amt2Csts[0], NumElems/2);
13125     } else {
13126       // Variable shift amount
13127       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13128       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13129     }
13130
13131     // Issue new vector shifts for the smaller types
13132     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13133     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13134
13135     // Concatenate the result back
13136     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13137   }
13138
13139   return SDValue();
13140 }
13141
13142 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13143   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13144   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13145   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13146   // has only one use.
13147   SDNode *N = Op.getNode();
13148   SDValue LHS = N->getOperand(0);
13149   SDValue RHS = N->getOperand(1);
13150   unsigned BaseOp = 0;
13151   unsigned Cond = 0;
13152   SDLoc DL(Op);
13153   switch (Op.getOpcode()) {
13154   default: llvm_unreachable("Unknown ovf instruction!");
13155   case ISD::SADDO:
13156     // A subtract of one will be selected as a INC. Note that INC doesn't
13157     // set CF, so we can't do this for UADDO.
13158     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13159       if (C->isOne()) {
13160         BaseOp = X86ISD::INC;
13161         Cond = X86::COND_O;
13162         break;
13163       }
13164     BaseOp = X86ISD::ADD;
13165     Cond = X86::COND_O;
13166     break;
13167   case ISD::UADDO:
13168     BaseOp = X86ISD::ADD;
13169     Cond = X86::COND_B;
13170     break;
13171   case ISD::SSUBO:
13172     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13173     // set CF, so we can't do this for USUBO.
13174     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13175       if (C->isOne()) {
13176         BaseOp = X86ISD::DEC;
13177         Cond = X86::COND_O;
13178         break;
13179       }
13180     BaseOp = X86ISD::SUB;
13181     Cond = X86::COND_O;
13182     break;
13183   case ISD::USUBO:
13184     BaseOp = X86ISD::SUB;
13185     Cond = X86::COND_B;
13186     break;
13187   case ISD::SMULO:
13188     BaseOp = X86ISD::SMUL;
13189     Cond = X86::COND_O;
13190     break;
13191   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13192     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13193                                  MVT::i32);
13194     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13195
13196     SDValue SetCC =
13197       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13198                   DAG.getConstant(X86::COND_O, MVT::i32),
13199                   SDValue(Sum.getNode(), 2));
13200
13201     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13202   }
13203   }
13204
13205   // Also sets EFLAGS.
13206   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13207   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13208
13209   SDValue SetCC =
13210     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13211                 DAG.getConstant(Cond, MVT::i32),
13212                 SDValue(Sum.getNode(), 1));
13213
13214   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13215 }
13216
13217 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13218                                                   SelectionDAG &DAG) const {
13219   SDLoc dl(Op);
13220   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13221   EVT VT = Op.getValueType();
13222
13223   if (!Subtarget->hasSSE2() || !VT.isVector())
13224     return SDValue();
13225
13226   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13227                       ExtraVT.getScalarType().getSizeInBits();
13228
13229   switch (VT.getSimpleVT().SimpleTy) {
13230     default: return SDValue();
13231     case MVT::v8i32:
13232     case MVT::v16i16:
13233       if (!Subtarget->hasFp256())
13234         return SDValue();
13235       if (!Subtarget->hasInt256()) {
13236         // needs to be split
13237         unsigned NumElems = VT.getVectorNumElements();
13238
13239         // Extract the LHS vectors
13240         SDValue LHS = Op.getOperand(0);
13241         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13242         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13243
13244         MVT EltVT = VT.getVectorElementType().getSimpleVT();
13245         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13246
13247         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13248         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13249         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13250                                    ExtraNumElems/2);
13251         SDValue Extra = DAG.getValueType(ExtraVT);
13252
13253         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13254         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13255
13256         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13257       }
13258       // fall through
13259     case MVT::v4i32:
13260     case MVT::v8i16: {
13261       SDValue Op0 = Op.getOperand(0);
13262       SDValue Op00 = Op0.getOperand(0);
13263       SDValue Tmp1;
13264       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13265       if (Op0.getOpcode() == ISD::BITCAST &&
13266           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13267         // (sext (vzext x)) -> (vsext x)
13268         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13269         if (Tmp1.getNode()) {
13270           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13271           // This folding is only valid when the in-reg type is a vector of i8,
13272           // i16, or i32.
13273           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13274               ExtraEltVT == MVT::i32) {
13275             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13276             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13277                    "This optimization is invalid without a VZEXT.");
13278             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13279           }
13280           Op0 = Tmp1;
13281         }
13282       }
13283
13284       // If the above didn't work, then just use Shift-Left + Shift-Right.
13285       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13286                                         DAG);
13287       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13288                                         DAG);
13289     }
13290   }
13291 }
13292
13293 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13294                                  SelectionDAG &DAG) {
13295   SDLoc dl(Op);
13296   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13297     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13298   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13299     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13300
13301   // The only fence that needs an instruction is a sequentially-consistent
13302   // cross-thread fence.
13303   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13304     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13305     // no-sse2). There isn't any reason to disable it if the target processor
13306     // supports it.
13307     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13308       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13309
13310     SDValue Chain = Op.getOperand(0);
13311     SDValue Zero = DAG.getConstant(0, MVT::i32);
13312     SDValue Ops[] = {
13313       DAG.getRegister(X86::ESP, MVT::i32), // Base
13314       DAG.getTargetConstant(1, MVT::i8),   // Scale
13315       DAG.getRegister(0, MVT::i32),        // Index
13316       DAG.getTargetConstant(0, MVT::i32),  // Disp
13317       DAG.getRegister(0, MVT::i32),        // Segment.
13318       Zero,
13319       Chain
13320     };
13321     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13322     return SDValue(Res, 0);
13323   }
13324
13325   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13326   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13327 }
13328
13329 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13330                              SelectionDAG &DAG) {
13331   EVT T = Op.getValueType();
13332   SDLoc DL(Op);
13333   unsigned Reg = 0;
13334   unsigned size = 0;
13335   switch(T.getSimpleVT().SimpleTy) {
13336   default: llvm_unreachable("Invalid value type!");
13337   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13338   case MVT::i16: Reg = X86::AX;  size = 2; break;
13339   case MVT::i32: Reg = X86::EAX; size = 4; break;
13340   case MVT::i64:
13341     assert(Subtarget->is64Bit() && "Node not type legal!");
13342     Reg = X86::RAX; size = 8;
13343     break;
13344   }
13345   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13346                                     Op.getOperand(2), SDValue());
13347   SDValue Ops[] = { cpIn.getValue(0),
13348                     Op.getOperand(1),
13349                     Op.getOperand(3),
13350                     DAG.getTargetConstant(size, MVT::i8),
13351                     cpIn.getValue(1) };
13352   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13353   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13354   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13355                                            Ops, array_lengthof(Ops), T, MMO);
13356   SDValue cpOut =
13357     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13358   return cpOut;
13359 }
13360
13361 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13362                                      SelectionDAG &DAG) {
13363   assert(Subtarget->is64Bit() && "Result not type legalized?");
13364   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13365   SDValue TheChain = Op.getOperand(0);
13366   SDLoc dl(Op);
13367   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13368   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13369   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13370                                    rax.getValue(2));
13371   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13372                             DAG.getConstant(32, MVT::i8));
13373   SDValue Ops[] = {
13374     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13375     rdx.getValue(1)
13376   };
13377   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13378 }
13379
13380 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13381                             SelectionDAG &DAG) {
13382   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13383   MVT DstVT = Op.getSimpleValueType();
13384   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13385          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13386   assert((DstVT == MVT::i64 ||
13387           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13388          "Unexpected custom BITCAST");
13389   // i64 <=> MMX conversions are Legal.
13390   if (SrcVT==MVT::i64 && DstVT.isVector())
13391     return Op;
13392   if (DstVT==MVT::i64 && SrcVT.isVector())
13393     return Op;
13394   // MMX <=> MMX conversions are Legal.
13395   if (SrcVT.isVector() && DstVT.isVector())
13396     return Op;
13397   // All other conversions need to be expanded.
13398   return SDValue();
13399 }
13400
13401 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13402   SDNode *Node = Op.getNode();
13403   SDLoc dl(Node);
13404   EVT T = Node->getValueType(0);
13405   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13406                               DAG.getConstant(0, T), Node->getOperand(2));
13407   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13408                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13409                        Node->getOperand(0),
13410                        Node->getOperand(1), negOp,
13411                        cast<AtomicSDNode>(Node)->getSrcValue(),
13412                        cast<AtomicSDNode>(Node)->getAlignment(),
13413                        cast<AtomicSDNode>(Node)->getOrdering(),
13414                        cast<AtomicSDNode>(Node)->getSynchScope());
13415 }
13416
13417 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13418   SDNode *Node = Op.getNode();
13419   SDLoc dl(Node);
13420   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13421
13422   // Convert seq_cst store -> xchg
13423   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13424   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13425   //        (The only way to get a 16-byte store is cmpxchg16b)
13426   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13427   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13428       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13429     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13430                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13431                                  Node->getOperand(0),
13432                                  Node->getOperand(1), Node->getOperand(2),
13433                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13434                                  cast<AtomicSDNode>(Node)->getOrdering(),
13435                                  cast<AtomicSDNode>(Node)->getSynchScope());
13436     return Swap.getValue(1);
13437   }
13438   // Other atomic stores have a simple pattern.
13439   return Op;
13440 }
13441
13442 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13443   EVT VT = Op.getNode()->getValueType(0);
13444
13445   // Let legalize expand this if it isn't a legal type yet.
13446   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13447     return SDValue();
13448
13449   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13450
13451   unsigned Opc;
13452   bool ExtraOp = false;
13453   switch (Op.getOpcode()) {
13454   default: llvm_unreachable("Invalid code");
13455   case ISD::ADDC: Opc = X86ISD::ADD; break;
13456   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13457   case ISD::SUBC: Opc = X86ISD::SUB; break;
13458   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13459   }
13460
13461   if (!ExtraOp)
13462     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13463                        Op.getOperand(1));
13464   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13465                      Op.getOperand(1), Op.getOperand(2));
13466 }
13467
13468 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13469                             SelectionDAG &DAG) {
13470   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13471
13472   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13473   // which returns the values as { float, float } (in XMM0) or
13474   // { double, double } (which is returned in XMM0, XMM1).
13475   SDLoc dl(Op);
13476   SDValue Arg = Op.getOperand(0);
13477   EVT ArgVT = Arg.getValueType();
13478   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13479
13480   TargetLowering::ArgListTy Args;
13481   TargetLowering::ArgListEntry Entry;
13482
13483   Entry.Node = Arg;
13484   Entry.Ty = ArgTy;
13485   Entry.isSExt = false;
13486   Entry.isZExt = false;
13487   Args.push_back(Entry);
13488
13489   bool isF64 = ArgVT == MVT::f64;
13490   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13491   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13492   // the results are returned via SRet in memory.
13493   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13495   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13496
13497   Type *RetTy = isF64
13498     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13499     : (Type*)VectorType::get(ArgTy, 4);
13500   TargetLowering::
13501     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13502                          false, false, false, false, 0,
13503                          CallingConv::C, /*isTaillCall=*/false,
13504                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13505                          Callee, Args, DAG, dl);
13506   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13507
13508   if (isF64)
13509     // Returned in xmm0 and xmm1.
13510     return CallResult.first;
13511
13512   // Returned in bits 0:31 and 32:64 xmm0.
13513   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13514                                CallResult.first, DAG.getIntPtrConstant(0));
13515   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13516                                CallResult.first, DAG.getIntPtrConstant(1));
13517   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13518   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13519 }
13520
13521 /// LowerOperation - Provide custom lowering hooks for some operations.
13522 ///
13523 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13524   switch (Op.getOpcode()) {
13525   default: llvm_unreachable("Should not custom lower this!");
13526   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13527   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13528   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13529   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13530   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13531   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13532   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13533   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13534   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13535   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13536   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13537   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13538   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13539   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13540   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13541   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13542   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13543   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13544   case ISD::SHL_PARTS:
13545   case ISD::SRA_PARTS:
13546   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13547   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13548   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13549   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13550   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13551   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13552   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13553   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13554   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13555   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13556   case ISD::FABS:               return LowerFABS(Op, DAG);
13557   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13558   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13559   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13560   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13561   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13562   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13563   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13564   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13565   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13566   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13567   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13568   case ISD::INTRINSIC_VOID:
13569   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13570   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13571   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13572   case ISD::FRAME_TO_ARGS_OFFSET:
13573                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13574   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13575   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13576   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13577   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13578   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13579   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13580   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13581   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13582   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13583   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13584   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13585   case ISD::SRA:
13586   case ISD::SRL:
13587   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13588   case ISD::SADDO:
13589   case ISD::UADDO:
13590   case ISD::SSUBO:
13591   case ISD::USUBO:
13592   case ISD::SMULO:
13593   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13594   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13595   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13596   case ISD::ADDC:
13597   case ISD::ADDE:
13598   case ISD::SUBC:
13599   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13600   case ISD::ADD:                return LowerADD(Op, DAG);
13601   case ISD::SUB:                return LowerSUB(Op, DAG);
13602   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13603   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13604   }
13605 }
13606
13607 static void ReplaceATOMIC_LOAD(SDNode *Node,
13608                                   SmallVectorImpl<SDValue> &Results,
13609                                   SelectionDAG &DAG) {
13610   SDLoc dl(Node);
13611   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13612
13613   // Convert wide load -> cmpxchg8b/cmpxchg16b
13614   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13615   //        (The only way to get a 16-byte load is cmpxchg16b)
13616   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13617   SDValue Zero = DAG.getConstant(0, VT);
13618   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13619                                Node->getOperand(0),
13620                                Node->getOperand(1), Zero, Zero,
13621                                cast<AtomicSDNode>(Node)->getMemOperand(),
13622                                cast<AtomicSDNode>(Node)->getOrdering(),
13623                                cast<AtomicSDNode>(Node)->getSynchScope());
13624   Results.push_back(Swap.getValue(0));
13625   Results.push_back(Swap.getValue(1));
13626 }
13627
13628 static void
13629 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13630                         SelectionDAG &DAG, unsigned NewOp) {
13631   SDLoc dl(Node);
13632   assert (Node->getValueType(0) == MVT::i64 &&
13633           "Only know how to expand i64 atomics");
13634
13635   SDValue Chain = Node->getOperand(0);
13636   SDValue In1 = Node->getOperand(1);
13637   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13638                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13639   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13640                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13641   SDValue Ops[] = { Chain, In1, In2L, In2H };
13642   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13643   SDValue Result =
13644     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13645                             cast<MemSDNode>(Node)->getMemOperand());
13646   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13647   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13648   Results.push_back(Result.getValue(2));
13649 }
13650
13651 /// ReplaceNodeResults - Replace a node with an illegal result type
13652 /// with a new node built out of custom code.
13653 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13654                                            SmallVectorImpl<SDValue>&Results,
13655                                            SelectionDAG &DAG) const {
13656   SDLoc dl(N);
13657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13658   switch (N->getOpcode()) {
13659   default:
13660     llvm_unreachable("Do not know how to custom type legalize this operation!");
13661   case ISD::SIGN_EXTEND_INREG:
13662   case ISD::ADDC:
13663   case ISD::ADDE:
13664   case ISD::SUBC:
13665   case ISD::SUBE:
13666     // We don't want to expand or promote these.
13667     return;
13668   case ISD::FP_TO_SINT:
13669   case ISD::FP_TO_UINT: {
13670     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13671
13672     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13673       return;
13674
13675     std::pair<SDValue,SDValue> Vals =
13676         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13677     SDValue FIST = Vals.first, StackSlot = Vals.second;
13678     if (FIST.getNode() != 0) {
13679       EVT VT = N->getValueType(0);
13680       // Return a load from the stack slot.
13681       if (StackSlot.getNode() != 0)
13682         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13683                                       MachinePointerInfo(),
13684                                       false, false, false, 0));
13685       else
13686         Results.push_back(FIST);
13687     }
13688     return;
13689   }
13690   case ISD::UINT_TO_FP: {
13691     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13692     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13693         N->getValueType(0) != MVT::v2f32)
13694       return;
13695     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13696                                  N->getOperand(0));
13697     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13698                                      MVT::f64);
13699     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13700     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13701                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13702     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13703     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13704     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13705     return;
13706   }
13707   case ISD::FP_ROUND: {
13708     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13709         return;
13710     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13711     Results.push_back(V);
13712     return;
13713   }
13714   case ISD::READCYCLECOUNTER: {
13715     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13716     SDValue TheChain = N->getOperand(0);
13717     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13718     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13719                                      rd.getValue(1));
13720     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13721                                      eax.getValue(2));
13722     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13723     SDValue Ops[] = { eax, edx };
13724     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13725                                   array_lengthof(Ops)));
13726     Results.push_back(edx.getValue(1));
13727     return;
13728   }
13729   case ISD::ATOMIC_CMP_SWAP: {
13730     EVT T = N->getValueType(0);
13731     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13732     bool Regs64bit = T == MVT::i128;
13733     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13734     SDValue cpInL, cpInH;
13735     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13736                         DAG.getConstant(0, HalfT));
13737     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13738                         DAG.getConstant(1, HalfT));
13739     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13740                              Regs64bit ? X86::RAX : X86::EAX,
13741                              cpInL, SDValue());
13742     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13743                              Regs64bit ? X86::RDX : X86::EDX,
13744                              cpInH, cpInL.getValue(1));
13745     SDValue swapInL, swapInH;
13746     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13747                           DAG.getConstant(0, HalfT));
13748     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13749                           DAG.getConstant(1, HalfT));
13750     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13751                                Regs64bit ? X86::RBX : X86::EBX,
13752                                swapInL, cpInH.getValue(1));
13753     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13754                                Regs64bit ? X86::RCX : X86::ECX,
13755                                swapInH, swapInL.getValue(1));
13756     SDValue Ops[] = { swapInH.getValue(0),
13757                       N->getOperand(1),
13758                       swapInH.getValue(1) };
13759     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13760     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13761     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13762                                   X86ISD::LCMPXCHG8_DAG;
13763     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13764                                              Ops, array_lengthof(Ops), T, MMO);
13765     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13766                                         Regs64bit ? X86::RAX : X86::EAX,
13767                                         HalfT, Result.getValue(1));
13768     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13769                                         Regs64bit ? X86::RDX : X86::EDX,
13770                                         HalfT, cpOutL.getValue(2));
13771     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13772     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13773     Results.push_back(cpOutH.getValue(1));
13774     return;
13775   }
13776   case ISD::ATOMIC_LOAD_ADD:
13777   case ISD::ATOMIC_LOAD_AND:
13778   case ISD::ATOMIC_LOAD_NAND:
13779   case ISD::ATOMIC_LOAD_OR:
13780   case ISD::ATOMIC_LOAD_SUB:
13781   case ISD::ATOMIC_LOAD_XOR:
13782   case ISD::ATOMIC_LOAD_MAX:
13783   case ISD::ATOMIC_LOAD_MIN:
13784   case ISD::ATOMIC_LOAD_UMAX:
13785   case ISD::ATOMIC_LOAD_UMIN:
13786   case ISD::ATOMIC_SWAP: {
13787     unsigned Opc;
13788     switch (N->getOpcode()) {
13789     default: llvm_unreachable("Unexpected opcode");
13790     case ISD::ATOMIC_LOAD_ADD:
13791       Opc = X86ISD::ATOMADD64_DAG;
13792       break;
13793     case ISD::ATOMIC_LOAD_AND:
13794       Opc = X86ISD::ATOMAND64_DAG;
13795       break;
13796     case ISD::ATOMIC_LOAD_NAND:
13797       Opc = X86ISD::ATOMNAND64_DAG;
13798       break;
13799     case ISD::ATOMIC_LOAD_OR:
13800       Opc = X86ISD::ATOMOR64_DAG;
13801       break;
13802     case ISD::ATOMIC_LOAD_SUB:
13803       Opc = X86ISD::ATOMSUB64_DAG;
13804       break;
13805     case ISD::ATOMIC_LOAD_XOR:
13806       Opc = X86ISD::ATOMXOR64_DAG;
13807       break;
13808     case ISD::ATOMIC_LOAD_MAX:
13809       Opc = X86ISD::ATOMMAX64_DAG;
13810       break;
13811     case ISD::ATOMIC_LOAD_MIN:
13812       Opc = X86ISD::ATOMMIN64_DAG;
13813       break;
13814     case ISD::ATOMIC_LOAD_UMAX:
13815       Opc = X86ISD::ATOMUMAX64_DAG;
13816       break;
13817     case ISD::ATOMIC_LOAD_UMIN:
13818       Opc = X86ISD::ATOMUMIN64_DAG;
13819       break;
13820     case ISD::ATOMIC_SWAP:
13821       Opc = X86ISD::ATOMSWAP64_DAG;
13822       break;
13823     }
13824     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13825     return;
13826   }
13827   case ISD::ATOMIC_LOAD:
13828     ReplaceATOMIC_LOAD(N, Results, DAG);
13829   }
13830 }
13831
13832 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13833   switch (Opcode) {
13834   default: return NULL;
13835   case X86ISD::BSF:                return "X86ISD::BSF";
13836   case X86ISD::BSR:                return "X86ISD::BSR";
13837   case X86ISD::SHLD:               return "X86ISD::SHLD";
13838   case X86ISD::SHRD:               return "X86ISD::SHRD";
13839   case X86ISD::FAND:               return "X86ISD::FAND";
13840   case X86ISD::FANDN:              return "X86ISD::FANDN";
13841   case X86ISD::FOR:                return "X86ISD::FOR";
13842   case X86ISD::FXOR:               return "X86ISD::FXOR";
13843   case X86ISD::FSRL:               return "X86ISD::FSRL";
13844   case X86ISD::FILD:               return "X86ISD::FILD";
13845   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13846   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13847   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13848   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13849   case X86ISD::FLD:                return "X86ISD::FLD";
13850   case X86ISD::FST:                return "X86ISD::FST";
13851   case X86ISD::CALL:               return "X86ISD::CALL";
13852   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13853   case X86ISD::BT:                 return "X86ISD::BT";
13854   case X86ISD::CMP:                return "X86ISD::CMP";
13855   case X86ISD::COMI:               return "X86ISD::COMI";
13856   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13857   case X86ISD::CMPM:               return "X86ISD::CMPM";
13858   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
13859   case X86ISD::SETCC:              return "X86ISD::SETCC";
13860   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13861   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
13862   case X86ISD::CMOV:               return "X86ISD::CMOV";
13863   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13864   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13865   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13866   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13867   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13868   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13869   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13870   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13871   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13872   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13873   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13874   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13875   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13876   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13877   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13878   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13879   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13880   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13881   case X86ISD::HADD:               return "X86ISD::HADD";
13882   case X86ISD::HSUB:               return "X86ISD::HSUB";
13883   case X86ISD::FHADD:              return "X86ISD::FHADD";
13884   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13885   case X86ISD::UMAX:               return "X86ISD::UMAX";
13886   case X86ISD::UMIN:               return "X86ISD::UMIN";
13887   case X86ISD::SMAX:               return "X86ISD::SMAX";
13888   case X86ISD::SMIN:               return "X86ISD::SMIN";
13889   case X86ISD::FMAX:               return "X86ISD::FMAX";
13890   case X86ISD::FMIN:               return "X86ISD::FMIN";
13891   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13892   case X86ISD::FMINC:              return "X86ISD::FMINC";
13893   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13894   case X86ISD::FRCP:               return "X86ISD::FRCP";
13895   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13896   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13897   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13898   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13899   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13900   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13901   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13902   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13903   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13904   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13905   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13906   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13907   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13908   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13909   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13910   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13911   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13912   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13913   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13914   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13915   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13916   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13917   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
13918   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
13919   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
13920   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13921   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13922   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13923   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13924   case X86ISD::VSHL:               return "X86ISD::VSHL";
13925   case X86ISD::VSRL:               return "X86ISD::VSRL";
13926   case X86ISD::VSRA:               return "X86ISD::VSRA";
13927   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13928   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13929   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13930   case X86ISD::CMPP:               return "X86ISD::CMPP";
13931   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13932   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13933   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
13934   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
13935   case X86ISD::ADD:                return "X86ISD::ADD";
13936   case X86ISD::SUB:                return "X86ISD::SUB";
13937   case X86ISD::ADC:                return "X86ISD::ADC";
13938   case X86ISD::SBB:                return "X86ISD::SBB";
13939   case X86ISD::SMUL:               return "X86ISD::SMUL";
13940   case X86ISD::UMUL:               return "X86ISD::UMUL";
13941   case X86ISD::INC:                return "X86ISD::INC";
13942   case X86ISD::DEC:                return "X86ISD::DEC";
13943   case X86ISD::OR:                 return "X86ISD::OR";
13944   case X86ISD::XOR:                return "X86ISD::XOR";
13945   case X86ISD::AND:                return "X86ISD::AND";
13946   case X86ISD::BLSI:               return "X86ISD::BLSI";
13947   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13948   case X86ISD::BLSR:               return "X86ISD::BLSR";
13949   case X86ISD::BZHI:               return "X86ISD::BZHI";
13950   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
13951   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13952   case X86ISD::PTEST:              return "X86ISD::PTEST";
13953   case X86ISD::TESTP:              return "X86ISD::TESTP";
13954   case X86ISD::TESTM:              return "X86ISD::TESTM";
13955   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
13956   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13957   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13958   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13959   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13960   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13961   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13962   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13963   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13964   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13965   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13966   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13967   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13968   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13969   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13970   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13971   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13972   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13973   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13974   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
13975   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13976   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13977   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13978   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
13979   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13980   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13981   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13982   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13983   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13984   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13985   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13986   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13987   case X86ISD::SAHF:               return "X86ISD::SAHF";
13988   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13989   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13990   case X86ISD::FMADD:              return "X86ISD::FMADD";
13991   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13992   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13993   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13994   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13995   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13996   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13997   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13998   case X86ISD::XTEST:              return "X86ISD::XTEST";
13999   }
14000 }
14001
14002 // isLegalAddressingMode - Return true if the addressing mode represented
14003 // by AM is legal for this target, for a load/store of the specified type.
14004 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14005                                               Type *Ty) const {
14006   // X86 supports extremely general addressing modes.
14007   CodeModel::Model M = getTargetMachine().getCodeModel();
14008   Reloc::Model R = getTargetMachine().getRelocationModel();
14009
14010   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14011   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14012     return false;
14013
14014   if (AM.BaseGV) {
14015     unsigned GVFlags =
14016       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14017
14018     // If a reference to this global requires an extra load, we can't fold it.
14019     if (isGlobalStubReference(GVFlags))
14020       return false;
14021
14022     // If BaseGV requires a register for the PIC base, we cannot also have a
14023     // BaseReg specified.
14024     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14025       return false;
14026
14027     // If lower 4G is not available, then we must use rip-relative addressing.
14028     if ((M != CodeModel::Small || R != Reloc::Static) &&
14029         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14030       return false;
14031   }
14032
14033   switch (AM.Scale) {
14034   case 0:
14035   case 1:
14036   case 2:
14037   case 4:
14038   case 8:
14039     // These scales always work.
14040     break;
14041   case 3:
14042   case 5:
14043   case 9:
14044     // These scales are formed with basereg+scalereg.  Only accept if there is
14045     // no basereg yet.
14046     if (AM.HasBaseReg)
14047       return false;
14048     break;
14049   default:  // Other stuff never works.
14050     return false;
14051   }
14052
14053   return true;
14054 }
14055
14056 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14057   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14058     return false;
14059   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14060   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14061   return NumBits1 > NumBits2;
14062 }
14063
14064 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14065   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14066     return false;
14067
14068   if (!isTypeLegal(EVT::getEVT(Ty1)))
14069     return false;
14070
14071   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14072
14073   // Assuming the caller doesn't have a zeroext or signext return parameter,
14074   // truncation all the way down to i1 is valid.
14075   return true;
14076 }
14077
14078 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14079   return isInt<32>(Imm);
14080 }
14081
14082 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14083   // Can also use sub to handle negated immediates.
14084   return isInt<32>(Imm);
14085 }
14086
14087 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14088   if (!VT1.isInteger() || !VT2.isInteger())
14089     return false;
14090   unsigned NumBits1 = VT1.getSizeInBits();
14091   unsigned NumBits2 = VT2.getSizeInBits();
14092   return NumBits1 > NumBits2;
14093 }
14094
14095 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14096   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14097   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14098 }
14099
14100 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14101   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14102   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14103 }
14104
14105 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14106   EVT VT1 = Val.getValueType();
14107   if (isZExtFree(VT1, VT2))
14108     return true;
14109
14110   if (Val.getOpcode() != ISD::LOAD)
14111     return false;
14112
14113   if (!VT1.isSimple() || !VT1.isInteger() ||
14114       !VT2.isSimple() || !VT2.isInteger())
14115     return false;
14116
14117   switch (VT1.getSimpleVT().SimpleTy) {
14118   default: break;
14119   case MVT::i8:
14120   case MVT::i16:
14121   case MVT::i32:
14122     // X86 has 8, 16, and 32-bit zero-extending loads.
14123     return true;
14124   }
14125
14126   return false;
14127 }
14128
14129 bool
14130 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14131   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14132     return false;
14133
14134   VT = VT.getScalarType();
14135
14136   if (!VT.isSimple())
14137     return false;
14138
14139   switch (VT.getSimpleVT().SimpleTy) {
14140   case MVT::f32:
14141   case MVT::f64:
14142     return true;
14143   default:
14144     break;
14145   }
14146
14147   return false;
14148 }
14149
14150 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14151   // i16 instructions are longer (0x66 prefix) and potentially slower.
14152   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14153 }
14154
14155 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14156 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14157 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14158 /// are assumed to be legal.
14159 bool
14160 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14161                                       EVT VT) const {
14162   if (!VT.isSimple())
14163     return false;
14164
14165   MVT SVT = VT.getSimpleVT();
14166
14167   // Very little shuffling can be done for 64-bit vectors right now.
14168   if (VT.getSizeInBits() == 64)
14169     return false;
14170
14171   // FIXME: pshufb, blends, shifts.
14172   return (SVT.getVectorNumElements() == 2 ||
14173           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14174           isMOVLMask(M, SVT) ||
14175           isSHUFPMask(M, SVT) ||
14176           isPSHUFDMask(M, SVT) ||
14177           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14178           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14179           isPALIGNRMask(M, SVT, Subtarget) ||
14180           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14181           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14182           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14183           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14184 }
14185
14186 bool
14187 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14188                                           EVT VT) const {
14189   if (!VT.isSimple())
14190     return false;
14191
14192   MVT SVT = VT.getSimpleVT();
14193   unsigned NumElts = SVT.getVectorNumElements();
14194   // FIXME: This collection of masks seems suspect.
14195   if (NumElts == 2)
14196     return true;
14197   if (NumElts == 4 && SVT.is128BitVector()) {
14198     return (isMOVLMask(Mask, SVT)  ||
14199             isCommutedMOVLMask(Mask, SVT, true) ||
14200             isSHUFPMask(Mask, SVT) ||
14201             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14202   }
14203   return false;
14204 }
14205
14206 //===----------------------------------------------------------------------===//
14207 //                           X86 Scheduler Hooks
14208 //===----------------------------------------------------------------------===//
14209
14210 /// Utility function to emit xbegin specifying the start of an RTM region.
14211 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14212                                      const TargetInstrInfo *TII) {
14213   DebugLoc DL = MI->getDebugLoc();
14214
14215   const BasicBlock *BB = MBB->getBasicBlock();
14216   MachineFunction::iterator I = MBB;
14217   ++I;
14218
14219   // For the v = xbegin(), we generate
14220   //
14221   // thisMBB:
14222   //  xbegin sinkMBB
14223   //
14224   // mainMBB:
14225   //  eax = -1
14226   //
14227   // sinkMBB:
14228   //  v = eax
14229
14230   MachineBasicBlock *thisMBB = MBB;
14231   MachineFunction *MF = MBB->getParent();
14232   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14233   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14234   MF->insert(I, mainMBB);
14235   MF->insert(I, sinkMBB);
14236
14237   // Transfer the remainder of BB and its successor edges to sinkMBB.
14238   sinkMBB->splice(sinkMBB->begin(), MBB,
14239                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14240   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14241
14242   // thisMBB:
14243   //  xbegin sinkMBB
14244   //  # fallthrough to mainMBB
14245   //  # abortion to sinkMBB
14246   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14247   thisMBB->addSuccessor(mainMBB);
14248   thisMBB->addSuccessor(sinkMBB);
14249
14250   // mainMBB:
14251   //  EAX = -1
14252   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14253   mainMBB->addSuccessor(sinkMBB);
14254
14255   // sinkMBB:
14256   // EAX is live into the sinkMBB
14257   sinkMBB->addLiveIn(X86::EAX);
14258   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14259           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14260     .addReg(X86::EAX);
14261
14262   MI->eraseFromParent();
14263   return sinkMBB;
14264 }
14265
14266 // Get CMPXCHG opcode for the specified data type.
14267 static unsigned getCmpXChgOpcode(EVT VT) {
14268   switch (VT.getSimpleVT().SimpleTy) {
14269   case MVT::i8:  return X86::LCMPXCHG8;
14270   case MVT::i16: return X86::LCMPXCHG16;
14271   case MVT::i32: return X86::LCMPXCHG32;
14272   case MVT::i64: return X86::LCMPXCHG64;
14273   default:
14274     break;
14275   }
14276   llvm_unreachable("Invalid operand size!");
14277 }
14278
14279 // Get LOAD opcode for the specified data type.
14280 static unsigned getLoadOpcode(EVT VT) {
14281   switch (VT.getSimpleVT().SimpleTy) {
14282   case MVT::i8:  return X86::MOV8rm;
14283   case MVT::i16: return X86::MOV16rm;
14284   case MVT::i32: return X86::MOV32rm;
14285   case MVT::i64: return X86::MOV64rm;
14286   default:
14287     break;
14288   }
14289   llvm_unreachable("Invalid operand size!");
14290 }
14291
14292 // Get opcode of the non-atomic one from the specified atomic instruction.
14293 static unsigned getNonAtomicOpcode(unsigned Opc) {
14294   switch (Opc) {
14295   case X86::ATOMAND8:  return X86::AND8rr;
14296   case X86::ATOMAND16: return X86::AND16rr;
14297   case X86::ATOMAND32: return X86::AND32rr;
14298   case X86::ATOMAND64: return X86::AND64rr;
14299   case X86::ATOMOR8:   return X86::OR8rr;
14300   case X86::ATOMOR16:  return X86::OR16rr;
14301   case X86::ATOMOR32:  return X86::OR32rr;
14302   case X86::ATOMOR64:  return X86::OR64rr;
14303   case X86::ATOMXOR8:  return X86::XOR8rr;
14304   case X86::ATOMXOR16: return X86::XOR16rr;
14305   case X86::ATOMXOR32: return X86::XOR32rr;
14306   case X86::ATOMXOR64: return X86::XOR64rr;
14307   }
14308   llvm_unreachable("Unhandled atomic-load-op opcode!");
14309 }
14310
14311 // Get opcode of the non-atomic one from the specified atomic instruction with
14312 // extra opcode.
14313 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14314                                                unsigned &ExtraOpc) {
14315   switch (Opc) {
14316   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14317   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14318   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14319   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14320   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14321   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14322   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14323   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14324   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14325   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14326   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14327   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14328   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14329   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14330   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14331   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14332   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14333   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14334   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14335   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14336   }
14337   llvm_unreachable("Unhandled atomic-load-op opcode!");
14338 }
14339
14340 // Get opcode of the non-atomic one from the specified atomic instruction for
14341 // 64-bit data type on 32-bit target.
14342 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14343   switch (Opc) {
14344   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14345   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14346   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14347   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14348   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14349   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14350   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14351   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14352   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14353   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14354   }
14355   llvm_unreachable("Unhandled atomic-load-op opcode!");
14356 }
14357
14358 // Get opcode of the non-atomic one from the specified atomic instruction for
14359 // 64-bit data type on 32-bit target with extra opcode.
14360 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14361                                                    unsigned &HiOpc,
14362                                                    unsigned &ExtraOpc) {
14363   switch (Opc) {
14364   case X86::ATOMNAND6432:
14365     ExtraOpc = X86::NOT32r;
14366     HiOpc = X86::AND32rr;
14367     return X86::AND32rr;
14368   }
14369   llvm_unreachable("Unhandled atomic-load-op opcode!");
14370 }
14371
14372 // Get pseudo CMOV opcode from the specified data type.
14373 static unsigned getPseudoCMOVOpc(EVT VT) {
14374   switch (VT.getSimpleVT().SimpleTy) {
14375   case MVT::i8:  return X86::CMOV_GR8;
14376   case MVT::i16: return X86::CMOV_GR16;
14377   case MVT::i32: return X86::CMOV_GR32;
14378   default:
14379     break;
14380   }
14381   llvm_unreachable("Unknown CMOV opcode!");
14382 }
14383
14384 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14385 // They will be translated into a spin-loop or compare-exchange loop from
14386 //
14387 //    ...
14388 //    dst = atomic-fetch-op MI.addr, MI.val
14389 //    ...
14390 //
14391 // to
14392 //
14393 //    ...
14394 //    t1 = LOAD MI.addr
14395 // loop:
14396 //    t4 = phi(t1, t3 / loop)
14397 //    t2 = OP MI.val, t4
14398 //    EAX = t4
14399 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14400 //    t3 = EAX
14401 //    JNE loop
14402 // sink:
14403 //    dst = t3
14404 //    ...
14405 MachineBasicBlock *
14406 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14407                                        MachineBasicBlock *MBB) const {
14408   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14409   DebugLoc DL = MI->getDebugLoc();
14410
14411   MachineFunction *MF = MBB->getParent();
14412   MachineRegisterInfo &MRI = MF->getRegInfo();
14413
14414   const BasicBlock *BB = MBB->getBasicBlock();
14415   MachineFunction::iterator I = MBB;
14416   ++I;
14417
14418   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14419          "Unexpected number of operands");
14420
14421   assert(MI->hasOneMemOperand() &&
14422          "Expected atomic-load-op to have one memoperand");
14423
14424   // Memory Reference
14425   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14426   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14427
14428   unsigned DstReg, SrcReg;
14429   unsigned MemOpndSlot;
14430
14431   unsigned CurOp = 0;
14432
14433   DstReg = MI->getOperand(CurOp++).getReg();
14434   MemOpndSlot = CurOp;
14435   CurOp += X86::AddrNumOperands;
14436   SrcReg = MI->getOperand(CurOp++).getReg();
14437
14438   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14439   MVT::SimpleValueType VT = *RC->vt_begin();
14440   unsigned t1 = MRI.createVirtualRegister(RC);
14441   unsigned t2 = MRI.createVirtualRegister(RC);
14442   unsigned t3 = MRI.createVirtualRegister(RC);
14443   unsigned t4 = MRI.createVirtualRegister(RC);
14444   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14445
14446   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14447   unsigned LOADOpc = getLoadOpcode(VT);
14448
14449   // For the atomic load-arith operator, we generate
14450   //
14451   //  thisMBB:
14452   //    t1 = LOAD [MI.addr]
14453   //  mainMBB:
14454   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14455   //    t1 = OP MI.val, EAX
14456   //    EAX = t4
14457   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14458   //    t3 = EAX
14459   //    JNE mainMBB
14460   //  sinkMBB:
14461   //    dst = t3
14462
14463   MachineBasicBlock *thisMBB = MBB;
14464   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14465   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14466   MF->insert(I, mainMBB);
14467   MF->insert(I, sinkMBB);
14468
14469   MachineInstrBuilder MIB;
14470
14471   // Transfer the remainder of BB and its successor edges to sinkMBB.
14472   sinkMBB->splice(sinkMBB->begin(), MBB,
14473                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14474   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14475
14476   // thisMBB:
14477   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14478   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14479     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14480     if (NewMO.isReg())
14481       NewMO.setIsKill(false);
14482     MIB.addOperand(NewMO);
14483   }
14484   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14485     unsigned flags = (*MMOI)->getFlags();
14486     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14487     MachineMemOperand *MMO =
14488       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14489                                (*MMOI)->getSize(),
14490                                (*MMOI)->getBaseAlignment(),
14491                                (*MMOI)->getTBAAInfo(),
14492                                (*MMOI)->getRanges());
14493     MIB.addMemOperand(MMO);
14494   }
14495
14496   thisMBB->addSuccessor(mainMBB);
14497
14498   // mainMBB:
14499   MachineBasicBlock *origMainMBB = mainMBB;
14500
14501   // Add a PHI.
14502   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14503                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14504
14505   unsigned Opc = MI->getOpcode();
14506   switch (Opc) {
14507   default:
14508     llvm_unreachable("Unhandled atomic-load-op opcode!");
14509   case X86::ATOMAND8:
14510   case X86::ATOMAND16:
14511   case X86::ATOMAND32:
14512   case X86::ATOMAND64:
14513   case X86::ATOMOR8:
14514   case X86::ATOMOR16:
14515   case X86::ATOMOR32:
14516   case X86::ATOMOR64:
14517   case X86::ATOMXOR8:
14518   case X86::ATOMXOR16:
14519   case X86::ATOMXOR32:
14520   case X86::ATOMXOR64: {
14521     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14522     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14523       .addReg(t4);
14524     break;
14525   }
14526   case X86::ATOMNAND8:
14527   case X86::ATOMNAND16:
14528   case X86::ATOMNAND32:
14529   case X86::ATOMNAND64: {
14530     unsigned Tmp = MRI.createVirtualRegister(RC);
14531     unsigned NOTOpc;
14532     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14533     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14534       .addReg(t4);
14535     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14536     break;
14537   }
14538   case X86::ATOMMAX8:
14539   case X86::ATOMMAX16:
14540   case X86::ATOMMAX32:
14541   case X86::ATOMMAX64:
14542   case X86::ATOMMIN8:
14543   case X86::ATOMMIN16:
14544   case X86::ATOMMIN32:
14545   case X86::ATOMMIN64:
14546   case X86::ATOMUMAX8:
14547   case X86::ATOMUMAX16:
14548   case X86::ATOMUMAX32:
14549   case X86::ATOMUMAX64:
14550   case X86::ATOMUMIN8:
14551   case X86::ATOMUMIN16:
14552   case X86::ATOMUMIN32:
14553   case X86::ATOMUMIN64: {
14554     unsigned CMPOpc;
14555     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14556
14557     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14558       .addReg(SrcReg)
14559       .addReg(t4);
14560
14561     if (Subtarget->hasCMov()) {
14562       if (VT != MVT::i8) {
14563         // Native support
14564         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14565           .addReg(SrcReg)
14566           .addReg(t4);
14567       } else {
14568         // Promote i8 to i32 to use CMOV32
14569         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14570         const TargetRegisterClass *RC32 =
14571           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14572         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14573         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14574         unsigned Tmp = MRI.createVirtualRegister(RC32);
14575
14576         unsigned Undef = MRI.createVirtualRegister(RC32);
14577         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14578
14579         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14580           .addReg(Undef)
14581           .addReg(SrcReg)
14582           .addImm(X86::sub_8bit);
14583         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14584           .addReg(Undef)
14585           .addReg(t4)
14586           .addImm(X86::sub_8bit);
14587
14588         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14589           .addReg(SrcReg32)
14590           .addReg(AccReg32);
14591
14592         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14593           .addReg(Tmp, 0, X86::sub_8bit);
14594       }
14595     } else {
14596       // Use pseudo select and lower them.
14597       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14598              "Invalid atomic-load-op transformation!");
14599       unsigned SelOpc = getPseudoCMOVOpc(VT);
14600       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14601       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14602       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14603               .addReg(SrcReg).addReg(t4)
14604               .addImm(CC);
14605       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14606       // Replace the original PHI node as mainMBB is changed after CMOV
14607       // lowering.
14608       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14609         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14610       Phi->eraseFromParent();
14611     }
14612     break;
14613   }
14614   }
14615
14616   // Copy PhyReg back from virtual register.
14617   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14618     .addReg(t4);
14619
14620   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14621   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14622     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14623     if (NewMO.isReg())
14624       NewMO.setIsKill(false);
14625     MIB.addOperand(NewMO);
14626   }
14627   MIB.addReg(t2);
14628   MIB.setMemRefs(MMOBegin, MMOEnd);
14629
14630   // Copy PhyReg back to virtual register.
14631   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14632     .addReg(PhyReg);
14633
14634   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14635
14636   mainMBB->addSuccessor(origMainMBB);
14637   mainMBB->addSuccessor(sinkMBB);
14638
14639   // sinkMBB:
14640   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14641           TII->get(TargetOpcode::COPY), DstReg)
14642     .addReg(t3);
14643
14644   MI->eraseFromParent();
14645   return sinkMBB;
14646 }
14647
14648 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14649 // instructions. They will be translated into a spin-loop or compare-exchange
14650 // loop from
14651 //
14652 //    ...
14653 //    dst = atomic-fetch-op MI.addr, MI.val
14654 //    ...
14655 //
14656 // to
14657 //
14658 //    ...
14659 //    t1L = LOAD [MI.addr + 0]
14660 //    t1H = LOAD [MI.addr + 4]
14661 // loop:
14662 //    t4L = phi(t1L, t3L / loop)
14663 //    t4H = phi(t1H, t3H / loop)
14664 //    t2L = OP MI.val.lo, t4L
14665 //    t2H = OP MI.val.hi, t4H
14666 //    EAX = t4L
14667 //    EDX = t4H
14668 //    EBX = t2L
14669 //    ECX = t2H
14670 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14671 //    t3L = EAX
14672 //    t3H = EDX
14673 //    JNE loop
14674 // sink:
14675 //    dstL = t3L
14676 //    dstH = t3H
14677 //    ...
14678 MachineBasicBlock *
14679 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14680                                            MachineBasicBlock *MBB) const {
14681   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14682   DebugLoc DL = MI->getDebugLoc();
14683
14684   MachineFunction *MF = MBB->getParent();
14685   MachineRegisterInfo &MRI = MF->getRegInfo();
14686
14687   const BasicBlock *BB = MBB->getBasicBlock();
14688   MachineFunction::iterator I = MBB;
14689   ++I;
14690
14691   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14692          "Unexpected number of operands");
14693
14694   assert(MI->hasOneMemOperand() &&
14695          "Expected atomic-load-op32 to have one memoperand");
14696
14697   // Memory Reference
14698   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14699   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14700
14701   unsigned DstLoReg, DstHiReg;
14702   unsigned SrcLoReg, SrcHiReg;
14703   unsigned MemOpndSlot;
14704
14705   unsigned CurOp = 0;
14706
14707   DstLoReg = MI->getOperand(CurOp++).getReg();
14708   DstHiReg = MI->getOperand(CurOp++).getReg();
14709   MemOpndSlot = CurOp;
14710   CurOp += X86::AddrNumOperands;
14711   SrcLoReg = MI->getOperand(CurOp++).getReg();
14712   SrcHiReg = MI->getOperand(CurOp++).getReg();
14713
14714   const TargetRegisterClass *RC = &X86::GR32RegClass;
14715   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14716
14717   unsigned t1L = MRI.createVirtualRegister(RC);
14718   unsigned t1H = MRI.createVirtualRegister(RC);
14719   unsigned t2L = MRI.createVirtualRegister(RC);
14720   unsigned t2H = MRI.createVirtualRegister(RC);
14721   unsigned t3L = MRI.createVirtualRegister(RC);
14722   unsigned t3H = MRI.createVirtualRegister(RC);
14723   unsigned t4L = MRI.createVirtualRegister(RC);
14724   unsigned t4H = MRI.createVirtualRegister(RC);
14725
14726   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14727   unsigned LOADOpc = X86::MOV32rm;
14728
14729   // For the atomic load-arith operator, we generate
14730   //
14731   //  thisMBB:
14732   //    t1L = LOAD [MI.addr + 0]
14733   //    t1H = LOAD [MI.addr + 4]
14734   //  mainMBB:
14735   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14736   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14737   //    t2L = OP MI.val.lo, t4L
14738   //    t2H = OP MI.val.hi, t4H
14739   //    EBX = t2L
14740   //    ECX = t2H
14741   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14742   //    t3L = EAX
14743   //    t3H = EDX
14744   //    JNE loop
14745   //  sinkMBB:
14746   //    dstL = t3L
14747   //    dstH = t3H
14748
14749   MachineBasicBlock *thisMBB = MBB;
14750   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14751   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14752   MF->insert(I, mainMBB);
14753   MF->insert(I, sinkMBB);
14754
14755   MachineInstrBuilder MIB;
14756
14757   // Transfer the remainder of BB and its successor edges to sinkMBB.
14758   sinkMBB->splice(sinkMBB->begin(), MBB,
14759                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14760   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14761
14762   // thisMBB:
14763   // Lo
14764   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14765   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14766     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14767     if (NewMO.isReg())
14768       NewMO.setIsKill(false);
14769     MIB.addOperand(NewMO);
14770   }
14771   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14772     unsigned flags = (*MMOI)->getFlags();
14773     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14774     MachineMemOperand *MMO =
14775       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14776                                (*MMOI)->getSize(),
14777                                (*MMOI)->getBaseAlignment(),
14778                                (*MMOI)->getTBAAInfo(),
14779                                (*MMOI)->getRanges());
14780     MIB.addMemOperand(MMO);
14781   };
14782   MachineInstr *LowMI = MIB;
14783
14784   // Hi
14785   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14786   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14787     if (i == X86::AddrDisp) {
14788       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14789     } else {
14790       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14791       if (NewMO.isReg())
14792         NewMO.setIsKill(false);
14793       MIB.addOperand(NewMO);
14794     }
14795   }
14796   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14797
14798   thisMBB->addSuccessor(mainMBB);
14799
14800   // mainMBB:
14801   MachineBasicBlock *origMainMBB = mainMBB;
14802
14803   // Add PHIs.
14804   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14805                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14806   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14807                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14808
14809   unsigned Opc = MI->getOpcode();
14810   switch (Opc) {
14811   default:
14812     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14813   case X86::ATOMAND6432:
14814   case X86::ATOMOR6432:
14815   case X86::ATOMXOR6432:
14816   case X86::ATOMADD6432:
14817   case X86::ATOMSUB6432: {
14818     unsigned HiOpc;
14819     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14820     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14821       .addReg(SrcLoReg);
14822     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14823       .addReg(SrcHiReg);
14824     break;
14825   }
14826   case X86::ATOMNAND6432: {
14827     unsigned HiOpc, NOTOpc;
14828     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14829     unsigned TmpL = MRI.createVirtualRegister(RC);
14830     unsigned TmpH = MRI.createVirtualRegister(RC);
14831     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14832       .addReg(t4L);
14833     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14834       .addReg(t4H);
14835     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14836     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14837     break;
14838   }
14839   case X86::ATOMMAX6432:
14840   case X86::ATOMMIN6432:
14841   case X86::ATOMUMAX6432:
14842   case X86::ATOMUMIN6432: {
14843     unsigned HiOpc;
14844     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14845     unsigned cL = MRI.createVirtualRegister(RC8);
14846     unsigned cH = MRI.createVirtualRegister(RC8);
14847     unsigned cL32 = MRI.createVirtualRegister(RC);
14848     unsigned cH32 = MRI.createVirtualRegister(RC);
14849     unsigned cc = MRI.createVirtualRegister(RC);
14850     // cl := cmp src_lo, lo
14851     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14852       .addReg(SrcLoReg).addReg(t4L);
14853     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14854     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14855     // ch := cmp src_hi, hi
14856     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14857       .addReg(SrcHiReg).addReg(t4H);
14858     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14859     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14860     // cc := if (src_hi == hi) ? cl : ch;
14861     if (Subtarget->hasCMov()) {
14862       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14863         .addReg(cH32).addReg(cL32);
14864     } else {
14865       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14866               .addReg(cH32).addReg(cL32)
14867               .addImm(X86::COND_E);
14868       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14869     }
14870     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14871     if (Subtarget->hasCMov()) {
14872       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14873         .addReg(SrcLoReg).addReg(t4L);
14874       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14875         .addReg(SrcHiReg).addReg(t4H);
14876     } else {
14877       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14878               .addReg(SrcLoReg).addReg(t4L)
14879               .addImm(X86::COND_NE);
14880       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14881       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14882       // 2nd CMOV lowering.
14883       mainMBB->addLiveIn(X86::EFLAGS);
14884       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14885               .addReg(SrcHiReg).addReg(t4H)
14886               .addImm(X86::COND_NE);
14887       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14888       // Replace the original PHI node as mainMBB is changed after CMOV
14889       // lowering.
14890       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14891         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14892       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14893         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14894       PhiL->eraseFromParent();
14895       PhiH->eraseFromParent();
14896     }
14897     break;
14898   }
14899   case X86::ATOMSWAP6432: {
14900     unsigned HiOpc;
14901     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14902     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14903     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14904     break;
14905   }
14906   }
14907
14908   // Copy EDX:EAX back from HiReg:LoReg
14909   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14910   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14911   // Copy ECX:EBX from t1H:t1L
14912   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14913   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14914
14915   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14916   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14917     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14918     if (NewMO.isReg())
14919       NewMO.setIsKill(false);
14920     MIB.addOperand(NewMO);
14921   }
14922   MIB.setMemRefs(MMOBegin, MMOEnd);
14923
14924   // Copy EDX:EAX back to t3H:t3L
14925   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14926   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14927
14928   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14929
14930   mainMBB->addSuccessor(origMainMBB);
14931   mainMBB->addSuccessor(sinkMBB);
14932
14933   // sinkMBB:
14934   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14935           TII->get(TargetOpcode::COPY), DstLoReg)
14936     .addReg(t3L);
14937   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14938           TII->get(TargetOpcode::COPY), DstHiReg)
14939     .addReg(t3H);
14940
14941   MI->eraseFromParent();
14942   return sinkMBB;
14943 }
14944
14945 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14946 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14947 // in the .td file.
14948 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14949                                        const TargetInstrInfo *TII) {
14950   unsigned Opc;
14951   switch (MI->getOpcode()) {
14952   default: llvm_unreachable("illegal opcode!");
14953   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14954   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14955   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14956   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14957   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14958   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14959   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14960   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14961   }
14962
14963   DebugLoc dl = MI->getDebugLoc();
14964   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14965
14966   unsigned NumArgs = MI->getNumOperands();
14967   for (unsigned i = 1; i < NumArgs; ++i) {
14968     MachineOperand &Op = MI->getOperand(i);
14969     if (!(Op.isReg() && Op.isImplicit()))
14970       MIB.addOperand(Op);
14971   }
14972   if (MI->hasOneMemOperand())
14973     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14974
14975   BuildMI(*BB, MI, dl,
14976     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14977     .addReg(X86::XMM0);
14978
14979   MI->eraseFromParent();
14980   return BB;
14981 }
14982
14983 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14984 // defs in an instruction pattern
14985 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14986                                        const TargetInstrInfo *TII) {
14987   unsigned Opc;
14988   switch (MI->getOpcode()) {
14989   default: llvm_unreachable("illegal opcode!");
14990   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14991   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14992   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14993   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14994   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14995   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14996   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14997   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14998   }
14999
15000   DebugLoc dl = MI->getDebugLoc();
15001   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15002
15003   unsigned NumArgs = MI->getNumOperands(); // remove the results
15004   for (unsigned i = 1; i < NumArgs; ++i) {
15005     MachineOperand &Op = MI->getOperand(i);
15006     if (!(Op.isReg() && Op.isImplicit()))
15007       MIB.addOperand(Op);
15008   }
15009   if (MI->hasOneMemOperand())
15010     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15011
15012   BuildMI(*BB, MI, dl,
15013     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15014     .addReg(X86::ECX);
15015
15016   MI->eraseFromParent();
15017   return BB;
15018 }
15019
15020 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15021                                        const TargetInstrInfo *TII,
15022                                        const X86Subtarget* Subtarget) {
15023   DebugLoc dl = MI->getDebugLoc();
15024
15025   // Address into RAX/EAX, other two args into ECX, EDX.
15026   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15027   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15028   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15029   for (int i = 0; i < X86::AddrNumOperands; ++i)
15030     MIB.addOperand(MI->getOperand(i));
15031
15032   unsigned ValOps = X86::AddrNumOperands;
15033   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15034     .addReg(MI->getOperand(ValOps).getReg());
15035   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15036     .addReg(MI->getOperand(ValOps+1).getReg());
15037
15038   // The instruction doesn't actually take any operands though.
15039   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15040
15041   MI->eraseFromParent(); // The pseudo is gone now.
15042   return BB;
15043 }
15044
15045 MachineBasicBlock *
15046 X86TargetLowering::EmitVAARG64WithCustomInserter(
15047                    MachineInstr *MI,
15048                    MachineBasicBlock *MBB) const {
15049   // Emit va_arg instruction on X86-64.
15050
15051   // Operands to this pseudo-instruction:
15052   // 0  ) Output        : destination address (reg)
15053   // 1-5) Input         : va_list address (addr, i64mem)
15054   // 6  ) ArgSize       : Size (in bytes) of vararg type
15055   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15056   // 8  ) Align         : Alignment of type
15057   // 9  ) EFLAGS (implicit-def)
15058
15059   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15060   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15061
15062   unsigned DestReg = MI->getOperand(0).getReg();
15063   MachineOperand &Base = MI->getOperand(1);
15064   MachineOperand &Scale = MI->getOperand(2);
15065   MachineOperand &Index = MI->getOperand(3);
15066   MachineOperand &Disp = MI->getOperand(4);
15067   MachineOperand &Segment = MI->getOperand(5);
15068   unsigned ArgSize = MI->getOperand(6).getImm();
15069   unsigned ArgMode = MI->getOperand(7).getImm();
15070   unsigned Align = MI->getOperand(8).getImm();
15071
15072   // Memory Reference
15073   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15074   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15075   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15076
15077   // Machine Information
15078   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15079   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15080   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15081   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15082   DebugLoc DL = MI->getDebugLoc();
15083
15084   // struct va_list {
15085   //   i32   gp_offset
15086   //   i32   fp_offset
15087   //   i64   overflow_area (address)
15088   //   i64   reg_save_area (address)
15089   // }
15090   // sizeof(va_list) = 24
15091   // alignment(va_list) = 8
15092
15093   unsigned TotalNumIntRegs = 6;
15094   unsigned TotalNumXMMRegs = 8;
15095   bool UseGPOffset = (ArgMode == 1);
15096   bool UseFPOffset = (ArgMode == 2);
15097   unsigned MaxOffset = TotalNumIntRegs * 8 +
15098                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15099
15100   /* Align ArgSize to a multiple of 8 */
15101   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15102   bool NeedsAlign = (Align > 8);
15103
15104   MachineBasicBlock *thisMBB = MBB;
15105   MachineBasicBlock *overflowMBB;
15106   MachineBasicBlock *offsetMBB;
15107   MachineBasicBlock *endMBB;
15108
15109   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15110   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15111   unsigned OffsetReg = 0;
15112
15113   if (!UseGPOffset && !UseFPOffset) {
15114     // If we only pull from the overflow region, we don't create a branch.
15115     // We don't need to alter control flow.
15116     OffsetDestReg = 0; // unused
15117     OverflowDestReg = DestReg;
15118
15119     offsetMBB = NULL;
15120     overflowMBB = thisMBB;
15121     endMBB = thisMBB;
15122   } else {
15123     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15124     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15125     // If not, pull from overflow_area. (branch to overflowMBB)
15126     //
15127     //       thisMBB
15128     //         |     .
15129     //         |        .
15130     //     offsetMBB   overflowMBB
15131     //         |        .
15132     //         |     .
15133     //        endMBB
15134
15135     // Registers for the PHI in endMBB
15136     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15137     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15138
15139     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15140     MachineFunction *MF = MBB->getParent();
15141     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15142     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15143     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15144
15145     MachineFunction::iterator MBBIter = MBB;
15146     ++MBBIter;
15147
15148     // Insert the new basic blocks
15149     MF->insert(MBBIter, offsetMBB);
15150     MF->insert(MBBIter, overflowMBB);
15151     MF->insert(MBBIter, endMBB);
15152
15153     // Transfer the remainder of MBB and its successor edges to endMBB.
15154     endMBB->splice(endMBB->begin(), thisMBB,
15155                     llvm::next(MachineBasicBlock::iterator(MI)),
15156                     thisMBB->end());
15157     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15158
15159     // Make offsetMBB and overflowMBB successors of thisMBB
15160     thisMBB->addSuccessor(offsetMBB);
15161     thisMBB->addSuccessor(overflowMBB);
15162
15163     // endMBB is a successor of both offsetMBB and overflowMBB
15164     offsetMBB->addSuccessor(endMBB);
15165     overflowMBB->addSuccessor(endMBB);
15166
15167     // Load the offset value into a register
15168     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15169     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15170       .addOperand(Base)
15171       .addOperand(Scale)
15172       .addOperand(Index)
15173       .addDisp(Disp, UseFPOffset ? 4 : 0)
15174       .addOperand(Segment)
15175       .setMemRefs(MMOBegin, MMOEnd);
15176
15177     // Check if there is enough room left to pull this argument.
15178     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15179       .addReg(OffsetReg)
15180       .addImm(MaxOffset + 8 - ArgSizeA8);
15181
15182     // Branch to "overflowMBB" if offset >= max
15183     // Fall through to "offsetMBB" otherwise
15184     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15185       .addMBB(overflowMBB);
15186   }
15187
15188   // In offsetMBB, emit code to use the reg_save_area.
15189   if (offsetMBB) {
15190     assert(OffsetReg != 0);
15191
15192     // Read the reg_save_area address.
15193     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15194     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15195       .addOperand(Base)
15196       .addOperand(Scale)
15197       .addOperand(Index)
15198       .addDisp(Disp, 16)
15199       .addOperand(Segment)
15200       .setMemRefs(MMOBegin, MMOEnd);
15201
15202     // Zero-extend the offset
15203     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15204       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15205         .addImm(0)
15206         .addReg(OffsetReg)
15207         .addImm(X86::sub_32bit);
15208
15209     // Add the offset to the reg_save_area to get the final address.
15210     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15211       .addReg(OffsetReg64)
15212       .addReg(RegSaveReg);
15213
15214     // Compute the offset for the next argument
15215     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15216     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15217       .addReg(OffsetReg)
15218       .addImm(UseFPOffset ? 16 : 8);
15219
15220     // Store it back into the va_list.
15221     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15222       .addOperand(Base)
15223       .addOperand(Scale)
15224       .addOperand(Index)
15225       .addDisp(Disp, UseFPOffset ? 4 : 0)
15226       .addOperand(Segment)
15227       .addReg(NextOffsetReg)
15228       .setMemRefs(MMOBegin, MMOEnd);
15229
15230     // Jump to endMBB
15231     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15232       .addMBB(endMBB);
15233   }
15234
15235   //
15236   // Emit code to use overflow area
15237   //
15238
15239   // Load the overflow_area address into a register.
15240   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15241   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15242     .addOperand(Base)
15243     .addOperand(Scale)
15244     .addOperand(Index)
15245     .addDisp(Disp, 8)
15246     .addOperand(Segment)
15247     .setMemRefs(MMOBegin, MMOEnd);
15248
15249   // If we need to align it, do so. Otherwise, just copy the address
15250   // to OverflowDestReg.
15251   if (NeedsAlign) {
15252     // Align the overflow address
15253     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15254     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15255
15256     // aligned_addr = (addr + (align-1)) & ~(align-1)
15257     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15258       .addReg(OverflowAddrReg)
15259       .addImm(Align-1);
15260
15261     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15262       .addReg(TmpReg)
15263       .addImm(~(uint64_t)(Align-1));
15264   } else {
15265     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15266       .addReg(OverflowAddrReg);
15267   }
15268
15269   // Compute the next overflow address after this argument.
15270   // (the overflow address should be kept 8-byte aligned)
15271   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15272   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15273     .addReg(OverflowDestReg)
15274     .addImm(ArgSizeA8);
15275
15276   // Store the new overflow address.
15277   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15278     .addOperand(Base)
15279     .addOperand(Scale)
15280     .addOperand(Index)
15281     .addDisp(Disp, 8)
15282     .addOperand(Segment)
15283     .addReg(NextAddrReg)
15284     .setMemRefs(MMOBegin, MMOEnd);
15285
15286   // If we branched, emit the PHI to the front of endMBB.
15287   if (offsetMBB) {
15288     BuildMI(*endMBB, endMBB->begin(), DL,
15289             TII->get(X86::PHI), DestReg)
15290       .addReg(OffsetDestReg).addMBB(offsetMBB)
15291       .addReg(OverflowDestReg).addMBB(overflowMBB);
15292   }
15293
15294   // Erase the pseudo instruction
15295   MI->eraseFromParent();
15296
15297   return endMBB;
15298 }
15299
15300 MachineBasicBlock *
15301 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15302                                                  MachineInstr *MI,
15303                                                  MachineBasicBlock *MBB) const {
15304   // Emit code to save XMM registers to the stack. The ABI says that the
15305   // number of registers to save is given in %al, so it's theoretically
15306   // possible to do an indirect jump trick to avoid saving all of them,
15307   // however this code takes a simpler approach and just executes all
15308   // of the stores if %al is non-zero. It's less code, and it's probably
15309   // easier on the hardware branch predictor, and stores aren't all that
15310   // expensive anyway.
15311
15312   // Create the new basic blocks. One block contains all the XMM stores,
15313   // and one block is the final destination regardless of whether any
15314   // stores were performed.
15315   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15316   MachineFunction *F = MBB->getParent();
15317   MachineFunction::iterator MBBIter = MBB;
15318   ++MBBIter;
15319   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15320   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15321   F->insert(MBBIter, XMMSaveMBB);
15322   F->insert(MBBIter, EndMBB);
15323
15324   // Transfer the remainder of MBB and its successor edges to EndMBB.
15325   EndMBB->splice(EndMBB->begin(), MBB,
15326                  llvm::next(MachineBasicBlock::iterator(MI)),
15327                  MBB->end());
15328   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15329
15330   // The original block will now fall through to the XMM save block.
15331   MBB->addSuccessor(XMMSaveMBB);
15332   // The XMMSaveMBB will fall through to the end block.
15333   XMMSaveMBB->addSuccessor(EndMBB);
15334
15335   // Now add the instructions.
15336   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15337   DebugLoc DL = MI->getDebugLoc();
15338
15339   unsigned CountReg = MI->getOperand(0).getReg();
15340   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15341   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15342
15343   if (!Subtarget->isTargetWin64()) {
15344     // If %al is 0, branch around the XMM save block.
15345     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15346     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15347     MBB->addSuccessor(EndMBB);
15348   }
15349
15350   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15351   // that was just emitted, but clearly shouldn't be "saved".
15352   assert((MI->getNumOperands() <= 3 ||
15353           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15354           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15355          && "Expected last argument to be EFLAGS");
15356   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15357   // In the XMM save block, save all the XMM argument registers.
15358   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15359     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15360     MachineMemOperand *MMO =
15361       F->getMachineMemOperand(
15362           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15363         MachineMemOperand::MOStore,
15364         /*Size=*/16, /*Align=*/16);
15365     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15366       .addFrameIndex(RegSaveFrameIndex)
15367       .addImm(/*Scale=*/1)
15368       .addReg(/*IndexReg=*/0)
15369       .addImm(/*Disp=*/Offset)
15370       .addReg(/*Segment=*/0)
15371       .addReg(MI->getOperand(i).getReg())
15372       .addMemOperand(MMO);
15373   }
15374
15375   MI->eraseFromParent();   // The pseudo instruction is gone now.
15376
15377   return EndMBB;
15378 }
15379
15380 // The EFLAGS operand of SelectItr might be missing a kill marker
15381 // because there were multiple uses of EFLAGS, and ISel didn't know
15382 // which to mark. Figure out whether SelectItr should have had a
15383 // kill marker, and set it if it should. Returns the correct kill
15384 // marker value.
15385 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15386                                      MachineBasicBlock* BB,
15387                                      const TargetRegisterInfo* TRI) {
15388   // Scan forward through BB for a use/def of EFLAGS.
15389   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
15390   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15391     const MachineInstr& mi = *miI;
15392     if (mi.readsRegister(X86::EFLAGS))
15393       return false;
15394     if (mi.definesRegister(X86::EFLAGS))
15395       break; // Should have kill-flag - update below.
15396   }
15397
15398   // If we hit the end of the block, check whether EFLAGS is live into a
15399   // successor.
15400   if (miI == BB->end()) {
15401     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15402                                           sEnd = BB->succ_end();
15403          sItr != sEnd; ++sItr) {
15404       MachineBasicBlock* succ = *sItr;
15405       if (succ->isLiveIn(X86::EFLAGS))
15406         return false;
15407     }
15408   }
15409
15410   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15411   // out. SelectMI should have a kill flag on EFLAGS.
15412   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15413   return true;
15414 }
15415
15416 MachineBasicBlock *
15417 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15418                                      MachineBasicBlock *BB) const {
15419   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15420   DebugLoc DL = MI->getDebugLoc();
15421
15422   // To "insert" a SELECT_CC instruction, we actually have to insert the
15423   // diamond control-flow pattern.  The incoming instruction knows the
15424   // destination vreg to set, the condition code register to branch on, the
15425   // true/false values to select between, and a branch opcode to use.
15426   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15427   MachineFunction::iterator It = BB;
15428   ++It;
15429
15430   //  thisMBB:
15431   //  ...
15432   //   TrueVal = ...
15433   //   cmpTY ccX, r1, r2
15434   //   bCC copy1MBB
15435   //   fallthrough --> copy0MBB
15436   MachineBasicBlock *thisMBB = BB;
15437   MachineFunction *F = BB->getParent();
15438   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15439   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15440   F->insert(It, copy0MBB);
15441   F->insert(It, sinkMBB);
15442
15443   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15444   // live into the sink and copy blocks.
15445   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15446   if (!MI->killsRegister(X86::EFLAGS) &&
15447       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15448     copy0MBB->addLiveIn(X86::EFLAGS);
15449     sinkMBB->addLiveIn(X86::EFLAGS);
15450   }
15451
15452   // Transfer the remainder of BB and its successor edges to sinkMBB.
15453   sinkMBB->splice(sinkMBB->begin(), BB,
15454                   llvm::next(MachineBasicBlock::iterator(MI)),
15455                   BB->end());
15456   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15457
15458   // Add the true and fallthrough blocks as its successors.
15459   BB->addSuccessor(copy0MBB);
15460   BB->addSuccessor(sinkMBB);
15461
15462   // Create the conditional branch instruction.
15463   unsigned Opc =
15464     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15465   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15466
15467   //  copy0MBB:
15468   //   %FalseValue = ...
15469   //   # fallthrough to sinkMBB
15470   copy0MBB->addSuccessor(sinkMBB);
15471
15472   //  sinkMBB:
15473   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15474   //  ...
15475   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15476           TII->get(X86::PHI), MI->getOperand(0).getReg())
15477     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15478     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15479
15480   MI->eraseFromParent();   // The pseudo instruction is gone now.
15481   return sinkMBB;
15482 }
15483
15484 MachineBasicBlock *
15485 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15486                                         bool Is64Bit) const {
15487   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15488   DebugLoc DL = MI->getDebugLoc();
15489   MachineFunction *MF = BB->getParent();
15490   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15491
15492   assert(getTargetMachine().Options.EnableSegmentedStacks);
15493
15494   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15495   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15496
15497   // BB:
15498   //  ... [Till the alloca]
15499   // If stacklet is not large enough, jump to mallocMBB
15500   //
15501   // bumpMBB:
15502   //  Allocate by subtracting from RSP
15503   //  Jump to continueMBB
15504   //
15505   // mallocMBB:
15506   //  Allocate by call to runtime
15507   //
15508   // continueMBB:
15509   //  ...
15510   //  [rest of original BB]
15511   //
15512
15513   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15514   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15515   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15516
15517   MachineRegisterInfo &MRI = MF->getRegInfo();
15518   const TargetRegisterClass *AddrRegClass =
15519     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15520
15521   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15522     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15523     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15524     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15525     sizeVReg = MI->getOperand(1).getReg(),
15526     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15527
15528   MachineFunction::iterator MBBIter = BB;
15529   ++MBBIter;
15530
15531   MF->insert(MBBIter, bumpMBB);
15532   MF->insert(MBBIter, mallocMBB);
15533   MF->insert(MBBIter, continueMBB);
15534
15535   continueMBB->splice(continueMBB->begin(), BB, llvm::next
15536                       (MachineBasicBlock::iterator(MI)), BB->end());
15537   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15538
15539   // Add code to the main basic block to check if the stack limit has been hit,
15540   // and if so, jump to mallocMBB otherwise to bumpMBB.
15541   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15542   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15543     .addReg(tmpSPVReg).addReg(sizeVReg);
15544   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15545     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15546     .addReg(SPLimitVReg);
15547   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15548
15549   // bumpMBB simply decreases the stack pointer, since we know the current
15550   // stacklet has enough space.
15551   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15552     .addReg(SPLimitVReg);
15553   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15554     .addReg(SPLimitVReg);
15555   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15556
15557   // Calls into a routine in libgcc to allocate more space from the heap.
15558   const uint32_t *RegMask =
15559     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15560   if (Is64Bit) {
15561     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15562       .addReg(sizeVReg);
15563     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15564       .addExternalSymbol("__morestack_allocate_stack_space")
15565       .addRegMask(RegMask)
15566       .addReg(X86::RDI, RegState::Implicit)
15567       .addReg(X86::RAX, RegState::ImplicitDefine);
15568   } else {
15569     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15570       .addImm(12);
15571     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15572     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15573       .addExternalSymbol("__morestack_allocate_stack_space")
15574       .addRegMask(RegMask)
15575       .addReg(X86::EAX, RegState::ImplicitDefine);
15576   }
15577
15578   if (!Is64Bit)
15579     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15580       .addImm(16);
15581
15582   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15583     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15584   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15585
15586   // Set up the CFG correctly.
15587   BB->addSuccessor(bumpMBB);
15588   BB->addSuccessor(mallocMBB);
15589   mallocMBB->addSuccessor(continueMBB);
15590   bumpMBB->addSuccessor(continueMBB);
15591
15592   // Take care of the PHI nodes.
15593   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15594           MI->getOperand(0).getReg())
15595     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15596     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15597
15598   // Delete the original pseudo instruction.
15599   MI->eraseFromParent();
15600
15601   // And we're done.
15602   return continueMBB;
15603 }
15604
15605 MachineBasicBlock *
15606 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15607                                           MachineBasicBlock *BB) const {
15608   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15609   DebugLoc DL = MI->getDebugLoc();
15610
15611   assert(!Subtarget->isTargetMacho());
15612
15613   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15614   // non-trivial part is impdef of ESP.
15615
15616   if (Subtarget->isTargetWin64()) {
15617     if (Subtarget->isTargetCygMing()) {
15618       // ___chkstk(Mingw64):
15619       // Clobbers R10, R11, RAX and EFLAGS.
15620       // Updates RSP.
15621       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15622         .addExternalSymbol("___chkstk")
15623         .addReg(X86::RAX, RegState::Implicit)
15624         .addReg(X86::RSP, RegState::Implicit)
15625         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15626         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15627         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15628     } else {
15629       // __chkstk(MSVCRT): does not update stack pointer.
15630       // Clobbers R10, R11 and EFLAGS.
15631       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15632         .addExternalSymbol("__chkstk")
15633         .addReg(X86::RAX, RegState::Implicit)
15634         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15635       // RAX has the offset to be subtracted from RSP.
15636       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15637         .addReg(X86::RSP)
15638         .addReg(X86::RAX);
15639     }
15640   } else {
15641     const char *StackProbeSymbol =
15642       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15643
15644     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15645       .addExternalSymbol(StackProbeSymbol)
15646       .addReg(X86::EAX, RegState::Implicit)
15647       .addReg(X86::ESP, RegState::Implicit)
15648       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15649       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15650       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15651   }
15652
15653   MI->eraseFromParent();   // The pseudo instruction is gone now.
15654   return BB;
15655 }
15656
15657 MachineBasicBlock *
15658 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15659                                       MachineBasicBlock *BB) const {
15660   // This is pretty easy.  We're taking the value that we received from
15661   // our load from the relocation, sticking it in either RDI (x86-64)
15662   // or EAX and doing an indirect call.  The return value will then
15663   // be in the normal return register.
15664   const X86InstrInfo *TII
15665     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15666   DebugLoc DL = MI->getDebugLoc();
15667   MachineFunction *F = BB->getParent();
15668
15669   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15670   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15671
15672   // Get a register mask for the lowered call.
15673   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15674   // proper register mask.
15675   const uint32_t *RegMask =
15676     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15677   if (Subtarget->is64Bit()) {
15678     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15679                                       TII->get(X86::MOV64rm), X86::RDI)
15680     .addReg(X86::RIP)
15681     .addImm(0).addReg(0)
15682     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15683                       MI->getOperand(3).getTargetFlags())
15684     .addReg(0);
15685     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15686     addDirectMem(MIB, X86::RDI);
15687     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15688   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15689     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15690                                       TII->get(X86::MOV32rm), X86::EAX)
15691     .addReg(0)
15692     .addImm(0).addReg(0)
15693     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15694                       MI->getOperand(3).getTargetFlags())
15695     .addReg(0);
15696     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15697     addDirectMem(MIB, X86::EAX);
15698     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15699   } else {
15700     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15701                                       TII->get(X86::MOV32rm), X86::EAX)
15702     .addReg(TII->getGlobalBaseReg(F))
15703     .addImm(0).addReg(0)
15704     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15705                       MI->getOperand(3).getTargetFlags())
15706     .addReg(0);
15707     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15708     addDirectMem(MIB, X86::EAX);
15709     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15710   }
15711
15712   MI->eraseFromParent(); // The pseudo instruction is gone now.
15713   return BB;
15714 }
15715
15716 MachineBasicBlock *
15717 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15718                                     MachineBasicBlock *MBB) const {
15719   DebugLoc DL = MI->getDebugLoc();
15720   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15721
15722   MachineFunction *MF = MBB->getParent();
15723   MachineRegisterInfo &MRI = MF->getRegInfo();
15724
15725   const BasicBlock *BB = MBB->getBasicBlock();
15726   MachineFunction::iterator I = MBB;
15727   ++I;
15728
15729   // Memory Reference
15730   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15731   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15732
15733   unsigned DstReg;
15734   unsigned MemOpndSlot = 0;
15735
15736   unsigned CurOp = 0;
15737
15738   DstReg = MI->getOperand(CurOp++).getReg();
15739   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15740   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15741   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15742   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15743
15744   MemOpndSlot = CurOp;
15745
15746   MVT PVT = getPointerTy();
15747   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15748          "Invalid Pointer Size!");
15749
15750   // For v = setjmp(buf), we generate
15751   //
15752   // thisMBB:
15753   //  buf[LabelOffset] = restoreMBB
15754   //  SjLjSetup restoreMBB
15755   //
15756   // mainMBB:
15757   //  v_main = 0
15758   //
15759   // sinkMBB:
15760   //  v = phi(main, restore)
15761   //
15762   // restoreMBB:
15763   //  v_restore = 1
15764
15765   MachineBasicBlock *thisMBB = MBB;
15766   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15767   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15768   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15769   MF->insert(I, mainMBB);
15770   MF->insert(I, sinkMBB);
15771   MF->push_back(restoreMBB);
15772
15773   MachineInstrBuilder MIB;
15774
15775   // Transfer the remainder of BB and its successor edges to sinkMBB.
15776   sinkMBB->splice(sinkMBB->begin(), MBB,
15777                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15778   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15779
15780   // thisMBB:
15781   unsigned PtrStoreOpc = 0;
15782   unsigned LabelReg = 0;
15783   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15784   Reloc::Model RM = getTargetMachine().getRelocationModel();
15785   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15786                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15787
15788   // Prepare IP either in reg or imm.
15789   if (!UseImmLabel) {
15790     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15791     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15792     LabelReg = MRI.createVirtualRegister(PtrRC);
15793     if (Subtarget->is64Bit()) {
15794       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15795               .addReg(X86::RIP)
15796               .addImm(0)
15797               .addReg(0)
15798               .addMBB(restoreMBB)
15799               .addReg(0);
15800     } else {
15801       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15802       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15803               .addReg(XII->getGlobalBaseReg(MF))
15804               .addImm(0)
15805               .addReg(0)
15806               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15807               .addReg(0);
15808     }
15809   } else
15810     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15811   // Store IP
15812   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15813   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15814     if (i == X86::AddrDisp)
15815       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15816     else
15817       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15818   }
15819   if (!UseImmLabel)
15820     MIB.addReg(LabelReg);
15821   else
15822     MIB.addMBB(restoreMBB);
15823   MIB.setMemRefs(MMOBegin, MMOEnd);
15824   // Setup
15825   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15826           .addMBB(restoreMBB);
15827
15828   const X86RegisterInfo *RegInfo =
15829     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15830   MIB.addRegMask(RegInfo->getNoPreservedMask());
15831   thisMBB->addSuccessor(mainMBB);
15832   thisMBB->addSuccessor(restoreMBB);
15833
15834   // mainMBB:
15835   //  EAX = 0
15836   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15837   mainMBB->addSuccessor(sinkMBB);
15838
15839   // sinkMBB:
15840   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15841           TII->get(X86::PHI), DstReg)
15842     .addReg(mainDstReg).addMBB(mainMBB)
15843     .addReg(restoreDstReg).addMBB(restoreMBB);
15844
15845   // restoreMBB:
15846   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15847   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15848   restoreMBB->addSuccessor(sinkMBB);
15849
15850   MI->eraseFromParent();
15851   return sinkMBB;
15852 }
15853
15854 MachineBasicBlock *
15855 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15856                                      MachineBasicBlock *MBB) const {
15857   DebugLoc DL = MI->getDebugLoc();
15858   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15859
15860   MachineFunction *MF = MBB->getParent();
15861   MachineRegisterInfo &MRI = MF->getRegInfo();
15862
15863   // Memory Reference
15864   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15865   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15866
15867   MVT PVT = getPointerTy();
15868   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15869          "Invalid Pointer Size!");
15870
15871   const TargetRegisterClass *RC =
15872     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15873   unsigned Tmp = MRI.createVirtualRegister(RC);
15874   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15875   const X86RegisterInfo *RegInfo =
15876     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15877   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15878   unsigned SP = RegInfo->getStackRegister();
15879
15880   MachineInstrBuilder MIB;
15881
15882   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15883   const int64_t SPOffset = 2 * PVT.getStoreSize();
15884
15885   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15886   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15887
15888   // Reload FP
15889   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15890   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15891     MIB.addOperand(MI->getOperand(i));
15892   MIB.setMemRefs(MMOBegin, MMOEnd);
15893   // Reload IP
15894   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15895   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15896     if (i == X86::AddrDisp)
15897       MIB.addDisp(MI->getOperand(i), LabelOffset);
15898     else
15899       MIB.addOperand(MI->getOperand(i));
15900   }
15901   MIB.setMemRefs(MMOBegin, MMOEnd);
15902   // Reload SP
15903   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15904   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15905     if (i == X86::AddrDisp)
15906       MIB.addDisp(MI->getOperand(i), SPOffset);
15907     else
15908       MIB.addOperand(MI->getOperand(i));
15909   }
15910   MIB.setMemRefs(MMOBegin, MMOEnd);
15911   // Jump
15912   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15913
15914   MI->eraseFromParent();
15915   return MBB;
15916 }
15917
15918 MachineBasicBlock *
15919 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15920                                                MachineBasicBlock *BB) const {
15921   switch (MI->getOpcode()) {
15922   default: llvm_unreachable("Unexpected instr type to insert");
15923   case X86::TAILJMPd64:
15924   case X86::TAILJMPr64:
15925   case X86::TAILJMPm64:
15926     llvm_unreachable("TAILJMP64 would not be touched here.");
15927   case X86::TCRETURNdi64:
15928   case X86::TCRETURNri64:
15929   case X86::TCRETURNmi64:
15930     return BB;
15931   case X86::WIN_ALLOCA:
15932     return EmitLoweredWinAlloca(MI, BB);
15933   case X86::SEG_ALLOCA_32:
15934     return EmitLoweredSegAlloca(MI, BB, false);
15935   case X86::SEG_ALLOCA_64:
15936     return EmitLoweredSegAlloca(MI, BB, true);
15937   case X86::TLSCall_32:
15938   case X86::TLSCall_64:
15939     return EmitLoweredTLSCall(MI, BB);
15940   case X86::CMOV_GR8:
15941   case X86::CMOV_FR32:
15942   case X86::CMOV_FR64:
15943   case X86::CMOV_V4F32:
15944   case X86::CMOV_V2F64:
15945   case X86::CMOV_V2I64:
15946   case X86::CMOV_V8F32:
15947   case X86::CMOV_V4F64:
15948   case X86::CMOV_V4I64:
15949   case X86::CMOV_V16F32:
15950   case X86::CMOV_V8F64:
15951   case X86::CMOV_V8I64:
15952   case X86::CMOV_GR16:
15953   case X86::CMOV_GR32:
15954   case X86::CMOV_RFP32:
15955   case X86::CMOV_RFP64:
15956   case X86::CMOV_RFP80:
15957     return EmitLoweredSelect(MI, BB);
15958
15959   case X86::FP32_TO_INT16_IN_MEM:
15960   case X86::FP32_TO_INT32_IN_MEM:
15961   case X86::FP32_TO_INT64_IN_MEM:
15962   case X86::FP64_TO_INT16_IN_MEM:
15963   case X86::FP64_TO_INT32_IN_MEM:
15964   case X86::FP64_TO_INT64_IN_MEM:
15965   case X86::FP80_TO_INT16_IN_MEM:
15966   case X86::FP80_TO_INT32_IN_MEM:
15967   case X86::FP80_TO_INT64_IN_MEM: {
15968     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15969     DebugLoc DL = MI->getDebugLoc();
15970
15971     // Change the floating point control register to use "round towards zero"
15972     // mode when truncating to an integer value.
15973     MachineFunction *F = BB->getParent();
15974     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15975     addFrameReference(BuildMI(*BB, MI, DL,
15976                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15977
15978     // Load the old value of the high byte of the control word...
15979     unsigned OldCW =
15980       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15981     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15982                       CWFrameIdx);
15983
15984     // Set the high part to be round to zero...
15985     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15986       .addImm(0xC7F);
15987
15988     // Reload the modified control word now...
15989     addFrameReference(BuildMI(*BB, MI, DL,
15990                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15991
15992     // Restore the memory image of control word to original value
15993     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15994       .addReg(OldCW);
15995
15996     // Get the X86 opcode to use.
15997     unsigned Opc;
15998     switch (MI->getOpcode()) {
15999     default: llvm_unreachable("illegal opcode!");
16000     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16001     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16002     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16003     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16004     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16005     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16006     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16007     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16008     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16009     }
16010
16011     X86AddressMode AM;
16012     MachineOperand &Op = MI->getOperand(0);
16013     if (Op.isReg()) {
16014       AM.BaseType = X86AddressMode::RegBase;
16015       AM.Base.Reg = Op.getReg();
16016     } else {
16017       AM.BaseType = X86AddressMode::FrameIndexBase;
16018       AM.Base.FrameIndex = Op.getIndex();
16019     }
16020     Op = MI->getOperand(1);
16021     if (Op.isImm())
16022       AM.Scale = Op.getImm();
16023     Op = MI->getOperand(2);
16024     if (Op.isImm())
16025       AM.IndexReg = Op.getImm();
16026     Op = MI->getOperand(3);
16027     if (Op.isGlobal()) {
16028       AM.GV = Op.getGlobal();
16029     } else {
16030       AM.Disp = Op.getImm();
16031     }
16032     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16033                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16034
16035     // Reload the original control word now.
16036     addFrameReference(BuildMI(*BB, MI, DL,
16037                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16038
16039     MI->eraseFromParent();   // The pseudo instruction is gone now.
16040     return BB;
16041   }
16042     // String/text processing lowering.
16043   case X86::PCMPISTRM128REG:
16044   case X86::VPCMPISTRM128REG:
16045   case X86::PCMPISTRM128MEM:
16046   case X86::VPCMPISTRM128MEM:
16047   case X86::PCMPESTRM128REG:
16048   case X86::VPCMPESTRM128REG:
16049   case X86::PCMPESTRM128MEM:
16050   case X86::VPCMPESTRM128MEM:
16051     assert(Subtarget->hasSSE42() &&
16052            "Target must have SSE4.2 or AVX features enabled");
16053     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16054
16055   // String/text processing lowering.
16056   case X86::PCMPISTRIREG:
16057   case X86::VPCMPISTRIREG:
16058   case X86::PCMPISTRIMEM:
16059   case X86::VPCMPISTRIMEM:
16060   case X86::PCMPESTRIREG:
16061   case X86::VPCMPESTRIREG:
16062   case X86::PCMPESTRIMEM:
16063   case X86::VPCMPESTRIMEM:
16064     assert(Subtarget->hasSSE42() &&
16065            "Target must have SSE4.2 or AVX features enabled");
16066     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16067
16068   // Thread synchronization.
16069   case X86::MONITOR:
16070     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16071
16072   // xbegin
16073   case X86::XBEGIN:
16074     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16075
16076   // Atomic Lowering.
16077   case X86::ATOMAND8:
16078   case X86::ATOMAND16:
16079   case X86::ATOMAND32:
16080   case X86::ATOMAND64:
16081     // Fall through
16082   case X86::ATOMOR8:
16083   case X86::ATOMOR16:
16084   case X86::ATOMOR32:
16085   case X86::ATOMOR64:
16086     // Fall through
16087   case X86::ATOMXOR16:
16088   case X86::ATOMXOR8:
16089   case X86::ATOMXOR32:
16090   case X86::ATOMXOR64:
16091     // Fall through
16092   case X86::ATOMNAND8:
16093   case X86::ATOMNAND16:
16094   case X86::ATOMNAND32:
16095   case X86::ATOMNAND64:
16096     // Fall through
16097   case X86::ATOMMAX8:
16098   case X86::ATOMMAX16:
16099   case X86::ATOMMAX32:
16100   case X86::ATOMMAX64:
16101     // Fall through
16102   case X86::ATOMMIN8:
16103   case X86::ATOMMIN16:
16104   case X86::ATOMMIN32:
16105   case X86::ATOMMIN64:
16106     // Fall through
16107   case X86::ATOMUMAX8:
16108   case X86::ATOMUMAX16:
16109   case X86::ATOMUMAX32:
16110   case X86::ATOMUMAX64:
16111     // Fall through
16112   case X86::ATOMUMIN8:
16113   case X86::ATOMUMIN16:
16114   case X86::ATOMUMIN32:
16115   case X86::ATOMUMIN64:
16116     return EmitAtomicLoadArith(MI, BB);
16117
16118   // This group does 64-bit operations on a 32-bit host.
16119   case X86::ATOMAND6432:
16120   case X86::ATOMOR6432:
16121   case X86::ATOMXOR6432:
16122   case X86::ATOMNAND6432:
16123   case X86::ATOMADD6432:
16124   case X86::ATOMSUB6432:
16125   case X86::ATOMMAX6432:
16126   case X86::ATOMMIN6432:
16127   case X86::ATOMUMAX6432:
16128   case X86::ATOMUMIN6432:
16129   case X86::ATOMSWAP6432:
16130     return EmitAtomicLoadArith6432(MI, BB);
16131
16132   case X86::VASTART_SAVE_XMM_REGS:
16133     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16134
16135   case X86::VAARG_64:
16136     return EmitVAARG64WithCustomInserter(MI, BB);
16137
16138   case X86::EH_SjLj_SetJmp32:
16139   case X86::EH_SjLj_SetJmp64:
16140     return emitEHSjLjSetJmp(MI, BB);
16141
16142   case X86::EH_SjLj_LongJmp32:
16143   case X86::EH_SjLj_LongJmp64:
16144     return emitEHSjLjLongJmp(MI, BB);
16145
16146   case TargetOpcode::STACKMAP:
16147   case TargetOpcode::PATCHPOINT:
16148     return emitPatchPoint(MI, BB);
16149   }
16150 }
16151
16152 //===----------------------------------------------------------------------===//
16153 //                           X86 Optimization Hooks
16154 //===----------------------------------------------------------------------===//
16155
16156 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16157                                                        APInt &KnownZero,
16158                                                        APInt &KnownOne,
16159                                                        const SelectionDAG &DAG,
16160                                                        unsigned Depth) const {
16161   unsigned BitWidth = KnownZero.getBitWidth();
16162   unsigned Opc = Op.getOpcode();
16163   assert((Opc >= ISD::BUILTIN_OP_END ||
16164           Opc == ISD::INTRINSIC_WO_CHAIN ||
16165           Opc == ISD::INTRINSIC_W_CHAIN ||
16166           Opc == ISD::INTRINSIC_VOID) &&
16167          "Should use MaskedValueIsZero if you don't know whether Op"
16168          " is a target node!");
16169
16170   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16171   switch (Opc) {
16172   default: break;
16173   case X86ISD::ADD:
16174   case X86ISD::SUB:
16175   case X86ISD::ADC:
16176   case X86ISD::SBB:
16177   case X86ISD::SMUL:
16178   case X86ISD::UMUL:
16179   case X86ISD::INC:
16180   case X86ISD::DEC:
16181   case X86ISD::OR:
16182   case X86ISD::XOR:
16183   case X86ISD::AND:
16184     // These nodes' second result is a boolean.
16185     if (Op.getResNo() == 0)
16186       break;
16187     // Fallthrough
16188   case X86ISD::SETCC:
16189     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16190     break;
16191   case ISD::INTRINSIC_WO_CHAIN: {
16192     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16193     unsigned NumLoBits = 0;
16194     switch (IntId) {
16195     default: break;
16196     case Intrinsic::x86_sse_movmsk_ps:
16197     case Intrinsic::x86_avx_movmsk_ps_256:
16198     case Intrinsic::x86_sse2_movmsk_pd:
16199     case Intrinsic::x86_avx_movmsk_pd_256:
16200     case Intrinsic::x86_mmx_pmovmskb:
16201     case Intrinsic::x86_sse2_pmovmskb_128:
16202     case Intrinsic::x86_avx2_pmovmskb: {
16203       // High bits of movmskp{s|d}, pmovmskb are known zero.
16204       switch (IntId) {
16205         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16206         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16207         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16208         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16209         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16210         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16211         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16212         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16213       }
16214       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16215       break;
16216     }
16217     }
16218     break;
16219   }
16220   }
16221 }
16222
16223 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16224                                                          unsigned Depth) const {
16225   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16226   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16227     return Op.getValueType().getScalarType().getSizeInBits();
16228
16229   // Fallback case.
16230   return 1;
16231 }
16232
16233 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16234 /// node is a GlobalAddress + offset.
16235 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16236                                        const GlobalValue* &GA,
16237                                        int64_t &Offset) const {
16238   if (N->getOpcode() == X86ISD::Wrapper) {
16239     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16240       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16241       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16242       return true;
16243     }
16244   }
16245   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16246 }
16247
16248 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16249 /// same as extracting the high 128-bit part of 256-bit vector and then
16250 /// inserting the result into the low part of a new 256-bit vector
16251 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16252   EVT VT = SVOp->getValueType(0);
16253   unsigned NumElems = VT.getVectorNumElements();
16254
16255   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16256   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16257     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16258         SVOp->getMaskElt(j) >= 0)
16259       return false;
16260
16261   return true;
16262 }
16263
16264 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16265 /// same as extracting the low 128-bit part of 256-bit vector and then
16266 /// inserting the result into the high part of a new 256-bit vector
16267 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16268   EVT VT = SVOp->getValueType(0);
16269   unsigned NumElems = VT.getVectorNumElements();
16270
16271   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16272   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16273     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16274         SVOp->getMaskElt(j) >= 0)
16275       return false;
16276
16277   return true;
16278 }
16279
16280 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16281 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16282                                         TargetLowering::DAGCombinerInfo &DCI,
16283                                         const X86Subtarget* Subtarget) {
16284   SDLoc dl(N);
16285   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16286   SDValue V1 = SVOp->getOperand(0);
16287   SDValue V2 = SVOp->getOperand(1);
16288   EVT VT = SVOp->getValueType(0);
16289   unsigned NumElems = VT.getVectorNumElements();
16290
16291   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16292       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16293     //
16294     //                   0,0,0,...
16295     //                      |
16296     //    V      UNDEF    BUILD_VECTOR    UNDEF
16297     //     \      /           \           /
16298     //  CONCAT_VECTOR         CONCAT_VECTOR
16299     //         \                  /
16300     //          \                /
16301     //          RESULT: V + zero extended
16302     //
16303     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16304         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16305         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16306       return SDValue();
16307
16308     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16309       return SDValue();
16310
16311     // To match the shuffle mask, the first half of the mask should
16312     // be exactly the first vector, and all the rest a splat with the
16313     // first element of the second one.
16314     for (unsigned i = 0; i != NumElems/2; ++i)
16315       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16316           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16317         return SDValue();
16318
16319     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16320     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16321       if (Ld->hasNUsesOfValue(1, 0)) {
16322         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16323         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16324         SDValue ResNode =
16325           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16326                                   array_lengthof(Ops),
16327                                   Ld->getMemoryVT(),
16328                                   Ld->getPointerInfo(),
16329                                   Ld->getAlignment(),
16330                                   false/*isVolatile*/, true/*ReadMem*/,
16331                                   false/*WriteMem*/);
16332
16333         // Make sure the newly-created LOAD is in the same position as Ld in
16334         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16335         // and update uses of Ld's output chain to use the TokenFactor.
16336         if (Ld->hasAnyUseOfValue(1)) {
16337           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16338                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16339           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16340           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16341                                  SDValue(ResNode.getNode(), 1));
16342         }
16343
16344         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16345       }
16346     }
16347
16348     // Emit a zeroed vector and insert the desired subvector on its
16349     // first half.
16350     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16351     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16352     return DCI.CombineTo(N, InsV);
16353   }
16354
16355   //===--------------------------------------------------------------------===//
16356   // Combine some shuffles into subvector extracts and inserts:
16357   //
16358
16359   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16360   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16361     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16362     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16363     return DCI.CombineTo(N, InsV);
16364   }
16365
16366   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16367   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16368     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16369     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16370     return DCI.CombineTo(N, InsV);
16371   }
16372
16373   return SDValue();
16374 }
16375
16376 /// PerformShuffleCombine - Performs several different shuffle combines.
16377 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16378                                      TargetLowering::DAGCombinerInfo &DCI,
16379                                      const X86Subtarget *Subtarget) {
16380   SDLoc dl(N);
16381   EVT VT = N->getValueType(0);
16382
16383   // Don't create instructions with illegal types after legalize types has run.
16384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16385   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16386     return SDValue();
16387
16388   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16389   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16390       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16391     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16392
16393   // Only handle 128 wide vector from here on.
16394   if (!VT.is128BitVector())
16395     return SDValue();
16396
16397   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16398   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16399   // consecutive, non-overlapping, and in the right order.
16400   SmallVector<SDValue, 16> Elts;
16401   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16402     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16403
16404   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16405 }
16406
16407 /// PerformTruncateCombine - Converts truncate operation to
16408 /// a sequence of vector shuffle operations.
16409 /// It is possible when we truncate 256-bit vector to 128-bit vector
16410 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16411                                       TargetLowering::DAGCombinerInfo &DCI,
16412                                       const X86Subtarget *Subtarget)  {
16413   return SDValue();
16414 }
16415
16416 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16417 /// specific shuffle of a load can be folded into a single element load.
16418 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16419 /// shuffles have been customed lowered so we need to handle those here.
16420 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16421                                          TargetLowering::DAGCombinerInfo &DCI) {
16422   if (DCI.isBeforeLegalizeOps())
16423     return SDValue();
16424
16425   SDValue InVec = N->getOperand(0);
16426   SDValue EltNo = N->getOperand(1);
16427
16428   if (!isa<ConstantSDNode>(EltNo))
16429     return SDValue();
16430
16431   EVT VT = InVec.getValueType();
16432
16433   bool HasShuffleIntoBitcast = false;
16434   if (InVec.getOpcode() == ISD::BITCAST) {
16435     // Don't duplicate a load with other uses.
16436     if (!InVec.hasOneUse())
16437       return SDValue();
16438     EVT BCVT = InVec.getOperand(0).getValueType();
16439     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16440       return SDValue();
16441     InVec = InVec.getOperand(0);
16442     HasShuffleIntoBitcast = true;
16443   }
16444
16445   if (!isTargetShuffle(InVec.getOpcode()))
16446     return SDValue();
16447
16448   // Don't duplicate a load with other uses.
16449   if (!InVec.hasOneUse())
16450     return SDValue();
16451
16452   SmallVector<int, 16> ShuffleMask;
16453   bool UnaryShuffle;
16454   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16455                             UnaryShuffle))
16456     return SDValue();
16457
16458   // Select the input vector, guarding against out of range extract vector.
16459   unsigned NumElems = VT.getVectorNumElements();
16460   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16461   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16462   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16463                                          : InVec.getOperand(1);
16464
16465   // If inputs to shuffle are the same for both ops, then allow 2 uses
16466   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16467
16468   if (LdNode.getOpcode() == ISD::BITCAST) {
16469     // Don't duplicate a load with other uses.
16470     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16471       return SDValue();
16472
16473     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16474     LdNode = LdNode.getOperand(0);
16475   }
16476
16477   if (!ISD::isNormalLoad(LdNode.getNode()))
16478     return SDValue();
16479
16480   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16481
16482   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16483     return SDValue();
16484
16485   if (HasShuffleIntoBitcast) {
16486     // If there's a bitcast before the shuffle, check if the load type and
16487     // alignment is valid.
16488     unsigned Align = LN0->getAlignment();
16489     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16490     unsigned NewAlign = TLI.getDataLayout()->
16491       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16492
16493     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16494       return SDValue();
16495   }
16496
16497   // All checks match so transform back to vector_shuffle so that DAG combiner
16498   // can finish the job
16499   SDLoc dl(N);
16500
16501   // Create shuffle node taking into account the case that its a unary shuffle
16502   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16503   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16504                                  InVec.getOperand(0), Shuffle,
16505                                  &ShuffleMask[0]);
16506   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16507   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16508                      EltNo);
16509 }
16510
16511 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16512 /// generation and convert it from being a bunch of shuffles and extracts
16513 /// to a simple store and scalar loads to extract the elements.
16514 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16515                                          TargetLowering::DAGCombinerInfo &DCI) {
16516   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16517   if (NewOp.getNode())
16518     return NewOp;
16519
16520   SDValue InputVector = N->getOperand(0);
16521
16522   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16523   // from mmx to v2i32 has a single usage.
16524   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16525       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16526       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16527     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16528                        N->getValueType(0),
16529                        InputVector.getNode()->getOperand(0));
16530
16531   // Only operate on vectors of 4 elements, where the alternative shuffling
16532   // gets to be more expensive.
16533   if (InputVector.getValueType() != MVT::v4i32)
16534     return SDValue();
16535
16536   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16537   // single use which is a sign-extend or zero-extend, and all elements are
16538   // used.
16539   SmallVector<SDNode *, 4> Uses;
16540   unsigned ExtractedElements = 0;
16541   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16542        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16543     if (UI.getUse().getResNo() != InputVector.getResNo())
16544       return SDValue();
16545
16546     SDNode *Extract = *UI;
16547     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16548       return SDValue();
16549
16550     if (Extract->getValueType(0) != MVT::i32)
16551       return SDValue();
16552     if (!Extract->hasOneUse())
16553       return SDValue();
16554     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16555         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16556       return SDValue();
16557     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16558       return SDValue();
16559
16560     // Record which element was extracted.
16561     ExtractedElements |=
16562       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16563
16564     Uses.push_back(Extract);
16565   }
16566
16567   // If not all the elements were used, this may not be worthwhile.
16568   if (ExtractedElements != 15)
16569     return SDValue();
16570
16571   // Ok, we've now decided to do the transformation.
16572   SDLoc dl(InputVector);
16573
16574   // Store the value to a temporary stack slot.
16575   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16576   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16577                             MachinePointerInfo(), false, false, 0);
16578
16579   // Replace each use (extract) with a load of the appropriate element.
16580   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16581        UE = Uses.end(); UI != UE; ++UI) {
16582     SDNode *Extract = *UI;
16583
16584     // cOMpute the element's address.
16585     SDValue Idx = Extract->getOperand(1);
16586     unsigned EltSize =
16587         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16588     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16589     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16590     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16591
16592     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16593                                      StackPtr, OffsetVal);
16594
16595     // Load the scalar.
16596     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16597                                      ScalarAddr, MachinePointerInfo(),
16598                                      false, false, false, 0);
16599
16600     // Replace the exact with the load.
16601     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16602   }
16603
16604   // The replacement was made in place; don't return anything.
16605   return SDValue();
16606 }
16607
16608 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16609 static std::pair<unsigned, bool>
16610 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16611                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16612   if (!VT.isVector())
16613     return std::make_pair(0, false);
16614
16615   bool NeedSplit = false;
16616   switch (VT.getSimpleVT().SimpleTy) {
16617   default: return std::make_pair(0, false);
16618   case MVT::v32i8:
16619   case MVT::v16i16:
16620   case MVT::v8i32:
16621     if (!Subtarget->hasAVX2())
16622       NeedSplit = true;
16623     if (!Subtarget->hasAVX())
16624       return std::make_pair(0, false);
16625     break;
16626   case MVT::v16i8:
16627   case MVT::v8i16:
16628   case MVT::v4i32:
16629     if (!Subtarget->hasSSE2())
16630       return std::make_pair(0, false);
16631   }
16632
16633   // SSE2 has only a small subset of the operations.
16634   bool hasUnsigned = Subtarget->hasSSE41() ||
16635                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16636   bool hasSigned = Subtarget->hasSSE41() ||
16637                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16638
16639   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16640
16641   unsigned Opc = 0;
16642   // Check for x CC y ? x : y.
16643   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16644       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16645     switch (CC) {
16646     default: break;
16647     case ISD::SETULT:
16648     case ISD::SETULE:
16649       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16650     case ISD::SETUGT:
16651     case ISD::SETUGE:
16652       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16653     case ISD::SETLT:
16654     case ISD::SETLE:
16655       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16656     case ISD::SETGT:
16657     case ISD::SETGE:
16658       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16659     }
16660   // Check for x CC y ? y : x -- a min/max with reversed arms.
16661   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16662              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16663     switch (CC) {
16664     default: break;
16665     case ISD::SETULT:
16666     case ISD::SETULE:
16667       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16668     case ISD::SETUGT:
16669     case ISD::SETUGE:
16670       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16671     case ISD::SETLT:
16672     case ISD::SETLE:
16673       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16674     case ISD::SETGT:
16675     case ISD::SETGE:
16676       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16677     }
16678   }
16679
16680   return std::make_pair(Opc, NeedSplit);
16681 }
16682
16683 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16684 /// nodes.
16685 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16686                                     TargetLowering::DAGCombinerInfo &DCI,
16687                                     const X86Subtarget *Subtarget) {
16688   SDLoc DL(N);
16689   SDValue Cond = N->getOperand(0);
16690   // Get the LHS/RHS of the select.
16691   SDValue LHS = N->getOperand(1);
16692   SDValue RHS = N->getOperand(2);
16693   EVT VT = LHS.getValueType();
16694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16695
16696   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16697   // instructions match the semantics of the common C idiom x<y?x:y but not
16698   // x<=y?x:y, because of how they handle negative zero (which can be
16699   // ignored in unsafe-math mode).
16700   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16701       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
16702       (Subtarget->hasSSE2() ||
16703        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16704     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16705
16706     unsigned Opcode = 0;
16707     // Check for x CC y ? x : y.
16708     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16709         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16710       switch (CC) {
16711       default: break;
16712       case ISD::SETULT:
16713         // Converting this to a min would handle NaNs incorrectly, and swapping
16714         // the operands would cause it to handle comparisons between positive
16715         // and negative zero incorrectly.
16716         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16717           if (!DAG.getTarget().Options.UnsafeFPMath &&
16718               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16719             break;
16720           std::swap(LHS, RHS);
16721         }
16722         Opcode = X86ISD::FMIN;
16723         break;
16724       case ISD::SETOLE:
16725         // Converting this to a min would handle comparisons between positive
16726         // and negative zero incorrectly.
16727         if (!DAG.getTarget().Options.UnsafeFPMath &&
16728             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16729           break;
16730         Opcode = X86ISD::FMIN;
16731         break;
16732       case ISD::SETULE:
16733         // Converting this to a min would handle both negative zeros and NaNs
16734         // incorrectly, but we can swap the operands to fix both.
16735         std::swap(LHS, RHS);
16736       case ISD::SETOLT:
16737       case ISD::SETLT:
16738       case ISD::SETLE:
16739         Opcode = X86ISD::FMIN;
16740         break;
16741
16742       case ISD::SETOGE:
16743         // Converting this to a max would handle comparisons between positive
16744         // and negative zero incorrectly.
16745         if (!DAG.getTarget().Options.UnsafeFPMath &&
16746             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16747           break;
16748         Opcode = X86ISD::FMAX;
16749         break;
16750       case ISD::SETUGT:
16751         // Converting this to a max would handle NaNs incorrectly, and swapping
16752         // the operands would cause it to handle comparisons between positive
16753         // and negative zero incorrectly.
16754         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16755           if (!DAG.getTarget().Options.UnsafeFPMath &&
16756               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16757             break;
16758           std::swap(LHS, RHS);
16759         }
16760         Opcode = X86ISD::FMAX;
16761         break;
16762       case ISD::SETUGE:
16763         // Converting this to a max would handle both negative zeros and NaNs
16764         // incorrectly, but we can swap the operands to fix both.
16765         std::swap(LHS, RHS);
16766       case ISD::SETOGT:
16767       case ISD::SETGT:
16768       case ISD::SETGE:
16769         Opcode = X86ISD::FMAX;
16770         break;
16771       }
16772     // Check for x CC y ? y : x -- a min/max with reversed arms.
16773     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16774                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16775       switch (CC) {
16776       default: break;
16777       case ISD::SETOGE:
16778         // Converting this to a min would handle comparisons between positive
16779         // and negative zero incorrectly, and swapping the operands would
16780         // cause it to handle NaNs incorrectly.
16781         if (!DAG.getTarget().Options.UnsafeFPMath &&
16782             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16783           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16784             break;
16785           std::swap(LHS, RHS);
16786         }
16787         Opcode = X86ISD::FMIN;
16788         break;
16789       case ISD::SETUGT:
16790         // Converting this to a min would handle NaNs incorrectly.
16791         if (!DAG.getTarget().Options.UnsafeFPMath &&
16792             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16793           break;
16794         Opcode = X86ISD::FMIN;
16795         break;
16796       case ISD::SETUGE:
16797         // Converting this to a min would handle both negative zeros and NaNs
16798         // incorrectly, but we can swap the operands to fix both.
16799         std::swap(LHS, RHS);
16800       case ISD::SETOGT:
16801       case ISD::SETGT:
16802       case ISD::SETGE:
16803         Opcode = X86ISD::FMIN;
16804         break;
16805
16806       case ISD::SETULT:
16807         // Converting this to a max would handle NaNs incorrectly.
16808         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16809           break;
16810         Opcode = X86ISD::FMAX;
16811         break;
16812       case ISD::SETOLE:
16813         // Converting this to a max would handle comparisons between positive
16814         // and negative zero incorrectly, and swapping the operands would
16815         // cause it to handle NaNs incorrectly.
16816         if (!DAG.getTarget().Options.UnsafeFPMath &&
16817             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16818           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16819             break;
16820           std::swap(LHS, RHS);
16821         }
16822         Opcode = X86ISD::FMAX;
16823         break;
16824       case ISD::SETULE:
16825         // Converting this to a max would handle both negative zeros and NaNs
16826         // incorrectly, but we can swap the operands to fix both.
16827         std::swap(LHS, RHS);
16828       case ISD::SETOLT:
16829       case ISD::SETLT:
16830       case ISD::SETLE:
16831         Opcode = X86ISD::FMAX;
16832         break;
16833       }
16834     }
16835
16836     if (Opcode)
16837       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16838   }
16839
16840   EVT CondVT = Cond.getValueType();
16841   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
16842       CondVT.getVectorElementType() == MVT::i1) {
16843     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
16844     // lowering on AVX-512. In this case we convert it to
16845     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
16846     // The same situation for all 128 and 256-bit vectors of i8 and i16
16847     EVT OpVT = LHS.getValueType();
16848     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
16849         (OpVT.getVectorElementType() == MVT::i8 ||
16850          OpVT.getVectorElementType() == MVT::i16)) {
16851       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
16852       DCI.AddToWorklist(Cond.getNode());
16853       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
16854     }
16855   }
16856   // If this is a select between two integer constants, try to do some
16857   // optimizations.
16858   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16859     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16860       // Don't do this for crazy integer types.
16861       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16862         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16863         // so that TrueC (the true value) is larger than FalseC.
16864         bool NeedsCondInvert = false;
16865
16866         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16867             // Efficiently invertible.
16868             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16869              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16870               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16871           NeedsCondInvert = true;
16872           std::swap(TrueC, FalseC);
16873         }
16874
16875         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16876         if (FalseC->getAPIntValue() == 0 &&
16877             TrueC->getAPIntValue().isPowerOf2()) {
16878           if (NeedsCondInvert) // Invert the condition if needed.
16879             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16880                                DAG.getConstant(1, Cond.getValueType()));
16881
16882           // Zero extend the condition if needed.
16883           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16884
16885           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16886           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16887                              DAG.getConstant(ShAmt, MVT::i8));
16888         }
16889
16890         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16891         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16892           if (NeedsCondInvert) // Invert the condition if needed.
16893             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16894                                DAG.getConstant(1, Cond.getValueType()));
16895
16896           // Zero extend the condition if needed.
16897           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16898                              FalseC->getValueType(0), Cond);
16899           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16900                              SDValue(FalseC, 0));
16901         }
16902
16903         // Optimize cases that will turn into an LEA instruction.  This requires
16904         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16905         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16906           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16907           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16908
16909           bool isFastMultiplier = false;
16910           if (Diff < 10) {
16911             switch ((unsigned char)Diff) {
16912               default: break;
16913               case 1:  // result = add base, cond
16914               case 2:  // result = lea base(    , cond*2)
16915               case 3:  // result = lea base(cond, cond*2)
16916               case 4:  // result = lea base(    , cond*4)
16917               case 5:  // result = lea base(cond, cond*4)
16918               case 8:  // result = lea base(    , cond*8)
16919               case 9:  // result = lea base(cond, cond*8)
16920                 isFastMultiplier = true;
16921                 break;
16922             }
16923           }
16924
16925           if (isFastMultiplier) {
16926             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16927             if (NeedsCondInvert) // Invert the condition if needed.
16928               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16929                                  DAG.getConstant(1, Cond.getValueType()));
16930
16931             // Zero extend the condition if needed.
16932             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16933                                Cond);
16934             // Scale the condition by the difference.
16935             if (Diff != 1)
16936               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16937                                  DAG.getConstant(Diff, Cond.getValueType()));
16938
16939             // Add the base if non-zero.
16940             if (FalseC->getAPIntValue() != 0)
16941               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16942                                  SDValue(FalseC, 0));
16943             return Cond;
16944           }
16945         }
16946       }
16947   }
16948
16949   // Canonicalize max and min:
16950   // (x > y) ? x : y -> (x >= y) ? x : y
16951   // (x < y) ? x : y -> (x <= y) ? x : y
16952   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16953   // the need for an extra compare
16954   // against zero. e.g.
16955   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16956   // subl   %esi, %edi
16957   // testl  %edi, %edi
16958   // movl   $0, %eax
16959   // cmovgl %edi, %eax
16960   // =>
16961   // xorl   %eax, %eax
16962   // subl   %esi, $edi
16963   // cmovsl %eax, %edi
16964   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16965       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16966       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16967     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16968     switch (CC) {
16969     default: break;
16970     case ISD::SETLT:
16971     case ISD::SETGT: {
16972       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16973       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16974                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16975       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16976     }
16977     }
16978   }
16979
16980   // Early exit check
16981   if (!TLI.isTypeLegal(VT))
16982     return SDValue();
16983
16984   // Match VSELECTs into subs with unsigned saturation.
16985   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16986       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16987       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16988        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16989     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16990
16991     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16992     // left side invert the predicate to simplify logic below.
16993     SDValue Other;
16994     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16995       Other = RHS;
16996       CC = ISD::getSetCCInverse(CC, true);
16997     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16998       Other = LHS;
16999     }
17000
17001     if (Other.getNode() && Other->getNumOperands() == 2 &&
17002         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17003       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17004       SDValue CondRHS = Cond->getOperand(1);
17005
17006       // Look for a general sub with unsigned saturation first.
17007       // x >= y ? x-y : 0 --> subus x, y
17008       // x >  y ? x-y : 0 --> subus x, y
17009       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17010           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17011         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17012
17013       // If the RHS is a constant we have to reverse the const canonicalization.
17014       // x > C-1 ? x+-C : 0 --> subus x, C
17015       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17016           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17017         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17018         if (CondRHS.getConstantOperandVal(0) == -A-1)
17019           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17020                              DAG.getConstant(-A, VT));
17021       }
17022
17023       // Another special case: If C was a sign bit, the sub has been
17024       // canonicalized into a xor.
17025       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17026       //        it's safe to decanonicalize the xor?
17027       // x s< 0 ? x^C : 0 --> subus x, C
17028       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17029           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17030           isSplatVector(OpRHS.getNode())) {
17031         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17032         if (A.isSignBit())
17033           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17034       }
17035     }
17036   }
17037
17038   // Try to match a min/max vector operation.
17039   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17040     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17041     unsigned Opc = ret.first;
17042     bool NeedSplit = ret.second;
17043
17044     if (Opc && NeedSplit) {
17045       unsigned NumElems = VT.getVectorNumElements();
17046       // Extract the LHS vectors
17047       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17048       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17049
17050       // Extract the RHS vectors
17051       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17052       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17053
17054       // Create min/max for each subvector
17055       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17056       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17057
17058       // Merge the result
17059       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17060     } else if (Opc)
17061       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17062   }
17063
17064   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17065   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17066       // Check if SETCC has already been promoted
17067       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17068       // Check that condition value type matches vselect operand type
17069       CondVT == VT) { 
17070
17071     assert(Cond.getValueType().isVector() &&
17072            "vector select expects a vector selector!");
17073
17074     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17075     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17076
17077     if (!TValIsAllOnes && !FValIsAllZeros) {
17078       // Try invert the condition if true value is not all 1s and false value
17079       // is not all 0s.
17080       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17081       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17082
17083       if (TValIsAllZeros || FValIsAllOnes) {
17084         SDValue CC = Cond.getOperand(2);
17085         ISD::CondCode NewCC =
17086           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17087                                Cond.getOperand(0).getValueType().isInteger());
17088         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17089         std::swap(LHS, RHS);
17090         TValIsAllOnes = FValIsAllOnes;
17091         FValIsAllZeros = TValIsAllZeros;
17092       }
17093     }
17094
17095     if (TValIsAllOnes || FValIsAllZeros) {
17096       SDValue Ret;
17097
17098       if (TValIsAllOnes && FValIsAllZeros)
17099         Ret = Cond;
17100       else if (TValIsAllOnes)
17101         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17102                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17103       else if (FValIsAllZeros)
17104         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17105                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17106
17107       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17108     }
17109   }
17110
17111   // If we know that this node is legal then we know that it is going to be
17112   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17113   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17114   // to simplify previous instructions.
17115   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17116       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17117     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17118
17119     // Don't optimize vector selects that map to mask-registers.
17120     if (BitWidth == 1)
17121       return SDValue();
17122
17123     // Check all uses of that condition operand to check whether it will be
17124     // consumed by non-BLEND instructions, which may depend on all bits are set
17125     // properly.
17126     for (SDNode::use_iterator I = Cond->use_begin(),
17127                               E = Cond->use_end(); I != E; ++I)
17128       if (I->getOpcode() != ISD::VSELECT)
17129         // TODO: Add other opcodes eventually lowered into BLEND.
17130         return SDValue();
17131
17132     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17133     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17134
17135     APInt KnownZero, KnownOne;
17136     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17137                                           DCI.isBeforeLegalizeOps());
17138     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17139         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17140       DCI.CommitTargetLoweringOpt(TLO);
17141   }
17142
17143   return SDValue();
17144 }
17145
17146 // Check whether a boolean test is testing a boolean value generated by
17147 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17148 // code.
17149 //
17150 // Simplify the following patterns:
17151 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17152 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17153 // to (Op EFLAGS Cond)
17154 //
17155 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17156 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17157 // to (Op EFLAGS !Cond)
17158 //
17159 // where Op could be BRCOND or CMOV.
17160 //
17161 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17162   // Quit if not CMP and SUB with its value result used.
17163   if (Cmp.getOpcode() != X86ISD::CMP &&
17164       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17165       return SDValue();
17166
17167   // Quit if not used as a boolean value.
17168   if (CC != X86::COND_E && CC != X86::COND_NE)
17169     return SDValue();
17170
17171   // Check CMP operands. One of them should be 0 or 1 and the other should be
17172   // an SetCC or extended from it.
17173   SDValue Op1 = Cmp.getOperand(0);
17174   SDValue Op2 = Cmp.getOperand(1);
17175
17176   SDValue SetCC;
17177   const ConstantSDNode* C = 0;
17178   bool needOppositeCond = (CC == X86::COND_E);
17179   bool checkAgainstTrue = false; // Is it a comparison against 1?
17180
17181   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17182     SetCC = Op2;
17183   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17184     SetCC = Op1;
17185   else // Quit if all operands are not constants.
17186     return SDValue();
17187
17188   if (C->getZExtValue() == 1) {
17189     needOppositeCond = !needOppositeCond;
17190     checkAgainstTrue = true;
17191   } else if (C->getZExtValue() != 0)
17192     // Quit if the constant is neither 0 or 1.
17193     return SDValue();
17194
17195   bool truncatedToBoolWithAnd = false;
17196   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17197   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17198          SetCC.getOpcode() == ISD::TRUNCATE ||
17199          SetCC.getOpcode() == ISD::AND) {
17200     if (SetCC.getOpcode() == ISD::AND) {
17201       int OpIdx = -1;
17202       ConstantSDNode *CS;
17203       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17204           CS->getZExtValue() == 1)
17205         OpIdx = 1;
17206       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17207           CS->getZExtValue() == 1)
17208         OpIdx = 0;
17209       if (OpIdx == -1)
17210         break;
17211       SetCC = SetCC.getOperand(OpIdx);
17212       truncatedToBoolWithAnd = true;
17213     } else
17214       SetCC = SetCC.getOperand(0);
17215   }
17216
17217   switch (SetCC.getOpcode()) {
17218   case X86ISD::SETCC_CARRY:
17219     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17220     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17221     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17222     // truncated to i1 using 'and'.
17223     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17224       break;
17225     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17226            "Invalid use of SETCC_CARRY!");
17227     // FALL THROUGH
17228   case X86ISD::SETCC:
17229     // Set the condition code or opposite one if necessary.
17230     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17231     if (needOppositeCond)
17232       CC = X86::GetOppositeBranchCondition(CC);
17233     return SetCC.getOperand(1);
17234   case X86ISD::CMOV: {
17235     // Check whether false/true value has canonical one, i.e. 0 or 1.
17236     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17237     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17238     // Quit if true value is not a constant.
17239     if (!TVal)
17240       return SDValue();
17241     // Quit if false value is not a constant.
17242     if (!FVal) {
17243       SDValue Op = SetCC.getOperand(0);
17244       // Skip 'zext' or 'trunc' node.
17245       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17246           Op.getOpcode() == ISD::TRUNCATE)
17247         Op = Op.getOperand(0);
17248       // A special case for rdrand/rdseed, where 0 is set if false cond is
17249       // found.
17250       if ((Op.getOpcode() != X86ISD::RDRAND &&
17251            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17252         return SDValue();
17253     }
17254     // Quit if false value is not the constant 0 or 1.
17255     bool FValIsFalse = true;
17256     if (FVal && FVal->getZExtValue() != 0) {
17257       if (FVal->getZExtValue() != 1)
17258         return SDValue();
17259       // If FVal is 1, opposite cond is needed.
17260       needOppositeCond = !needOppositeCond;
17261       FValIsFalse = false;
17262     }
17263     // Quit if TVal is not the constant opposite of FVal.
17264     if (FValIsFalse && TVal->getZExtValue() != 1)
17265       return SDValue();
17266     if (!FValIsFalse && TVal->getZExtValue() != 0)
17267       return SDValue();
17268     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17269     if (needOppositeCond)
17270       CC = X86::GetOppositeBranchCondition(CC);
17271     return SetCC.getOperand(3);
17272   }
17273   }
17274
17275   return SDValue();
17276 }
17277
17278 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17279 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17280                                   TargetLowering::DAGCombinerInfo &DCI,
17281                                   const X86Subtarget *Subtarget) {
17282   SDLoc DL(N);
17283
17284   // If the flag operand isn't dead, don't touch this CMOV.
17285   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17286     return SDValue();
17287
17288   SDValue FalseOp = N->getOperand(0);
17289   SDValue TrueOp = N->getOperand(1);
17290   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17291   SDValue Cond = N->getOperand(3);
17292
17293   if (CC == X86::COND_E || CC == X86::COND_NE) {
17294     switch (Cond.getOpcode()) {
17295     default: break;
17296     case X86ISD::BSR:
17297     case X86ISD::BSF:
17298       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17299       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17300         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17301     }
17302   }
17303
17304   SDValue Flags;
17305
17306   Flags = checkBoolTestSetCCCombine(Cond, CC);
17307   if (Flags.getNode() &&
17308       // Extra check as FCMOV only supports a subset of X86 cond.
17309       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17310     SDValue Ops[] = { FalseOp, TrueOp,
17311                       DAG.getConstant(CC, MVT::i8), Flags };
17312     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17313                        Ops, array_lengthof(Ops));
17314   }
17315
17316   // If this is a select between two integer constants, try to do some
17317   // optimizations.  Note that the operands are ordered the opposite of SELECT
17318   // operands.
17319   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17320     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17321       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17322       // larger than FalseC (the false value).
17323       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17324         CC = X86::GetOppositeBranchCondition(CC);
17325         std::swap(TrueC, FalseC);
17326         std::swap(TrueOp, FalseOp);
17327       }
17328
17329       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17330       // This is efficient for any integer data type (including i8/i16) and
17331       // shift amount.
17332       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17333         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17334                            DAG.getConstant(CC, MVT::i8), Cond);
17335
17336         // Zero extend the condition if needed.
17337         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17338
17339         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17340         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17341                            DAG.getConstant(ShAmt, MVT::i8));
17342         if (N->getNumValues() == 2)  // Dead flag value?
17343           return DCI.CombineTo(N, Cond, SDValue());
17344         return Cond;
17345       }
17346
17347       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17348       // for any integer data type, including i8/i16.
17349       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17350         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17351                            DAG.getConstant(CC, MVT::i8), Cond);
17352
17353         // Zero extend the condition if needed.
17354         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17355                            FalseC->getValueType(0), Cond);
17356         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17357                            SDValue(FalseC, 0));
17358
17359         if (N->getNumValues() == 2)  // Dead flag value?
17360           return DCI.CombineTo(N, Cond, SDValue());
17361         return Cond;
17362       }
17363
17364       // Optimize cases that will turn into an LEA instruction.  This requires
17365       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17366       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17367         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17368         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17369
17370         bool isFastMultiplier = false;
17371         if (Diff < 10) {
17372           switch ((unsigned char)Diff) {
17373           default: break;
17374           case 1:  // result = add base, cond
17375           case 2:  // result = lea base(    , cond*2)
17376           case 3:  // result = lea base(cond, cond*2)
17377           case 4:  // result = lea base(    , cond*4)
17378           case 5:  // result = lea base(cond, cond*4)
17379           case 8:  // result = lea base(    , cond*8)
17380           case 9:  // result = lea base(cond, cond*8)
17381             isFastMultiplier = true;
17382             break;
17383           }
17384         }
17385
17386         if (isFastMultiplier) {
17387           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17388           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17389                              DAG.getConstant(CC, MVT::i8), Cond);
17390           // Zero extend the condition if needed.
17391           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17392                              Cond);
17393           // Scale the condition by the difference.
17394           if (Diff != 1)
17395             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17396                                DAG.getConstant(Diff, Cond.getValueType()));
17397
17398           // Add the base if non-zero.
17399           if (FalseC->getAPIntValue() != 0)
17400             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17401                                SDValue(FalseC, 0));
17402           if (N->getNumValues() == 2)  // Dead flag value?
17403             return DCI.CombineTo(N, Cond, SDValue());
17404           return Cond;
17405         }
17406       }
17407     }
17408   }
17409
17410   // Handle these cases:
17411   //   (select (x != c), e, c) -> select (x != c), e, x),
17412   //   (select (x == c), c, e) -> select (x == c), x, e)
17413   // where the c is an integer constant, and the "select" is the combination
17414   // of CMOV and CMP.
17415   //
17416   // The rationale for this change is that the conditional-move from a constant
17417   // needs two instructions, however, conditional-move from a register needs
17418   // only one instruction.
17419   //
17420   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17421   //  some instruction-combining opportunities. This opt needs to be
17422   //  postponed as late as possible.
17423   //
17424   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17425     // the DCI.xxxx conditions are provided to postpone the optimization as
17426     // late as possible.
17427
17428     ConstantSDNode *CmpAgainst = 0;
17429     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17430         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17431         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17432
17433       if (CC == X86::COND_NE &&
17434           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17435         CC = X86::GetOppositeBranchCondition(CC);
17436         std::swap(TrueOp, FalseOp);
17437       }
17438
17439       if (CC == X86::COND_E &&
17440           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17441         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17442                           DAG.getConstant(CC, MVT::i8), Cond };
17443         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17444                            array_lengthof(Ops));
17445       }
17446     }
17447   }
17448
17449   return SDValue();
17450 }
17451
17452 /// PerformMulCombine - Optimize a single multiply with constant into two
17453 /// in order to implement it with two cheaper instructions, e.g.
17454 /// LEA + SHL, LEA + LEA.
17455 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17456                                  TargetLowering::DAGCombinerInfo &DCI) {
17457   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17458     return SDValue();
17459
17460   EVT VT = N->getValueType(0);
17461   if (VT != MVT::i64)
17462     return SDValue();
17463
17464   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17465   if (!C)
17466     return SDValue();
17467   uint64_t MulAmt = C->getZExtValue();
17468   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17469     return SDValue();
17470
17471   uint64_t MulAmt1 = 0;
17472   uint64_t MulAmt2 = 0;
17473   if ((MulAmt % 9) == 0) {
17474     MulAmt1 = 9;
17475     MulAmt2 = MulAmt / 9;
17476   } else if ((MulAmt % 5) == 0) {
17477     MulAmt1 = 5;
17478     MulAmt2 = MulAmt / 5;
17479   } else if ((MulAmt % 3) == 0) {
17480     MulAmt1 = 3;
17481     MulAmt2 = MulAmt / 3;
17482   }
17483   if (MulAmt2 &&
17484       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17485     SDLoc DL(N);
17486
17487     if (isPowerOf2_64(MulAmt2) &&
17488         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17489       // If second multiplifer is pow2, issue it first. We want the multiply by
17490       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17491       // is an add.
17492       std::swap(MulAmt1, MulAmt2);
17493
17494     SDValue NewMul;
17495     if (isPowerOf2_64(MulAmt1))
17496       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17497                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17498     else
17499       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17500                            DAG.getConstant(MulAmt1, VT));
17501
17502     if (isPowerOf2_64(MulAmt2))
17503       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17504                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17505     else
17506       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17507                            DAG.getConstant(MulAmt2, VT));
17508
17509     // Do not add new nodes to DAG combiner worklist.
17510     DCI.CombineTo(N, NewMul, false);
17511   }
17512   return SDValue();
17513 }
17514
17515 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17516   SDValue N0 = N->getOperand(0);
17517   SDValue N1 = N->getOperand(1);
17518   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17519   EVT VT = N0.getValueType();
17520
17521   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17522   // since the result of setcc_c is all zero's or all ones.
17523   if (VT.isInteger() && !VT.isVector() &&
17524       N1C && N0.getOpcode() == ISD::AND &&
17525       N0.getOperand(1).getOpcode() == ISD::Constant) {
17526     SDValue N00 = N0.getOperand(0);
17527     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17528         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17529           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17530          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17531       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17532       APInt ShAmt = N1C->getAPIntValue();
17533       Mask = Mask.shl(ShAmt);
17534       if (Mask != 0)
17535         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17536                            N00, DAG.getConstant(Mask, VT));
17537     }
17538   }
17539
17540   // Hardware support for vector shifts is sparse which makes us scalarize the
17541   // vector operations in many cases. Also, on sandybridge ADD is faster than
17542   // shl.
17543   // (shl V, 1) -> add V,V
17544   if (isSplatVector(N1.getNode())) {
17545     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17546     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17547     // We shift all of the values by one. In many cases we do not have
17548     // hardware support for this operation. This is better expressed as an ADD
17549     // of two values.
17550     if (N1C && (1 == N1C->getZExtValue())) {
17551       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17552     }
17553   }
17554
17555   return SDValue();
17556 }
17557
17558 /// \brief Returns a vector of 0s if the node in input is a vector logical
17559 /// shift by a constant amount which is known to be bigger than or equal
17560 /// to the vector element size in bits.
17561 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17562                                       const X86Subtarget *Subtarget) {
17563   EVT VT = N->getValueType(0);
17564
17565   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17566       (!Subtarget->hasInt256() ||
17567        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17568     return SDValue();
17569
17570   SDValue Amt = N->getOperand(1);
17571   SDLoc DL(N);
17572   if (isSplatVector(Amt.getNode())) {
17573     SDValue SclrAmt = Amt->getOperand(0);
17574     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17575       APInt ShiftAmt = C->getAPIntValue();
17576       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17577
17578       // SSE2/AVX2 logical shifts always return a vector of 0s
17579       // if the shift amount is bigger than or equal to
17580       // the element size. The constant shift amount will be
17581       // encoded as a 8-bit immediate.
17582       if (ShiftAmt.trunc(8).uge(MaxAmount))
17583         return getZeroVector(VT, Subtarget, DAG, DL);
17584     }
17585   }
17586
17587   return SDValue();
17588 }
17589
17590 /// PerformShiftCombine - Combine shifts.
17591 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17592                                    TargetLowering::DAGCombinerInfo &DCI,
17593                                    const X86Subtarget *Subtarget) {
17594   if (N->getOpcode() == ISD::SHL) {
17595     SDValue V = PerformSHLCombine(N, DAG);
17596     if (V.getNode()) return V;
17597   }
17598
17599   if (N->getOpcode() != ISD::SRA) {
17600     // Try to fold this logical shift into a zero vector.
17601     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17602     if (V.getNode()) return V;
17603   }
17604
17605   return SDValue();
17606 }
17607
17608 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
17609 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17610 // and friends.  Likewise for OR -> CMPNEQSS.
17611 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17612                             TargetLowering::DAGCombinerInfo &DCI,
17613                             const X86Subtarget *Subtarget) {
17614   unsigned opcode;
17615
17616   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17617   // we're requiring SSE2 for both.
17618   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17619     SDValue N0 = N->getOperand(0);
17620     SDValue N1 = N->getOperand(1);
17621     SDValue CMP0 = N0->getOperand(1);
17622     SDValue CMP1 = N1->getOperand(1);
17623     SDLoc DL(N);
17624
17625     // The SETCCs should both refer to the same CMP.
17626     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
17627       return SDValue();
17628
17629     SDValue CMP00 = CMP0->getOperand(0);
17630     SDValue CMP01 = CMP0->getOperand(1);
17631     EVT     VT    = CMP00.getValueType();
17632
17633     if (VT == MVT::f32 || VT == MVT::f64) {
17634       bool ExpectingFlags = false;
17635       // Check for any users that want flags:
17636       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
17637            !ExpectingFlags && UI != UE; ++UI)
17638         switch (UI->getOpcode()) {
17639         default:
17640         case ISD::BR_CC:
17641         case ISD::BRCOND:
17642         case ISD::SELECT:
17643           ExpectingFlags = true;
17644           break;
17645         case ISD::CopyToReg:
17646         case ISD::SIGN_EXTEND:
17647         case ISD::ZERO_EXTEND:
17648         case ISD::ANY_EXTEND:
17649           break;
17650         }
17651
17652       if (!ExpectingFlags) {
17653         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
17654         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
17655
17656         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
17657           X86::CondCode tmp = cc0;
17658           cc0 = cc1;
17659           cc1 = tmp;
17660         }
17661
17662         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
17663             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17664           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17665           // FIXME: need symbolic constants for these magic numbers.
17666           // See X86ATTInstPrinter.cpp:printSSECC().
17667           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17668           if (Subtarget->hasAVX512()) {
17669             // SETCC type in AVX-512 is MVT::i1
17670             assert(N->getValueType(0) == MVT::i1 && "Unexpected AND node type");
17671             return DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00, CMP01,
17672                                DAG.getConstant(x86cc, MVT::i8));
17673           }
17674           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00, CMP01,
17675                                               DAG.getConstant(x86cc, MVT::i8));
17676           MVT IntVT = (is64BitFP ? MVT::i64 : MVT::i32); 
17677           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
17678                                               OnesOrZeroesF);
17679           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
17680                                       DAG.getConstant(1, IntVT));
17681           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17682           return OneBitOfTruth;
17683         }
17684       }
17685     }
17686   }
17687   return SDValue();
17688 }
17689
17690 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17691 /// so it can be folded inside ANDNP.
17692 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17693   EVT VT = N->getValueType(0);
17694
17695   // Match direct AllOnes for 128 and 256-bit vectors
17696   if (ISD::isBuildVectorAllOnes(N))
17697     return true;
17698
17699   // Look through a bit convert.
17700   if (N->getOpcode() == ISD::BITCAST)
17701     N = N->getOperand(0).getNode();
17702
17703   // Sometimes the operand may come from a insert_subvector building a 256-bit
17704   // allones vector
17705   if (VT.is256BitVector() &&
17706       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17707     SDValue V1 = N->getOperand(0);
17708     SDValue V2 = N->getOperand(1);
17709
17710     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17711         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17712         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17713         ISD::isBuildVectorAllOnes(V2.getNode()))
17714       return true;
17715   }
17716
17717   return false;
17718 }
17719
17720 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17721 // register. In most cases we actually compare or select YMM-sized registers
17722 // and mixing the two types creates horrible code. This method optimizes
17723 // some of the transition sequences.
17724 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17725                                  TargetLowering::DAGCombinerInfo &DCI,
17726                                  const X86Subtarget *Subtarget) {
17727   EVT VT = N->getValueType(0);
17728   if (!VT.is256BitVector())
17729     return SDValue();
17730
17731   assert((N->getOpcode() == ISD::ANY_EXTEND ||
17732           N->getOpcode() == ISD::ZERO_EXTEND ||
17733           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17734
17735   SDValue Narrow = N->getOperand(0);
17736   EVT NarrowVT = Narrow->getValueType(0);
17737   if (!NarrowVT.is128BitVector())
17738     return SDValue();
17739
17740   if (Narrow->getOpcode() != ISD::XOR &&
17741       Narrow->getOpcode() != ISD::AND &&
17742       Narrow->getOpcode() != ISD::OR)
17743     return SDValue();
17744
17745   SDValue N0  = Narrow->getOperand(0);
17746   SDValue N1  = Narrow->getOperand(1);
17747   SDLoc DL(Narrow);
17748
17749   // The Left side has to be a trunc.
17750   if (N0.getOpcode() != ISD::TRUNCATE)
17751     return SDValue();
17752
17753   // The type of the truncated inputs.
17754   EVT WideVT = N0->getOperand(0)->getValueType(0);
17755   if (WideVT != VT)
17756     return SDValue();
17757
17758   // The right side has to be a 'trunc' or a constant vector.
17759   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17760   bool RHSConst = (isSplatVector(N1.getNode()) &&
17761                    isa<ConstantSDNode>(N1->getOperand(0)));
17762   if (!RHSTrunc && !RHSConst)
17763     return SDValue();
17764
17765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17766
17767   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17768     return SDValue();
17769
17770   // Set N0 and N1 to hold the inputs to the new wide operation.
17771   N0 = N0->getOperand(0);
17772   if (RHSConst) {
17773     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17774                      N1->getOperand(0));
17775     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17776     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17777   } else if (RHSTrunc) {
17778     N1 = N1->getOperand(0);
17779   }
17780
17781   // Generate the wide operation.
17782   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17783   unsigned Opcode = N->getOpcode();
17784   switch (Opcode) {
17785   case ISD::ANY_EXTEND:
17786     return Op;
17787   case ISD::ZERO_EXTEND: {
17788     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17789     APInt Mask = APInt::getAllOnesValue(InBits);
17790     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17791     return DAG.getNode(ISD::AND, DL, VT,
17792                        Op, DAG.getConstant(Mask, VT));
17793   }
17794   case ISD::SIGN_EXTEND:
17795     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17796                        Op, DAG.getValueType(NarrowVT));
17797   default:
17798     llvm_unreachable("Unexpected opcode");
17799   }
17800 }
17801
17802 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17803                                  TargetLowering::DAGCombinerInfo &DCI,
17804                                  const X86Subtarget *Subtarget) {
17805   EVT VT = N->getValueType(0);
17806   if (DCI.isBeforeLegalizeOps())
17807     return SDValue();
17808
17809   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17810   if (R.getNode())
17811     return R;
17812
17813   // Create BLSI, BLSR, and BZHI instructions
17814   // BLSI is X & (-X)
17815   // BLSR is X & (X-1)
17816   // BZHI is X & ((1 << Y) - 1)
17817   // BEXTR is ((X >> imm) & (2**size-1))
17818   if (VT == MVT::i32 || VT == MVT::i64) {
17819     SDValue N0 = N->getOperand(0);
17820     SDValue N1 = N->getOperand(1);
17821     SDLoc DL(N);
17822
17823     if (Subtarget->hasBMI()) {
17824       // Check LHS for neg
17825       if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17826           isZero(N0.getOperand(0)))
17827         return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17828
17829       // Check RHS for neg
17830       if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17831           isZero(N1.getOperand(0)))
17832         return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17833
17834       // Check LHS for X-1
17835       if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17836           isAllOnes(N0.getOperand(1)))
17837         return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17838
17839       // Check RHS for X-1
17840       if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17841           isAllOnes(N1.getOperand(1)))
17842         return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17843     }
17844
17845     if (Subtarget->hasBMI2()) {
17846       // Check for (and (add (shl 1, Y), -1), X)
17847       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
17848         SDValue N00 = N0.getOperand(0);
17849         if (N00.getOpcode() == ISD::SHL) {
17850           SDValue N001 = N00.getOperand(1);
17851           assert(N001.getValueType() == MVT::i8 && "unexpected type");
17852           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
17853           if (C && C->getZExtValue() == 1)
17854             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
17855         }
17856       }
17857
17858       // Check for (and X, (add (shl 1, Y), -1))
17859       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
17860         SDValue N10 = N1.getOperand(0);
17861         if (N10.getOpcode() == ISD::SHL) {
17862           SDValue N101 = N10.getOperand(1);
17863           assert(N101.getValueType() == MVT::i8 && "unexpected type");
17864           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
17865           if (C && C->getZExtValue() == 1)
17866             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
17867         }
17868       }
17869     }
17870
17871     // Check for BEXTR.
17872     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
17873         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
17874       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
17875       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17876       if (MaskNode && ShiftNode) {
17877         uint64_t Mask = MaskNode->getZExtValue();
17878         uint64_t Shift = ShiftNode->getZExtValue();
17879         if (isMask_64(Mask)) {
17880           uint64_t MaskSize = CountPopulation_64(Mask);
17881           if (Shift + MaskSize <= VT.getSizeInBits())
17882             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
17883                                DAG.getConstant(Shift | (MaskSize << 8), VT));
17884         }
17885       }
17886     } // BEXTR
17887
17888     return SDValue();
17889   }
17890
17891   // Want to form ANDNP nodes:
17892   // 1) In the hopes of then easily combining them with OR and AND nodes
17893   //    to form PBLEND/PSIGN.
17894   // 2) To match ANDN packed intrinsics
17895   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17896     return SDValue();
17897
17898   SDValue N0 = N->getOperand(0);
17899   SDValue N1 = N->getOperand(1);
17900   SDLoc DL(N);
17901
17902   // Check LHS for vnot
17903   if (N0.getOpcode() == ISD::XOR &&
17904       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17905       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17906     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17907
17908   // Check RHS for vnot
17909   if (N1.getOpcode() == ISD::XOR &&
17910       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17911       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17912     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17913
17914   return SDValue();
17915 }
17916
17917 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17918                                 TargetLowering::DAGCombinerInfo &DCI,
17919                                 const X86Subtarget *Subtarget) {
17920   EVT VT = N->getValueType(0);
17921   if (DCI.isBeforeLegalizeOps())
17922     return SDValue();
17923
17924   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17925   if (R.getNode())
17926     return R;
17927
17928   SDValue N0 = N->getOperand(0);
17929   SDValue N1 = N->getOperand(1);
17930
17931   // look for psign/blend
17932   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17933     if (!Subtarget->hasSSSE3() ||
17934         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17935       return SDValue();
17936
17937     // Canonicalize pandn to RHS
17938     if (N0.getOpcode() == X86ISD::ANDNP)
17939       std::swap(N0, N1);
17940     // or (and (m, y), (pandn m, x))
17941     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17942       SDValue Mask = N1.getOperand(0);
17943       SDValue X    = N1.getOperand(1);
17944       SDValue Y;
17945       if (N0.getOperand(0) == Mask)
17946         Y = N0.getOperand(1);
17947       if (N0.getOperand(1) == Mask)
17948         Y = N0.getOperand(0);
17949
17950       // Check to see if the mask appeared in both the AND and ANDNP and
17951       if (!Y.getNode())
17952         return SDValue();
17953
17954       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17955       // Look through mask bitcast.
17956       if (Mask.getOpcode() == ISD::BITCAST)
17957         Mask = Mask.getOperand(0);
17958       if (X.getOpcode() == ISD::BITCAST)
17959         X = X.getOperand(0);
17960       if (Y.getOpcode() == ISD::BITCAST)
17961         Y = Y.getOperand(0);
17962
17963       EVT MaskVT = Mask.getValueType();
17964
17965       // Validate that the Mask operand is a vector sra node.
17966       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17967       // there is no psrai.b
17968       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17969       unsigned SraAmt = ~0;
17970       if (Mask.getOpcode() == ISD::SRA) {
17971         SDValue Amt = Mask.getOperand(1);
17972         if (isSplatVector(Amt.getNode())) {
17973           SDValue SclrAmt = Amt->getOperand(0);
17974           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17975             SraAmt = C->getZExtValue();
17976         }
17977       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17978         SDValue SraC = Mask.getOperand(1);
17979         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
17980       }
17981       if ((SraAmt + 1) != EltBits)
17982         return SDValue();
17983
17984       SDLoc DL(N);
17985
17986       // Now we know we at least have a plendvb with the mask val.  See if
17987       // we can form a psignb/w/d.
17988       // psign = x.type == y.type == mask.type && y = sub(0, x);
17989       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17990           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17991           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17992         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17993                "Unsupported VT for PSIGN");
17994         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17995         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17996       }
17997       // PBLENDVB only available on SSE 4.1
17998       if (!Subtarget->hasSSE41())
17999         return SDValue();
18000
18001       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18002
18003       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18004       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18005       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18006       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18007       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18008     }
18009   }
18010
18011   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18012     return SDValue();
18013
18014   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18015   MachineFunction &MF = DAG.getMachineFunction();
18016   bool OptForSize = MF.getFunction()->getAttributes().
18017     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18018
18019   // SHLD/SHRD instructions have lower register pressure, but on some
18020   // platforms they have higher latency than the equivalent
18021   // series of shifts/or that would otherwise be generated.
18022   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18023   // have higher latencies and we are not optimizing for size.
18024   if (!OptForSize && Subtarget->isSHLDSlow())
18025     return SDValue();
18026
18027   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18028     std::swap(N0, N1);
18029   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18030     return SDValue();
18031   if (!N0.hasOneUse() || !N1.hasOneUse())
18032     return SDValue();
18033
18034   SDValue ShAmt0 = N0.getOperand(1);
18035   if (ShAmt0.getValueType() != MVT::i8)
18036     return SDValue();
18037   SDValue ShAmt1 = N1.getOperand(1);
18038   if (ShAmt1.getValueType() != MVT::i8)
18039     return SDValue();
18040   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18041     ShAmt0 = ShAmt0.getOperand(0);
18042   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18043     ShAmt1 = ShAmt1.getOperand(0);
18044
18045   SDLoc DL(N);
18046   unsigned Opc = X86ISD::SHLD;
18047   SDValue Op0 = N0.getOperand(0);
18048   SDValue Op1 = N1.getOperand(0);
18049   if (ShAmt0.getOpcode() == ISD::SUB) {
18050     Opc = X86ISD::SHRD;
18051     std::swap(Op0, Op1);
18052     std::swap(ShAmt0, ShAmt1);
18053   }
18054
18055   unsigned Bits = VT.getSizeInBits();
18056   if (ShAmt1.getOpcode() == ISD::SUB) {
18057     SDValue Sum = ShAmt1.getOperand(0);
18058     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18059       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18060       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18061         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18062       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18063         return DAG.getNode(Opc, DL, VT,
18064                            Op0, Op1,
18065                            DAG.getNode(ISD::TRUNCATE, DL,
18066                                        MVT::i8, ShAmt0));
18067     }
18068   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18069     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18070     if (ShAmt0C &&
18071         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18072       return DAG.getNode(Opc, DL, VT,
18073                          N0.getOperand(0), N1.getOperand(0),
18074                          DAG.getNode(ISD::TRUNCATE, DL,
18075                                        MVT::i8, ShAmt0));
18076   }
18077
18078   return SDValue();
18079 }
18080
18081 // Generate NEG and CMOV for integer abs.
18082 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18083   EVT VT = N->getValueType(0);
18084
18085   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18086   // 8-bit integer abs to NEG and CMOV.
18087   if (VT.isInteger() && VT.getSizeInBits() == 8)
18088     return SDValue();
18089
18090   SDValue N0 = N->getOperand(0);
18091   SDValue N1 = N->getOperand(1);
18092   SDLoc DL(N);
18093
18094   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18095   // and change it to SUB and CMOV.
18096   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18097       N0.getOpcode() == ISD::ADD &&
18098       N0.getOperand(1) == N1 &&
18099       N1.getOpcode() == ISD::SRA &&
18100       N1.getOperand(0) == N0.getOperand(0))
18101     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18102       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18103         // Generate SUB & CMOV.
18104         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18105                                   DAG.getConstant(0, VT), N0.getOperand(0));
18106
18107         SDValue Ops[] = { N0.getOperand(0), Neg,
18108                           DAG.getConstant(X86::COND_GE, MVT::i8),
18109                           SDValue(Neg.getNode(), 1) };
18110         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18111                            Ops, array_lengthof(Ops));
18112       }
18113   return SDValue();
18114 }
18115
18116 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18117 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18118                                  TargetLowering::DAGCombinerInfo &DCI,
18119                                  const X86Subtarget *Subtarget) {
18120   EVT VT = N->getValueType(0);
18121   if (DCI.isBeforeLegalizeOps())
18122     return SDValue();
18123
18124   if (Subtarget->hasCMov()) {
18125     SDValue RV = performIntegerAbsCombine(N, DAG);
18126     if (RV.getNode())
18127       return RV;
18128   }
18129
18130   // Try forming BMI if it is available.
18131   if (!Subtarget->hasBMI())
18132     return SDValue();
18133
18134   if (VT != MVT::i32 && VT != MVT::i64)
18135     return SDValue();
18136
18137   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
18138
18139   // Create BLSMSK instructions by finding X ^ (X-1)
18140   SDValue N0 = N->getOperand(0);
18141   SDValue N1 = N->getOperand(1);
18142   SDLoc DL(N);
18143
18144   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
18145       isAllOnes(N0.getOperand(1)))
18146     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
18147
18148   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
18149       isAllOnes(N1.getOperand(1)))
18150     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
18151
18152   return SDValue();
18153 }
18154
18155 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18156 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18157                                   TargetLowering::DAGCombinerInfo &DCI,
18158                                   const X86Subtarget *Subtarget) {
18159   LoadSDNode *Ld = cast<LoadSDNode>(N);
18160   EVT RegVT = Ld->getValueType(0);
18161   EVT MemVT = Ld->getMemoryVT();
18162   SDLoc dl(Ld);
18163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18164   unsigned RegSz = RegVT.getSizeInBits();
18165
18166   // On Sandybridge unaligned 256bit loads are inefficient.
18167   ISD::LoadExtType Ext = Ld->getExtensionType();
18168   unsigned Alignment = Ld->getAlignment();
18169   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18170   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18171       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18172     unsigned NumElems = RegVT.getVectorNumElements();
18173     if (NumElems < 2)
18174       return SDValue();
18175
18176     SDValue Ptr = Ld->getBasePtr();
18177     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18178
18179     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18180                                   NumElems/2);
18181     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18182                                 Ld->getPointerInfo(), Ld->isVolatile(),
18183                                 Ld->isNonTemporal(), Ld->isInvariant(),
18184                                 Alignment);
18185     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18186     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18187                                 Ld->getPointerInfo(), Ld->isVolatile(),
18188                                 Ld->isNonTemporal(), Ld->isInvariant(),
18189                                 std::min(16U, Alignment));
18190     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18191                              Load1.getValue(1),
18192                              Load2.getValue(1));
18193
18194     SDValue NewVec = DAG.getUNDEF(RegVT);
18195     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18196     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18197     return DCI.CombineTo(N, NewVec, TF, true);
18198   }
18199
18200   // If this is a vector EXT Load then attempt to optimize it using a
18201   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18202   // expansion is still better than scalar code.
18203   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18204   // emit a shuffle and a arithmetic shift.
18205   // TODO: It is possible to support ZExt by zeroing the undef values
18206   // during the shuffle phase or after the shuffle.
18207   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18208       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18209     assert(MemVT != RegVT && "Cannot extend to the same type");
18210     assert(MemVT.isVector() && "Must load a vector from memory");
18211
18212     unsigned NumElems = RegVT.getVectorNumElements();
18213     unsigned MemSz = MemVT.getSizeInBits();
18214     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18215
18216     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18217       return SDValue();
18218
18219     // All sizes must be a power of two.
18220     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18221       return SDValue();
18222
18223     // Attempt to load the original value using scalar loads.
18224     // Find the largest scalar type that divides the total loaded size.
18225     MVT SclrLoadTy = MVT::i8;
18226     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18227          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18228       MVT Tp = (MVT::SimpleValueType)tp;
18229       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18230         SclrLoadTy = Tp;
18231       }
18232     }
18233
18234     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18235     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18236         (64 <= MemSz))
18237       SclrLoadTy = MVT::f64;
18238
18239     // Calculate the number of scalar loads that we need to perform
18240     // in order to load our vector from memory.
18241     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18242     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18243       return SDValue();
18244
18245     unsigned loadRegZize = RegSz;
18246     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18247       loadRegZize /= 2;
18248
18249     // Represent our vector as a sequence of elements which are the
18250     // largest scalar that we can load.
18251     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18252       loadRegZize/SclrLoadTy.getSizeInBits());
18253
18254     // Represent the data using the same element type that is stored in
18255     // memory. In practice, we ''widen'' MemVT.
18256     EVT WideVecVT =
18257           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18258                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18259
18260     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18261       "Invalid vector type");
18262
18263     // We can't shuffle using an illegal type.
18264     if (!TLI.isTypeLegal(WideVecVT))
18265       return SDValue();
18266
18267     SmallVector<SDValue, 8> Chains;
18268     SDValue Ptr = Ld->getBasePtr();
18269     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18270                                         TLI.getPointerTy());
18271     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18272
18273     for (unsigned i = 0; i < NumLoads; ++i) {
18274       // Perform a single load.
18275       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18276                                        Ptr, Ld->getPointerInfo(),
18277                                        Ld->isVolatile(), Ld->isNonTemporal(),
18278                                        Ld->isInvariant(), Ld->getAlignment());
18279       Chains.push_back(ScalarLoad.getValue(1));
18280       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18281       // another round of DAGCombining.
18282       if (i == 0)
18283         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18284       else
18285         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18286                           ScalarLoad, DAG.getIntPtrConstant(i));
18287
18288       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18289     }
18290
18291     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18292                                Chains.size());
18293
18294     // Bitcast the loaded value to a vector of the original element type, in
18295     // the size of the target vector type.
18296     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18297     unsigned SizeRatio = RegSz/MemSz;
18298
18299     if (Ext == ISD::SEXTLOAD) {
18300       // If we have SSE4.1 we can directly emit a VSEXT node.
18301       if (Subtarget->hasSSE41()) {
18302         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18303         return DCI.CombineTo(N, Sext, TF, true);
18304       }
18305
18306       // Otherwise we'll shuffle the small elements in the high bits of the
18307       // larger type and perform an arithmetic shift. If the shift is not legal
18308       // it's better to scalarize.
18309       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18310         return SDValue();
18311
18312       // Redistribute the loaded elements into the different locations.
18313       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18314       for (unsigned i = 0; i != NumElems; ++i)
18315         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18316
18317       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18318                                            DAG.getUNDEF(WideVecVT),
18319                                            &ShuffleVec[0]);
18320
18321       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18322
18323       // Build the arithmetic shift.
18324       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18325                      MemVT.getVectorElementType().getSizeInBits();
18326       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18327                           DAG.getConstant(Amt, RegVT));
18328
18329       return DCI.CombineTo(N, Shuff, TF, true);
18330     }
18331
18332     // Redistribute the loaded elements into the different locations.
18333     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18334     for (unsigned i = 0; i != NumElems; ++i)
18335       ShuffleVec[i*SizeRatio] = i;
18336
18337     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18338                                          DAG.getUNDEF(WideVecVT),
18339                                          &ShuffleVec[0]);
18340
18341     // Bitcast to the requested type.
18342     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18343     // Replace the original load with the new sequence
18344     // and return the new chain.
18345     return DCI.CombineTo(N, Shuff, TF, true);
18346   }
18347
18348   return SDValue();
18349 }
18350
18351 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18352 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18353                                    const X86Subtarget *Subtarget) {
18354   StoreSDNode *St = cast<StoreSDNode>(N);
18355   EVT VT = St->getValue().getValueType();
18356   EVT StVT = St->getMemoryVT();
18357   SDLoc dl(St);
18358   SDValue StoredVal = St->getOperand(1);
18359   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18360
18361   // If we are saving a concatenation of two XMM registers, perform two stores.
18362   // On Sandy Bridge, 256-bit memory operations are executed by two
18363   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18364   // memory  operation.
18365   unsigned Alignment = St->getAlignment();
18366   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18367   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18368       StVT == VT && !IsAligned) {
18369     unsigned NumElems = VT.getVectorNumElements();
18370     if (NumElems < 2)
18371       return SDValue();
18372
18373     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18374     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18375
18376     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18377     SDValue Ptr0 = St->getBasePtr();
18378     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18379
18380     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18381                                 St->getPointerInfo(), St->isVolatile(),
18382                                 St->isNonTemporal(), Alignment);
18383     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18384                                 St->getPointerInfo(), St->isVolatile(),
18385                                 St->isNonTemporal(),
18386                                 std::min(16U, Alignment));
18387     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18388   }
18389
18390   // Optimize trunc store (of multiple scalars) to shuffle and store.
18391   // First, pack all of the elements in one place. Next, store to memory
18392   // in fewer chunks.
18393   if (St->isTruncatingStore() && VT.isVector()) {
18394     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18395     unsigned NumElems = VT.getVectorNumElements();
18396     assert(StVT != VT && "Cannot truncate to the same type");
18397     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18398     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18399
18400     // From, To sizes and ElemCount must be pow of two
18401     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18402     // We are going to use the original vector elt for storing.
18403     // Accumulated smaller vector elements must be a multiple of the store size.
18404     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18405
18406     unsigned SizeRatio  = FromSz / ToSz;
18407
18408     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18409
18410     // Create a type on which we perform the shuffle
18411     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18412             StVT.getScalarType(), NumElems*SizeRatio);
18413
18414     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18415
18416     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18417     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18418     for (unsigned i = 0; i != NumElems; ++i)
18419       ShuffleVec[i] = i * SizeRatio;
18420
18421     // Can't shuffle using an illegal type.
18422     if (!TLI.isTypeLegal(WideVecVT))
18423       return SDValue();
18424
18425     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18426                                          DAG.getUNDEF(WideVecVT),
18427                                          &ShuffleVec[0]);
18428     // At this point all of the data is stored at the bottom of the
18429     // register. We now need to save it to mem.
18430
18431     // Find the largest store unit
18432     MVT StoreType = MVT::i8;
18433     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18434          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18435       MVT Tp = (MVT::SimpleValueType)tp;
18436       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18437         StoreType = Tp;
18438     }
18439
18440     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18441     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18442         (64 <= NumElems * ToSz))
18443       StoreType = MVT::f64;
18444
18445     // Bitcast the original vector into a vector of store-size units
18446     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18447             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18448     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18449     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18450     SmallVector<SDValue, 8> Chains;
18451     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18452                                         TLI.getPointerTy());
18453     SDValue Ptr = St->getBasePtr();
18454
18455     // Perform one or more big stores into memory.
18456     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18457       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18458                                    StoreType, ShuffWide,
18459                                    DAG.getIntPtrConstant(i));
18460       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18461                                 St->getPointerInfo(), St->isVolatile(),
18462                                 St->isNonTemporal(), St->getAlignment());
18463       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18464       Chains.push_back(Ch);
18465     }
18466
18467     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18468                                Chains.size());
18469   }
18470
18471   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18472   // the FP state in cases where an emms may be missing.
18473   // A preferable solution to the general problem is to figure out the right
18474   // places to insert EMMS.  This qualifies as a quick hack.
18475
18476   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18477   if (VT.getSizeInBits() != 64)
18478     return SDValue();
18479
18480   const Function *F = DAG.getMachineFunction().getFunction();
18481   bool NoImplicitFloatOps = F->getAttributes().
18482     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18483   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18484                      && Subtarget->hasSSE2();
18485   if ((VT.isVector() ||
18486        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18487       isa<LoadSDNode>(St->getValue()) &&
18488       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18489       St->getChain().hasOneUse() && !St->isVolatile()) {
18490     SDNode* LdVal = St->getValue().getNode();
18491     LoadSDNode *Ld = 0;
18492     int TokenFactorIndex = -1;
18493     SmallVector<SDValue, 8> Ops;
18494     SDNode* ChainVal = St->getChain().getNode();
18495     // Must be a store of a load.  We currently handle two cases:  the load
18496     // is a direct child, and it's under an intervening TokenFactor.  It is
18497     // possible to dig deeper under nested TokenFactors.
18498     if (ChainVal == LdVal)
18499       Ld = cast<LoadSDNode>(St->getChain());
18500     else if (St->getValue().hasOneUse() &&
18501              ChainVal->getOpcode() == ISD::TokenFactor) {
18502       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18503         if (ChainVal->getOperand(i).getNode() == LdVal) {
18504           TokenFactorIndex = i;
18505           Ld = cast<LoadSDNode>(St->getValue());
18506         } else
18507           Ops.push_back(ChainVal->getOperand(i));
18508       }
18509     }
18510
18511     if (!Ld || !ISD::isNormalLoad(Ld))
18512       return SDValue();
18513
18514     // If this is not the MMX case, i.e. we are just turning i64 load/store
18515     // into f64 load/store, avoid the transformation if there are multiple
18516     // uses of the loaded value.
18517     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18518       return SDValue();
18519
18520     SDLoc LdDL(Ld);
18521     SDLoc StDL(N);
18522     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18523     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18524     // pair instead.
18525     if (Subtarget->is64Bit() || F64IsLegal) {
18526       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18527       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18528                                   Ld->getPointerInfo(), Ld->isVolatile(),
18529                                   Ld->isNonTemporal(), Ld->isInvariant(),
18530                                   Ld->getAlignment());
18531       SDValue NewChain = NewLd.getValue(1);
18532       if (TokenFactorIndex != -1) {
18533         Ops.push_back(NewChain);
18534         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18535                                Ops.size());
18536       }
18537       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18538                           St->getPointerInfo(),
18539                           St->isVolatile(), St->isNonTemporal(),
18540                           St->getAlignment());
18541     }
18542
18543     // Otherwise, lower to two pairs of 32-bit loads / stores.
18544     SDValue LoAddr = Ld->getBasePtr();
18545     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18546                                  DAG.getConstant(4, MVT::i32));
18547
18548     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18549                                Ld->getPointerInfo(),
18550                                Ld->isVolatile(), Ld->isNonTemporal(),
18551                                Ld->isInvariant(), Ld->getAlignment());
18552     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18553                                Ld->getPointerInfo().getWithOffset(4),
18554                                Ld->isVolatile(), Ld->isNonTemporal(),
18555                                Ld->isInvariant(),
18556                                MinAlign(Ld->getAlignment(), 4));
18557
18558     SDValue NewChain = LoLd.getValue(1);
18559     if (TokenFactorIndex != -1) {
18560       Ops.push_back(LoLd);
18561       Ops.push_back(HiLd);
18562       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18563                              Ops.size());
18564     }
18565
18566     LoAddr = St->getBasePtr();
18567     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18568                          DAG.getConstant(4, MVT::i32));
18569
18570     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18571                                 St->getPointerInfo(),
18572                                 St->isVolatile(), St->isNonTemporal(),
18573                                 St->getAlignment());
18574     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18575                                 St->getPointerInfo().getWithOffset(4),
18576                                 St->isVolatile(),
18577                                 St->isNonTemporal(),
18578                                 MinAlign(St->getAlignment(), 4));
18579     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18580   }
18581   return SDValue();
18582 }
18583
18584 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18585 /// and return the operands for the horizontal operation in LHS and RHS.  A
18586 /// horizontal operation performs the binary operation on successive elements
18587 /// of its first operand, then on successive elements of its second operand,
18588 /// returning the resulting values in a vector.  For example, if
18589 ///   A = < float a0, float a1, float a2, float a3 >
18590 /// and
18591 ///   B = < float b0, float b1, float b2, float b3 >
18592 /// then the result of doing a horizontal operation on A and B is
18593 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18594 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18595 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18596 /// set to A, RHS to B, and the routine returns 'true'.
18597 /// Note that the binary operation should have the property that if one of the
18598 /// operands is UNDEF then the result is UNDEF.
18599 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18600   // Look for the following pattern: if
18601   //   A = < float a0, float a1, float a2, float a3 >
18602   //   B = < float b0, float b1, float b2, float b3 >
18603   // and
18604   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18605   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18606   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18607   // which is A horizontal-op B.
18608
18609   // At least one of the operands should be a vector shuffle.
18610   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18611       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18612     return false;
18613
18614   MVT VT = LHS.getSimpleValueType();
18615
18616   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18617          "Unsupported vector type for horizontal add/sub");
18618
18619   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18620   // operate independently on 128-bit lanes.
18621   unsigned NumElts = VT.getVectorNumElements();
18622   unsigned NumLanes = VT.getSizeInBits()/128;
18623   unsigned NumLaneElts = NumElts / NumLanes;
18624   assert((NumLaneElts % 2 == 0) &&
18625          "Vector type should have an even number of elements in each lane");
18626   unsigned HalfLaneElts = NumLaneElts/2;
18627
18628   // View LHS in the form
18629   //   LHS = VECTOR_SHUFFLE A, B, LMask
18630   // If LHS is not a shuffle then pretend it is the shuffle
18631   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18632   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18633   // type VT.
18634   SDValue A, B;
18635   SmallVector<int, 16> LMask(NumElts);
18636   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18637     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18638       A = LHS.getOperand(0);
18639     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18640       B = LHS.getOperand(1);
18641     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18642     std::copy(Mask.begin(), Mask.end(), LMask.begin());
18643   } else {
18644     if (LHS.getOpcode() != ISD::UNDEF)
18645       A = LHS;
18646     for (unsigned i = 0; i != NumElts; ++i)
18647       LMask[i] = i;
18648   }
18649
18650   // Likewise, view RHS in the form
18651   //   RHS = VECTOR_SHUFFLE C, D, RMask
18652   SDValue C, D;
18653   SmallVector<int, 16> RMask(NumElts);
18654   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18655     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
18656       C = RHS.getOperand(0);
18657     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
18658       D = RHS.getOperand(1);
18659     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
18660     std::copy(Mask.begin(), Mask.end(), RMask.begin());
18661   } else {
18662     if (RHS.getOpcode() != ISD::UNDEF)
18663       C = RHS;
18664     for (unsigned i = 0; i != NumElts; ++i)
18665       RMask[i] = i;
18666   }
18667
18668   // Check that the shuffles are both shuffling the same vectors.
18669   if (!(A == C && B == D) && !(A == D && B == C))
18670     return false;
18671
18672   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
18673   if (!A.getNode() && !B.getNode())
18674     return false;
18675
18676   // If A and B occur in reverse order in RHS, then "swap" them (which means
18677   // rewriting the mask).
18678   if (A != C)
18679     CommuteVectorShuffleMask(RMask, NumElts);
18680
18681   // At this point LHS and RHS are equivalent to
18682   //   LHS = VECTOR_SHUFFLE A, B, LMask
18683   //   RHS = VECTOR_SHUFFLE A, B, RMask
18684   // Check that the masks correspond to performing a horizontal operation.
18685   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
18686     for (unsigned i = 0; i != NumLaneElts; ++i) {
18687       int LIdx = LMask[i+l], RIdx = RMask[i+l];
18688
18689       // Ignore any UNDEF components.
18690       if (LIdx < 0 || RIdx < 0 ||
18691           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
18692           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
18693         continue;
18694
18695       // Check that successive elements are being operated on.  If not, this is
18696       // not a horizontal operation.
18697       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
18698       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
18699       if (!(LIdx == Index && RIdx == Index + 1) &&
18700           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
18701         return false;
18702     }
18703   }
18704
18705   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
18706   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
18707   return true;
18708 }
18709
18710 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
18711 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
18712                                   const X86Subtarget *Subtarget) {
18713   EVT VT = N->getValueType(0);
18714   SDValue LHS = N->getOperand(0);
18715   SDValue RHS = N->getOperand(1);
18716
18717   // Try to synthesize horizontal adds from adds of shuffles.
18718   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18719        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18720       isHorizontalBinOp(LHS, RHS, true))
18721     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
18722   return SDValue();
18723 }
18724
18725 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
18726 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
18727                                   const X86Subtarget *Subtarget) {
18728   EVT VT = N->getValueType(0);
18729   SDValue LHS = N->getOperand(0);
18730   SDValue RHS = N->getOperand(1);
18731
18732   // Try to synthesize horizontal subs from subs of shuffles.
18733   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18734        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18735       isHorizontalBinOp(LHS, RHS, false))
18736     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18737   return SDValue();
18738 }
18739
18740 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18741 /// X86ISD::FXOR nodes.
18742 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18743   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18744   // F[X]OR(0.0, x) -> x
18745   // F[X]OR(x, 0.0) -> x
18746   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18747     if (C->getValueAPF().isPosZero())
18748       return N->getOperand(1);
18749   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18750     if (C->getValueAPF().isPosZero())
18751       return N->getOperand(0);
18752   return SDValue();
18753 }
18754
18755 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18756 /// X86ISD::FMAX nodes.
18757 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18758   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18759
18760   // Only perform optimizations if UnsafeMath is used.
18761   if (!DAG.getTarget().Options.UnsafeFPMath)
18762     return SDValue();
18763
18764   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18765   // into FMINC and FMAXC, which are Commutative operations.
18766   unsigned NewOp = 0;
18767   switch (N->getOpcode()) {
18768     default: llvm_unreachable("unknown opcode");
18769     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
18770     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
18771   }
18772
18773   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18774                      N->getOperand(0), N->getOperand(1));
18775 }
18776
18777 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18778 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18779   // FAND(0.0, x) -> 0.0
18780   // FAND(x, 0.0) -> 0.0
18781   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18782     if (C->getValueAPF().isPosZero())
18783       return N->getOperand(0);
18784   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18785     if (C->getValueAPF().isPosZero())
18786       return N->getOperand(1);
18787   return SDValue();
18788 }
18789
18790 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18791 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18792   // FANDN(x, 0.0) -> 0.0
18793   // FANDN(0.0, x) -> x
18794   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18795     if (C->getValueAPF().isPosZero())
18796       return N->getOperand(1);
18797   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18798     if (C->getValueAPF().isPosZero())
18799       return N->getOperand(1);
18800   return SDValue();
18801 }
18802
18803 static SDValue PerformBTCombine(SDNode *N,
18804                                 SelectionDAG &DAG,
18805                                 TargetLowering::DAGCombinerInfo &DCI) {
18806   // BT ignores high bits in the bit index operand.
18807   SDValue Op1 = N->getOperand(1);
18808   if (Op1.hasOneUse()) {
18809     unsigned BitWidth = Op1.getValueSizeInBits();
18810     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18811     APInt KnownZero, KnownOne;
18812     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18813                                           !DCI.isBeforeLegalizeOps());
18814     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18815     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18816         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18817       DCI.CommitTargetLoweringOpt(TLO);
18818   }
18819   return SDValue();
18820 }
18821
18822 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18823   SDValue Op = N->getOperand(0);
18824   if (Op.getOpcode() == ISD::BITCAST)
18825     Op = Op.getOperand(0);
18826   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18827   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18828       VT.getVectorElementType().getSizeInBits() ==
18829       OpVT.getVectorElementType().getSizeInBits()) {
18830     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18831   }
18832   return SDValue();
18833 }
18834
18835 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18836                                                const X86Subtarget *Subtarget) {
18837   EVT VT = N->getValueType(0);
18838   if (!VT.isVector())
18839     return SDValue();
18840
18841   SDValue N0 = N->getOperand(0);
18842   SDValue N1 = N->getOperand(1);
18843   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18844   SDLoc dl(N);
18845
18846   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18847   // both SSE and AVX2 since there is no sign-extended shift right
18848   // operation on a vector with 64-bit elements.
18849   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18850   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18851   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18852       N0.getOpcode() == ISD::SIGN_EXTEND)) {
18853     SDValue N00 = N0.getOperand(0);
18854
18855     // EXTLOAD has a better solution on AVX2,
18856     // it may be replaced with X86ISD::VSEXT node.
18857     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18858       if (!ISD::isNormalLoad(N00.getNode()))
18859         return SDValue();
18860
18861     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18862         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18863                                   N00, N1);
18864       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18865     }
18866   }
18867   return SDValue();
18868 }
18869
18870 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18871                                   TargetLowering::DAGCombinerInfo &DCI,
18872                                   const X86Subtarget *Subtarget) {
18873   if (!DCI.isBeforeLegalizeOps())
18874     return SDValue();
18875
18876   if (!Subtarget->hasFp256())
18877     return SDValue();
18878
18879   EVT VT = N->getValueType(0);
18880   if (VT.isVector() && VT.getSizeInBits() == 256) {
18881     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18882     if (R.getNode())
18883       return R;
18884   }
18885
18886   return SDValue();
18887 }
18888
18889 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18890                                  const X86Subtarget* Subtarget) {
18891   SDLoc dl(N);
18892   EVT VT = N->getValueType(0);
18893
18894   // Let legalize expand this if it isn't a legal type yet.
18895   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18896     return SDValue();
18897
18898   EVT ScalarVT = VT.getScalarType();
18899   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18900       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18901     return SDValue();
18902
18903   SDValue A = N->getOperand(0);
18904   SDValue B = N->getOperand(1);
18905   SDValue C = N->getOperand(2);
18906
18907   bool NegA = (A.getOpcode() == ISD::FNEG);
18908   bool NegB = (B.getOpcode() == ISD::FNEG);
18909   bool NegC = (C.getOpcode() == ISD::FNEG);
18910
18911   // Negative multiplication when NegA xor NegB
18912   bool NegMul = (NegA != NegB);
18913   if (NegA)
18914     A = A.getOperand(0);
18915   if (NegB)
18916     B = B.getOperand(0);
18917   if (NegC)
18918     C = C.getOperand(0);
18919
18920   unsigned Opcode;
18921   if (!NegMul)
18922     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18923   else
18924     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18925
18926   return DAG.getNode(Opcode, dl, VT, A, B, C);
18927 }
18928
18929 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18930                                   TargetLowering::DAGCombinerInfo &DCI,
18931                                   const X86Subtarget *Subtarget) {
18932   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18933   //           (and (i32 x86isd::setcc_carry), 1)
18934   // This eliminates the zext. This transformation is necessary because
18935   // ISD::SETCC is always legalized to i8.
18936   SDLoc dl(N);
18937   SDValue N0 = N->getOperand(0);
18938   EVT VT = N->getValueType(0);
18939
18940   if (N0.getOpcode() == ISD::AND &&
18941       N0.hasOneUse() &&
18942       N0.getOperand(0).hasOneUse()) {
18943     SDValue N00 = N0.getOperand(0);
18944     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18945       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18946       if (!C || C->getZExtValue() != 1)
18947         return SDValue();
18948       return DAG.getNode(ISD::AND, dl, VT,
18949                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18950                                      N00.getOperand(0), N00.getOperand(1)),
18951                          DAG.getConstant(1, VT));
18952     }
18953   }
18954
18955   if (N0.getOpcode() == ISD::TRUNCATE &&
18956       N0.hasOneUse() &&
18957       N0.getOperand(0).hasOneUse()) {
18958     SDValue N00 = N0.getOperand(0);
18959     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18960       return DAG.getNode(ISD::AND, dl, VT,
18961                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18962                                      N00.getOperand(0), N00.getOperand(1)),
18963                          DAG.getConstant(1, VT));
18964     }
18965   }
18966   if (VT.is256BitVector()) {
18967     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18968     if (R.getNode())
18969       return R;
18970   }
18971
18972   return SDValue();
18973 }
18974
18975 // Optimize x == -y --> x+y == 0
18976 //          x != -y --> x+y != 0
18977 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18978   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18979   SDValue LHS = N->getOperand(0);
18980   SDValue RHS = N->getOperand(1);
18981
18982   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18983     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18984       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18985         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18986                                    LHS.getValueType(), RHS, LHS.getOperand(1));
18987         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18988                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18989       }
18990   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18991     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18992       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18993         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18994                                    RHS.getValueType(), LHS, RHS.getOperand(1));
18995         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18996                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18997       }
18998   return SDValue();
18999 }
19000
19001 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19002 // as "sbb reg,reg", since it can be extended without zext and produces
19003 // an all-ones bit which is more useful than 0/1 in some cases.
19004 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19005                                MVT VT) {
19006   if (VT == MVT::i8)
19007     return DAG.getNode(ISD::AND, DL, VT,
19008                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19009                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19010                        DAG.getConstant(1, VT));
19011   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19012   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19013                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19014                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19015 }
19016
19017 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19018 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19019                                    TargetLowering::DAGCombinerInfo &DCI,
19020                                    const X86Subtarget *Subtarget) {
19021   SDLoc DL(N);
19022   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19023   SDValue EFLAGS = N->getOperand(1);
19024
19025   if (CC == X86::COND_A) {
19026     // Try to convert COND_A into COND_B in an attempt to facilitate
19027     // materializing "setb reg".
19028     //
19029     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19030     // cannot take an immediate as its first operand.
19031     //
19032     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19033         EFLAGS.getValueType().isInteger() &&
19034         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19035       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19036                                    EFLAGS.getNode()->getVTList(),
19037                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19038       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19039       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19040     }
19041   }
19042
19043   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19044   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19045   // cases.
19046   if (CC == X86::COND_B)
19047     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19048
19049   SDValue Flags;
19050
19051   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19052   if (Flags.getNode()) {
19053     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19054     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19055   }
19056
19057   return SDValue();
19058 }
19059
19060 // Optimize branch condition evaluation.
19061 //
19062 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19063                                     TargetLowering::DAGCombinerInfo &DCI,
19064                                     const X86Subtarget *Subtarget) {
19065   SDLoc DL(N);
19066   SDValue Chain = N->getOperand(0);
19067   SDValue Dest = N->getOperand(1);
19068   SDValue EFLAGS = N->getOperand(3);
19069   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19070
19071   SDValue Flags;
19072
19073   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19074   if (Flags.getNode()) {
19075     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19076     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19077                        Flags);
19078   }
19079
19080   return SDValue();
19081 }
19082
19083 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19084                                         const X86TargetLowering *XTLI) {
19085   SDValue Op0 = N->getOperand(0);
19086   EVT InVT = Op0->getValueType(0);
19087
19088   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19089   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19090     SDLoc dl(N);
19091     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19092     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19093     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19094   }
19095
19096   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19097   // a 32-bit target where SSE doesn't support i64->FP operations.
19098   if (Op0.getOpcode() == ISD::LOAD) {
19099     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19100     EVT VT = Ld->getValueType(0);
19101     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19102         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19103         !XTLI->getSubtarget()->is64Bit() &&
19104         VT == MVT::i64) {
19105       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19106                                           Ld->getChain(), Op0, DAG);
19107       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19108       return FILDChain;
19109     }
19110   }
19111   return SDValue();
19112 }
19113
19114 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19115 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19116                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19117   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19118   // the result is either zero or one (depending on the input carry bit).
19119   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19120   if (X86::isZeroNode(N->getOperand(0)) &&
19121       X86::isZeroNode(N->getOperand(1)) &&
19122       // We don't have a good way to replace an EFLAGS use, so only do this when
19123       // dead right now.
19124       SDValue(N, 1).use_empty()) {
19125     SDLoc DL(N);
19126     EVT VT = N->getValueType(0);
19127     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19128     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19129                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19130                                            DAG.getConstant(X86::COND_B,MVT::i8),
19131                                            N->getOperand(2)),
19132                                DAG.getConstant(1, VT));
19133     return DCI.CombineTo(N, Res1, CarryOut);
19134   }
19135
19136   return SDValue();
19137 }
19138
19139 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19140 //      (add Y, (setne X, 0)) -> sbb -1, Y
19141 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19142 //      (sub (setne X, 0), Y) -> adc -1, Y
19143 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19144   SDLoc DL(N);
19145
19146   // Look through ZExts.
19147   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19148   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19149     return SDValue();
19150
19151   SDValue SetCC = Ext.getOperand(0);
19152   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19153     return SDValue();
19154
19155   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19156   if (CC != X86::COND_E && CC != X86::COND_NE)
19157     return SDValue();
19158
19159   SDValue Cmp = SetCC.getOperand(1);
19160   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19161       !X86::isZeroNode(Cmp.getOperand(1)) ||
19162       !Cmp.getOperand(0).getValueType().isInteger())
19163     return SDValue();
19164
19165   SDValue CmpOp0 = Cmp.getOperand(0);
19166   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19167                                DAG.getConstant(1, CmpOp0.getValueType()));
19168
19169   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19170   if (CC == X86::COND_NE)
19171     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19172                        DL, OtherVal.getValueType(), OtherVal,
19173                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19174   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19175                      DL, OtherVal.getValueType(), OtherVal,
19176                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19177 }
19178
19179 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19180 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19181                                  const X86Subtarget *Subtarget) {
19182   EVT VT = N->getValueType(0);
19183   SDValue Op0 = N->getOperand(0);
19184   SDValue Op1 = N->getOperand(1);
19185
19186   // Try to synthesize horizontal adds from adds of shuffles.
19187   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19188        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19189       isHorizontalBinOp(Op0, Op1, true))
19190     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19191
19192   return OptimizeConditionalInDecrement(N, DAG);
19193 }
19194
19195 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19196                                  const X86Subtarget *Subtarget) {
19197   SDValue Op0 = N->getOperand(0);
19198   SDValue Op1 = N->getOperand(1);
19199
19200   // X86 can't encode an immediate LHS of a sub. See if we can push the
19201   // negation into a preceding instruction.
19202   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19203     // If the RHS of the sub is a XOR with one use and a constant, invert the
19204     // immediate. Then add one to the LHS of the sub so we can turn
19205     // X-Y -> X+~Y+1, saving one register.
19206     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19207         isa<ConstantSDNode>(Op1.getOperand(1))) {
19208       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19209       EVT VT = Op0.getValueType();
19210       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19211                                    Op1.getOperand(0),
19212                                    DAG.getConstant(~XorC, VT));
19213       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19214                          DAG.getConstant(C->getAPIntValue()+1, VT));
19215     }
19216   }
19217
19218   // Try to synthesize horizontal adds from adds of shuffles.
19219   EVT VT = N->getValueType(0);
19220   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19221        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19222       isHorizontalBinOp(Op0, Op1, true))
19223     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19224
19225   return OptimizeConditionalInDecrement(N, DAG);
19226 }
19227
19228 /// performVZEXTCombine - Performs build vector combines
19229 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19230                                         TargetLowering::DAGCombinerInfo &DCI,
19231                                         const X86Subtarget *Subtarget) {
19232   // (vzext (bitcast (vzext (x)) -> (vzext x)
19233   SDValue In = N->getOperand(0);
19234   while (In.getOpcode() == ISD::BITCAST)
19235     In = In.getOperand(0);
19236
19237   if (In.getOpcode() != X86ISD::VZEXT)
19238     return SDValue();
19239
19240   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19241                      In.getOperand(0));
19242 }
19243
19244 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19245                                              DAGCombinerInfo &DCI) const {
19246   SelectionDAG &DAG = DCI.DAG;
19247   switch (N->getOpcode()) {
19248   default: break;
19249   case ISD::EXTRACT_VECTOR_ELT:
19250     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19251   case ISD::VSELECT:
19252   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19253   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19254   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19255   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19256   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19257   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19258   case ISD::SHL:
19259   case ISD::SRA:
19260   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19261   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19262   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19263   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19264   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19265   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19266   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19267   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19268   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19269   case X86ISD::FXOR:
19270   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19271   case X86ISD::FMIN:
19272   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19273   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19274   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19275   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19276   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19277   case ISD::ANY_EXTEND:
19278   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19279   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19280   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19281   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19282   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
19283   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19284   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19285   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19286   case X86ISD::SHUFP:       // Handle all target specific shuffles
19287   case X86ISD::PALIGNR:
19288   case X86ISD::UNPCKH:
19289   case X86ISD::UNPCKL:
19290   case X86ISD::MOVHLPS:
19291   case X86ISD::MOVLHPS:
19292   case X86ISD::PSHUFD:
19293   case X86ISD::PSHUFHW:
19294   case X86ISD::PSHUFLW:
19295   case X86ISD::MOVSS:
19296   case X86ISD::MOVSD:
19297   case X86ISD::VPERMILP:
19298   case X86ISD::VPERM2X128:
19299   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19300   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19301   }
19302
19303   return SDValue();
19304 }
19305
19306 /// isTypeDesirableForOp - Return true if the target has native support for
19307 /// the specified value type and it is 'desirable' to use the type for the
19308 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19309 /// instruction encodings are longer and some i16 instructions are slow.
19310 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19311   if (!isTypeLegal(VT))
19312     return false;
19313   if (VT != MVT::i16)
19314     return true;
19315
19316   switch (Opc) {
19317   default:
19318     return true;
19319   case ISD::LOAD:
19320   case ISD::SIGN_EXTEND:
19321   case ISD::ZERO_EXTEND:
19322   case ISD::ANY_EXTEND:
19323   case ISD::SHL:
19324   case ISD::SRL:
19325   case ISD::SUB:
19326   case ISD::ADD:
19327   case ISD::MUL:
19328   case ISD::AND:
19329   case ISD::OR:
19330   case ISD::XOR:
19331     return false;
19332   }
19333 }
19334
19335 /// IsDesirableToPromoteOp - This method query the target whether it is
19336 /// beneficial for dag combiner to promote the specified node. If true, it
19337 /// should return the desired promotion type by reference.
19338 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19339   EVT VT = Op.getValueType();
19340   if (VT != MVT::i16)
19341     return false;
19342
19343   bool Promote = false;
19344   bool Commute = false;
19345   switch (Op.getOpcode()) {
19346   default: break;
19347   case ISD::LOAD: {
19348     LoadSDNode *LD = cast<LoadSDNode>(Op);
19349     // If the non-extending load has a single use and it's not live out, then it
19350     // might be folded.
19351     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19352                                                      Op.hasOneUse()*/) {
19353       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19354              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19355         // The only case where we'd want to promote LOAD (rather then it being
19356         // promoted as an operand is when it's only use is liveout.
19357         if (UI->getOpcode() != ISD::CopyToReg)
19358           return false;
19359       }
19360     }
19361     Promote = true;
19362     break;
19363   }
19364   case ISD::SIGN_EXTEND:
19365   case ISD::ZERO_EXTEND:
19366   case ISD::ANY_EXTEND:
19367     Promote = true;
19368     break;
19369   case ISD::SHL:
19370   case ISD::SRL: {
19371     SDValue N0 = Op.getOperand(0);
19372     // Look out for (store (shl (load), x)).
19373     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19374       return false;
19375     Promote = true;
19376     break;
19377   }
19378   case ISD::ADD:
19379   case ISD::MUL:
19380   case ISD::AND:
19381   case ISD::OR:
19382   case ISD::XOR:
19383     Commute = true;
19384     // fallthrough
19385   case ISD::SUB: {
19386     SDValue N0 = Op.getOperand(0);
19387     SDValue N1 = Op.getOperand(1);
19388     if (!Commute && MayFoldLoad(N1))
19389       return false;
19390     // Avoid disabling potential load folding opportunities.
19391     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19392       return false;
19393     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19394       return false;
19395     Promote = true;
19396   }
19397   }
19398
19399   PVT = MVT::i32;
19400   return Promote;
19401 }
19402
19403 //===----------------------------------------------------------------------===//
19404 //                           X86 Inline Assembly Support
19405 //===----------------------------------------------------------------------===//
19406
19407 namespace {
19408   // Helper to match a string separated by whitespace.
19409   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19410     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19411
19412     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19413       StringRef piece(*args[i]);
19414       if (!s.startswith(piece)) // Check if the piece matches.
19415         return false;
19416
19417       s = s.substr(piece.size());
19418       StringRef::size_type pos = s.find_first_not_of(" \t");
19419       if (pos == 0) // We matched a prefix.
19420         return false;
19421
19422       s = s.substr(pos);
19423     }
19424
19425     return s.empty();
19426   }
19427   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19428 }
19429
19430 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19431
19432   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19433     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19434         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19435         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19436
19437       if (AsmPieces.size() == 3)
19438         return true;
19439       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19440         return true;
19441     }
19442   }
19443   return false;
19444 }
19445
19446 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19447   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19448
19449   std::string AsmStr = IA->getAsmString();
19450
19451   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19452   if (!Ty || Ty->getBitWidth() % 16 != 0)
19453     return false;
19454
19455   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19456   SmallVector<StringRef, 4> AsmPieces;
19457   SplitString(AsmStr, AsmPieces, ";\n");
19458
19459   switch (AsmPieces.size()) {
19460   default: return false;
19461   case 1:
19462     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19463     // we will turn this bswap into something that will be lowered to logical
19464     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19465     // lower so don't worry about this.
19466     // bswap $0
19467     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19468         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19469         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19470         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19471         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19472         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19473       // No need to check constraints, nothing other than the equivalent of
19474       // "=r,0" would be valid here.
19475       return IntrinsicLowering::LowerToByteSwap(CI);
19476     }
19477
19478     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19479     if (CI->getType()->isIntegerTy(16) &&
19480         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19481         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19482          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19483       AsmPieces.clear();
19484       const std::string &ConstraintsStr = IA->getConstraintString();
19485       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19486       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19487       if (clobbersFlagRegisters(AsmPieces))
19488         return IntrinsicLowering::LowerToByteSwap(CI);
19489     }
19490     break;
19491   case 3:
19492     if (CI->getType()->isIntegerTy(32) &&
19493         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19494         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19495         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19496         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19497       AsmPieces.clear();
19498       const std::string &ConstraintsStr = IA->getConstraintString();
19499       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19500       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19501       if (clobbersFlagRegisters(AsmPieces))
19502         return IntrinsicLowering::LowerToByteSwap(CI);
19503     }
19504
19505     if (CI->getType()->isIntegerTy(64)) {
19506       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19507       if (Constraints.size() >= 2 &&
19508           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19509           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19510         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19511         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19512             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19513             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19514           return IntrinsicLowering::LowerToByteSwap(CI);
19515       }
19516     }
19517     break;
19518   }
19519   return false;
19520 }
19521
19522 /// getConstraintType - Given a constraint letter, return the type of
19523 /// constraint it is for this target.
19524 X86TargetLowering::ConstraintType
19525 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19526   if (Constraint.size() == 1) {
19527     switch (Constraint[0]) {
19528     case 'R':
19529     case 'q':
19530     case 'Q':
19531     case 'f':
19532     case 't':
19533     case 'u':
19534     case 'y':
19535     case 'x':
19536     case 'Y':
19537     case 'l':
19538       return C_RegisterClass;
19539     case 'a':
19540     case 'b':
19541     case 'c':
19542     case 'd':
19543     case 'S':
19544     case 'D':
19545     case 'A':
19546       return C_Register;
19547     case 'I':
19548     case 'J':
19549     case 'K':
19550     case 'L':
19551     case 'M':
19552     case 'N':
19553     case 'G':
19554     case 'C':
19555     case 'e':
19556     case 'Z':
19557       return C_Other;
19558     default:
19559       break;
19560     }
19561   }
19562   return TargetLowering::getConstraintType(Constraint);
19563 }
19564
19565 /// Examine constraint type and operand type and determine a weight value.
19566 /// This object must already have been set up with the operand type
19567 /// and the current alternative constraint selected.
19568 TargetLowering::ConstraintWeight
19569   X86TargetLowering::getSingleConstraintMatchWeight(
19570     AsmOperandInfo &info, const char *constraint) const {
19571   ConstraintWeight weight = CW_Invalid;
19572   Value *CallOperandVal = info.CallOperandVal;
19573     // If we don't have a value, we can't do a match,
19574     // but allow it at the lowest weight.
19575   if (CallOperandVal == NULL)
19576     return CW_Default;
19577   Type *type = CallOperandVal->getType();
19578   // Look at the constraint type.
19579   switch (*constraint) {
19580   default:
19581     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19582   case 'R':
19583   case 'q':
19584   case 'Q':
19585   case 'a':
19586   case 'b':
19587   case 'c':
19588   case 'd':
19589   case 'S':
19590   case 'D':
19591   case 'A':
19592     if (CallOperandVal->getType()->isIntegerTy())
19593       weight = CW_SpecificReg;
19594     break;
19595   case 'f':
19596   case 't':
19597   case 'u':
19598     if (type->isFloatingPointTy())
19599       weight = CW_SpecificReg;
19600     break;
19601   case 'y':
19602     if (type->isX86_MMXTy() && Subtarget->hasMMX())
19603       weight = CW_SpecificReg;
19604     break;
19605   case 'x':
19606   case 'Y':
19607     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19608         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19609       weight = CW_Register;
19610     break;
19611   case 'I':
19612     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19613       if (C->getZExtValue() <= 31)
19614         weight = CW_Constant;
19615     }
19616     break;
19617   case 'J':
19618     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19619       if (C->getZExtValue() <= 63)
19620         weight = CW_Constant;
19621     }
19622     break;
19623   case 'K':
19624     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19625       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
19626         weight = CW_Constant;
19627     }
19628     break;
19629   case 'L':
19630     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19631       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
19632         weight = CW_Constant;
19633     }
19634     break;
19635   case 'M':
19636     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19637       if (C->getZExtValue() <= 3)
19638         weight = CW_Constant;
19639     }
19640     break;
19641   case 'N':
19642     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19643       if (C->getZExtValue() <= 0xff)
19644         weight = CW_Constant;
19645     }
19646     break;
19647   case 'G':
19648   case 'C':
19649     if (dyn_cast<ConstantFP>(CallOperandVal)) {
19650       weight = CW_Constant;
19651     }
19652     break;
19653   case 'e':
19654     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19655       if ((C->getSExtValue() >= -0x80000000LL) &&
19656           (C->getSExtValue() <= 0x7fffffffLL))
19657         weight = CW_Constant;
19658     }
19659     break;
19660   case 'Z':
19661     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19662       if (C->getZExtValue() <= 0xffffffff)
19663         weight = CW_Constant;
19664     }
19665     break;
19666   }
19667   return weight;
19668 }
19669
19670 /// LowerXConstraint - try to replace an X constraint, which matches anything,
19671 /// with another that has more specific requirements based on the type of the
19672 /// corresponding operand.
19673 const char *X86TargetLowering::
19674 LowerXConstraint(EVT ConstraintVT) const {
19675   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
19676   // 'f' like normal targets.
19677   if (ConstraintVT.isFloatingPoint()) {
19678     if (Subtarget->hasSSE2())
19679       return "Y";
19680     if (Subtarget->hasSSE1())
19681       return "x";
19682   }
19683
19684   return TargetLowering::LowerXConstraint(ConstraintVT);
19685 }
19686
19687 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19688 /// vector.  If it is invalid, don't add anything to Ops.
19689 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19690                                                      std::string &Constraint,
19691                                                      std::vector<SDValue>&Ops,
19692                                                      SelectionDAG &DAG) const {
19693   SDValue Result(0, 0);
19694
19695   // Only support length 1 constraints for now.
19696   if (Constraint.length() > 1) return;
19697
19698   char ConstraintLetter = Constraint[0];
19699   switch (ConstraintLetter) {
19700   default: break;
19701   case 'I':
19702     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19703       if (C->getZExtValue() <= 31) {
19704         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19705         break;
19706       }
19707     }
19708     return;
19709   case 'J':
19710     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19711       if (C->getZExtValue() <= 63) {
19712         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19713         break;
19714       }
19715     }
19716     return;
19717   case 'K':
19718     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19719       if (isInt<8>(C->getSExtValue())) {
19720         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19721         break;
19722       }
19723     }
19724     return;
19725   case 'N':
19726     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19727       if (C->getZExtValue() <= 255) {
19728         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19729         break;
19730       }
19731     }
19732     return;
19733   case 'e': {
19734     // 32-bit signed value
19735     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19736       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19737                                            C->getSExtValue())) {
19738         // Widen to 64 bits here to get it sign extended.
19739         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
19740         break;
19741       }
19742     // FIXME gcc accepts some relocatable values here too, but only in certain
19743     // memory models; it's complicated.
19744     }
19745     return;
19746   }
19747   case 'Z': {
19748     // 32-bit unsigned value
19749     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19750       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19751                                            C->getZExtValue())) {
19752         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19753         break;
19754       }
19755     }
19756     // FIXME gcc accepts some relocatable values here too, but only in certain
19757     // memory models; it's complicated.
19758     return;
19759   }
19760   case 'i': {
19761     // Literal immediates are always ok.
19762     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19763       // Widen to 64 bits here to get it sign extended.
19764       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19765       break;
19766     }
19767
19768     // In any sort of PIC mode addresses need to be computed at runtime by
19769     // adding in a register or some sort of table lookup.  These can't
19770     // be used as immediates.
19771     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19772       return;
19773
19774     // If we are in non-pic codegen mode, we allow the address of a global (with
19775     // an optional displacement) to be used with 'i'.
19776     GlobalAddressSDNode *GA = 0;
19777     int64_t Offset = 0;
19778
19779     // Match either (GA), (GA+C), (GA+C1+C2), etc.
19780     while (1) {
19781       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19782         Offset += GA->getOffset();
19783         break;
19784       } else if (Op.getOpcode() == ISD::ADD) {
19785         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19786           Offset += C->getZExtValue();
19787           Op = Op.getOperand(0);
19788           continue;
19789         }
19790       } else if (Op.getOpcode() == ISD::SUB) {
19791         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19792           Offset += -C->getZExtValue();
19793           Op = Op.getOperand(0);
19794           continue;
19795         }
19796       }
19797
19798       // Otherwise, this isn't something we can handle, reject it.
19799       return;
19800     }
19801
19802     const GlobalValue *GV = GA->getGlobal();
19803     // If we require an extra load to get this address, as in PIC mode, we
19804     // can't accept it.
19805     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19806                                                         getTargetMachine())))
19807       return;
19808
19809     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19810                                         GA->getValueType(0), Offset);
19811     break;
19812   }
19813   }
19814
19815   if (Result.getNode()) {
19816     Ops.push_back(Result);
19817     return;
19818   }
19819   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19820 }
19821
19822 std::pair<unsigned, const TargetRegisterClass*>
19823 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19824                                                 MVT VT) const {
19825   // First, see if this is a constraint that directly corresponds to an LLVM
19826   // register class.
19827   if (Constraint.size() == 1) {
19828     // GCC Constraint Letters
19829     switch (Constraint[0]) {
19830     default: break;
19831       // TODO: Slight differences here in allocation order and leaving
19832       // RIP in the class. Do they matter any more here than they do
19833       // in the normal allocation?
19834     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19835       if (Subtarget->is64Bit()) {
19836         if (VT == MVT::i32 || VT == MVT::f32)
19837           return std::make_pair(0U, &X86::GR32RegClass);
19838         if (VT == MVT::i16)
19839           return std::make_pair(0U, &X86::GR16RegClass);
19840         if (VT == MVT::i8 || VT == MVT::i1)
19841           return std::make_pair(0U, &X86::GR8RegClass);
19842         if (VT == MVT::i64 || VT == MVT::f64)
19843           return std::make_pair(0U, &X86::GR64RegClass);
19844         break;
19845       }
19846       // 32-bit fallthrough
19847     case 'Q':   // Q_REGS
19848       if (VT == MVT::i32 || VT == MVT::f32)
19849         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19850       if (VT == MVT::i16)
19851         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19852       if (VT == MVT::i8 || VT == MVT::i1)
19853         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19854       if (VT == MVT::i64)
19855         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19856       break;
19857     case 'r':   // GENERAL_REGS
19858     case 'l':   // INDEX_REGS
19859       if (VT == MVT::i8 || VT == MVT::i1)
19860         return std::make_pair(0U, &X86::GR8RegClass);
19861       if (VT == MVT::i16)
19862         return std::make_pair(0U, &X86::GR16RegClass);
19863       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19864         return std::make_pair(0U, &X86::GR32RegClass);
19865       return std::make_pair(0U, &X86::GR64RegClass);
19866     case 'R':   // LEGACY_REGS
19867       if (VT == MVT::i8 || VT == MVT::i1)
19868         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19869       if (VT == MVT::i16)
19870         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19871       if (VT == MVT::i32 || !Subtarget->is64Bit())
19872         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19873       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19874     case 'f':  // FP Stack registers.
19875       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19876       // value to the correct fpstack register class.
19877       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19878         return std::make_pair(0U, &X86::RFP32RegClass);
19879       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19880         return std::make_pair(0U, &X86::RFP64RegClass);
19881       return std::make_pair(0U, &X86::RFP80RegClass);
19882     case 'y':   // MMX_REGS if MMX allowed.
19883       if (!Subtarget->hasMMX()) break;
19884       return std::make_pair(0U, &X86::VR64RegClass);
19885     case 'Y':   // SSE_REGS if SSE2 allowed
19886       if (!Subtarget->hasSSE2()) break;
19887       // FALL THROUGH.
19888     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19889       if (!Subtarget->hasSSE1()) break;
19890
19891       switch (VT.SimpleTy) {
19892       default: break;
19893       // Scalar SSE types.
19894       case MVT::f32:
19895       case MVT::i32:
19896         return std::make_pair(0U, &X86::FR32RegClass);
19897       case MVT::f64:
19898       case MVT::i64:
19899         return std::make_pair(0U, &X86::FR64RegClass);
19900       // Vector types.
19901       case MVT::v16i8:
19902       case MVT::v8i16:
19903       case MVT::v4i32:
19904       case MVT::v2i64:
19905       case MVT::v4f32:
19906       case MVT::v2f64:
19907         return std::make_pair(0U, &X86::VR128RegClass);
19908       // AVX types.
19909       case MVT::v32i8:
19910       case MVT::v16i16:
19911       case MVT::v8i32:
19912       case MVT::v4i64:
19913       case MVT::v8f32:
19914       case MVT::v4f64:
19915         return std::make_pair(0U, &X86::VR256RegClass);
19916       case MVT::v8f64:
19917       case MVT::v16f32:
19918       case MVT::v16i32:
19919       case MVT::v8i64:
19920         return std::make_pair(0U, &X86::VR512RegClass);
19921       }
19922       break;
19923     }
19924   }
19925
19926   // Use the default implementation in TargetLowering to convert the register
19927   // constraint into a member of a register class.
19928   std::pair<unsigned, const TargetRegisterClass*> Res;
19929   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19930
19931   // Not found as a standard register?
19932   if (Res.second == 0) {
19933     // Map st(0) -> st(7) -> ST0
19934     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19935         tolower(Constraint[1]) == 's' &&
19936         tolower(Constraint[2]) == 't' &&
19937         Constraint[3] == '(' &&
19938         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19939         Constraint[5] == ')' &&
19940         Constraint[6] == '}') {
19941
19942       Res.first = X86::ST0+Constraint[4]-'0';
19943       Res.second = &X86::RFP80RegClass;
19944       return Res;
19945     }
19946
19947     // GCC allows "st(0)" to be called just plain "st".
19948     if (StringRef("{st}").equals_lower(Constraint)) {
19949       Res.first = X86::ST0;
19950       Res.second = &X86::RFP80RegClass;
19951       return Res;
19952     }
19953
19954     // flags -> EFLAGS
19955     if (StringRef("{flags}").equals_lower(Constraint)) {
19956       Res.first = X86::EFLAGS;
19957       Res.second = &X86::CCRRegClass;
19958       return Res;
19959     }
19960
19961     // 'A' means EAX + EDX.
19962     if (Constraint == "A") {
19963       Res.first = X86::EAX;
19964       Res.second = &X86::GR32_ADRegClass;
19965       return Res;
19966     }
19967     return Res;
19968   }
19969
19970   // Otherwise, check to see if this is a register class of the wrong value
19971   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19972   // turn into {ax},{dx}.
19973   if (Res.second->hasType(VT))
19974     return Res;   // Correct type already, nothing to do.
19975
19976   // All of the single-register GCC register classes map their values onto
19977   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
19978   // really want an 8-bit or 32-bit register, map to the appropriate register
19979   // class and return the appropriate register.
19980   if (Res.second == &X86::GR16RegClass) {
19981     if (VT == MVT::i8 || VT == MVT::i1) {
19982       unsigned DestReg = 0;
19983       switch (Res.first) {
19984       default: break;
19985       case X86::AX: DestReg = X86::AL; break;
19986       case X86::DX: DestReg = X86::DL; break;
19987       case X86::CX: DestReg = X86::CL; break;
19988       case X86::BX: DestReg = X86::BL; break;
19989       }
19990       if (DestReg) {
19991         Res.first = DestReg;
19992         Res.second = &X86::GR8RegClass;
19993       }
19994     } else if (VT == MVT::i32 || VT == MVT::f32) {
19995       unsigned DestReg = 0;
19996       switch (Res.first) {
19997       default: break;
19998       case X86::AX: DestReg = X86::EAX; break;
19999       case X86::DX: DestReg = X86::EDX; break;
20000       case X86::CX: DestReg = X86::ECX; break;
20001       case X86::BX: DestReg = X86::EBX; break;
20002       case X86::SI: DestReg = X86::ESI; break;
20003       case X86::DI: DestReg = X86::EDI; break;
20004       case X86::BP: DestReg = X86::EBP; break;
20005       case X86::SP: DestReg = X86::ESP; break;
20006       }
20007       if (DestReg) {
20008         Res.first = DestReg;
20009         Res.second = &X86::GR32RegClass;
20010       }
20011     } else if (VT == MVT::i64 || VT == MVT::f64) {
20012       unsigned DestReg = 0;
20013       switch (Res.first) {
20014       default: break;
20015       case X86::AX: DestReg = X86::RAX; break;
20016       case X86::DX: DestReg = X86::RDX; break;
20017       case X86::CX: DestReg = X86::RCX; break;
20018       case X86::BX: DestReg = X86::RBX; break;
20019       case X86::SI: DestReg = X86::RSI; break;
20020       case X86::DI: DestReg = X86::RDI; break;
20021       case X86::BP: DestReg = X86::RBP; break;
20022       case X86::SP: DestReg = X86::RSP; break;
20023       }
20024       if (DestReg) {
20025         Res.first = DestReg;
20026         Res.second = &X86::GR64RegClass;
20027       }
20028     }
20029   } else if (Res.second == &X86::FR32RegClass ||
20030              Res.second == &X86::FR64RegClass ||
20031              Res.second == &X86::VR128RegClass ||
20032              Res.second == &X86::VR256RegClass ||
20033              Res.second == &X86::FR32XRegClass ||
20034              Res.second == &X86::FR64XRegClass ||
20035              Res.second == &X86::VR128XRegClass ||
20036              Res.second == &X86::VR256XRegClass ||
20037              Res.second == &X86::VR512RegClass) {
20038     // Handle references to XMM physical registers that got mapped into the
20039     // wrong class.  This can happen with constraints like {xmm0} where the
20040     // target independent register mapper will just pick the first match it can
20041     // find, ignoring the required type.
20042
20043     if (VT == MVT::f32 || VT == MVT::i32)
20044       Res.second = &X86::FR32RegClass;
20045     else if (VT == MVT::f64 || VT == MVT::i64)
20046       Res.second = &X86::FR64RegClass;
20047     else if (X86::VR128RegClass.hasType(VT))
20048       Res.second = &X86::VR128RegClass;
20049     else if (X86::VR256RegClass.hasType(VT))
20050       Res.second = &X86::VR256RegClass;
20051     else if (X86::VR512RegClass.hasType(VT))
20052       Res.second = &X86::VR512RegClass;
20053   }
20054
20055   return Res;
20056 }