cd2f5a2946f85d520654384033f05f4f46511565
[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     In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(1, InVT));
9084     if (InVT.getSizeInBits() == 64)
9085       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9086     else if (InVT.getSizeInBits() < 32)
9087       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9088     return DAG.getNode(X86ISD::TRUNC, DL, VT, In);
9089   }
9090   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9091          "Invalid TRUNCATE operation");
9092
9093   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9094     if (VT.getVectorElementType().getSizeInBits() >=8)
9095       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9096
9097     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9098     unsigned NumElts = InVT.getVectorNumElements();
9099     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9100     if (InVT.getSizeInBits() < 512) {
9101       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9102       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9103       InVT = ExtVT;
9104     }
9105     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9106     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9107     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9108     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9109     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9110                            MachinePointerInfo::getConstantPool(),
9111                            false, false, false, Alignment);
9112     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9113     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9114     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9115   }
9116
9117   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9118     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9119     if (Subtarget->hasInt256()) {
9120       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9121       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9122       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9123                                 ShufMask);
9124       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9125                          DAG.getIntPtrConstant(0));
9126     }
9127
9128     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
9129     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9130                                DAG.getIntPtrConstant(0));
9131     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9132                                DAG.getIntPtrConstant(2));
9133
9134     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9135     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9136
9137     // The PSHUFD mask:
9138     static const int ShufMask1[] = {0, 2, 0, 0};
9139     SDValue Undef = DAG.getUNDEF(VT);
9140     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
9141     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
9142
9143     // The MOVLHPS mask:
9144     static const int ShufMask2[] = {0, 1, 4, 5};
9145     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
9146   }
9147
9148   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9149     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9150     if (Subtarget->hasInt256()) {
9151       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9152
9153       SmallVector<SDValue,32> pshufbMask;
9154       for (unsigned i = 0; i < 2; ++i) {
9155         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9156         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9157         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9158         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9159         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9160         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9161         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9162         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9163         for (unsigned j = 0; j < 8; ++j)
9164           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9165       }
9166       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9167                                &pshufbMask[0], 32);
9168       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9169       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9170
9171       static const int ShufMask[] = {0,  2,  -1,  -1};
9172       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9173                                 &ShufMask[0]);
9174       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9175                        DAG.getIntPtrConstant(0));
9176       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9177     }
9178
9179     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9180                                DAG.getIntPtrConstant(0));
9181
9182     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9183                                DAG.getIntPtrConstant(4));
9184
9185     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9186     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9187
9188     // The PSHUFB mask:
9189     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9190                                    -1, -1, -1, -1, -1, -1, -1, -1};
9191
9192     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9193     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9194     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9195
9196     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9197     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9198
9199     // The MOVLHPS Mask:
9200     static const int ShufMask2[] = {0, 1, 4, 5};
9201     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9202     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9203   }
9204
9205   // Handle truncation of V256 to V128 using shuffles.
9206   if (!VT.is128BitVector() || !InVT.is256BitVector())
9207     return SDValue();
9208
9209   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9210
9211   unsigned NumElems = VT.getVectorNumElements();
9212   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9213                              NumElems * 2);
9214
9215   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9216   // Prepare truncation shuffle mask
9217   for (unsigned i = 0; i != NumElems; ++i)
9218     MaskVec[i] = i * 2;
9219   SDValue V = DAG.getVectorShuffle(NVT, DL,
9220                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9221                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9222   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9223                      DAG.getIntPtrConstant(0));
9224 }
9225
9226 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9227                                            SelectionDAG &DAG) const {
9228   MVT VT = Op.getSimpleValueType();
9229   if (VT.isVector()) {
9230     if (VT == MVT::v8i16)
9231       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9232                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9233                                      MVT::v8i32, Op.getOperand(0)));
9234     return SDValue();
9235   }
9236
9237   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9238     /*IsSigned=*/ true, /*IsReplace=*/ false);
9239   SDValue FIST = Vals.first, StackSlot = Vals.second;
9240   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9241   if (FIST.getNode() == 0) return Op;
9242
9243   if (StackSlot.getNode())
9244     // Load the result.
9245     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9246                        FIST, StackSlot, MachinePointerInfo(),
9247                        false, false, false, 0);
9248
9249   // The node is the result.
9250   return FIST;
9251 }
9252
9253 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9254                                            SelectionDAG &DAG) const {
9255   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9256     /*IsSigned=*/ false, /*IsReplace=*/ false);
9257   SDValue FIST = Vals.first, StackSlot = Vals.second;
9258   assert(FIST.getNode() && "Unexpected failure");
9259
9260   if (StackSlot.getNode())
9261     // Load the result.
9262     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9263                        FIST, StackSlot, MachinePointerInfo(),
9264                        false, false, false, 0);
9265
9266   // The node is the result.
9267   return FIST;
9268 }
9269
9270 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9271   SDLoc DL(Op);
9272   MVT VT = Op.getSimpleValueType();
9273   SDValue In = Op.getOperand(0);
9274   MVT SVT = In.getSimpleValueType();
9275
9276   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9277
9278   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9279                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9280                                  In, DAG.getUNDEF(SVT)));
9281 }
9282
9283 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9284   LLVMContext *Context = DAG.getContext();
9285   SDLoc dl(Op);
9286   MVT VT = Op.getSimpleValueType();
9287   MVT EltVT = VT;
9288   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9289   if (VT.isVector()) {
9290     EltVT = VT.getVectorElementType();
9291     NumElts = VT.getVectorNumElements();
9292   }
9293   Constant *C;
9294   if (EltVT == MVT::f64)
9295     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9296                                           APInt(64, ~(1ULL << 63))));
9297   else
9298     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9299                                           APInt(32, ~(1U << 31))));
9300   C = ConstantVector::getSplat(NumElts, C);
9301   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9302   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9303   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9304                              MachinePointerInfo::getConstantPool(),
9305                              false, false, false, Alignment);
9306   if (VT.isVector()) {
9307     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9308     return DAG.getNode(ISD::BITCAST, dl, VT,
9309                        DAG.getNode(ISD::AND, dl, ANDVT,
9310                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9311                                                Op.getOperand(0)),
9312                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9313   }
9314   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9315 }
9316
9317 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9318   LLVMContext *Context = DAG.getContext();
9319   SDLoc dl(Op);
9320   MVT VT = Op.getSimpleValueType();
9321   MVT EltVT = VT;
9322   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9323   if (VT.isVector()) {
9324     EltVT = VT.getVectorElementType();
9325     NumElts = VT.getVectorNumElements();
9326   }
9327   Constant *C;
9328   if (EltVT == MVT::f64)
9329     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9330                                           APInt(64, 1ULL << 63)));
9331   else
9332     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9333                                           APInt(32, 1U << 31)));
9334   C = ConstantVector::getSplat(NumElts, C);
9335   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9336   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9337   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9338                              MachinePointerInfo::getConstantPool(),
9339                              false, false, false, Alignment);
9340   if (VT.isVector()) {
9341     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9342     return DAG.getNode(ISD::BITCAST, dl, VT,
9343                        DAG.getNode(ISD::XOR, dl, XORVT,
9344                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9345                                                Op.getOperand(0)),
9346                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9347   }
9348
9349   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9350 }
9351
9352 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9353   LLVMContext *Context = DAG.getContext();
9354   SDValue Op0 = Op.getOperand(0);
9355   SDValue Op1 = Op.getOperand(1);
9356   SDLoc dl(Op);
9357   MVT VT = Op.getSimpleValueType();
9358   MVT SrcVT = Op1.getSimpleValueType();
9359
9360   // If second operand is smaller, extend it first.
9361   if (SrcVT.bitsLT(VT)) {
9362     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9363     SrcVT = VT;
9364   }
9365   // And if it is bigger, shrink it first.
9366   if (SrcVT.bitsGT(VT)) {
9367     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9368     SrcVT = VT;
9369   }
9370
9371   // At this point the operands and the result should have the same
9372   // type, and that won't be f80 since that is not custom lowered.
9373
9374   // First get the sign bit of second operand.
9375   SmallVector<Constant*,4> CV;
9376   if (SrcVT == MVT::f64) {
9377     const fltSemantics &Sem = APFloat::IEEEdouble;
9378     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9379     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9380   } else {
9381     const fltSemantics &Sem = APFloat::IEEEsingle;
9382     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9383     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
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   }
9387   Constant *C = ConstantVector::get(CV);
9388   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9389   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9390                               MachinePointerInfo::getConstantPool(),
9391                               false, false, false, 16);
9392   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9393
9394   // Shift sign bit right or left if the two operands have different types.
9395   if (SrcVT.bitsGT(VT)) {
9396     // Op0 is MVT::f32, Op1 is MVT::f64.
9397     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9398     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9399                           DAG.getConstant(32, MVT::i32));
9400     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9401     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9402                           DAG.getIntPtrConstant(0));
9403   }
9404
9405   // Clear first operand sign bit.
9406   CV.clear();
9407   if (VT == MVT::f64) {
9408     const fltSemantics &Sem = APFloat::IEEEdouble;
9409     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9410                                                    APInt(64, ~(1ULL << 63)))));
9411     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9412   } else {
9413     const fltSemantics &Sem = APFloat::IEEEsingle;
9414     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9415                                                    APInt(32, ~(1U << 31)))));
9416     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
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   }
9420   C = ConstantVector::get(CV);
9421   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9422   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9423                               MachinePointerInfo::getConstantPool(),
9424                               false, false, false, 16);
9425   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9426
9427   // Or the value with the sign bit.
9428   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9429 }
9430
9431 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9432   SDValue N0 = Op.getOperand(0);
9433   SDLoc dl(Op);
9434   MVT VT = Op.getSimpleValueType();
9435
9436   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9437   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9438                                   DAG.getConstant(1, VT));
9439   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9440 }
9441
9442 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9443 //
9444 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9445                                       SelectionDAG &DAG) {
9446   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9447
9448   if (!Subtarget->hasSSE41())
9449     return SDValue();
9450
9451   if (!Op->hasOneUse())
9452     return SDValue();
9453
9454   SDNode *N = Op.getNode();
9455   SDLoc DL(N);
9456
9457   SmallVector<SDValue, 8> Opnds;
9458   DenseMap<SDValue, unsigned> VecInMap;
9459   EVT VT = MVT::Other;
9460
9461   // Recognize a special case where a vector is casted into wide integer to
9462   // test all 0s.
9463   Opnds.push_back(N->getOperand(0));
9464   Opnds.push_back(N->getOperand(1));
9465
9466   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9467     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9468     // BFS traverse all OR'd operands.
9469     if (I->getOpcode() == ISD::OR) {
9470       Opnds.push_back(I->getOperand(0));
9471       Opnds.push_back(I->getOperand(1));
9472       // Re-evaluate the number of nodes to be traversed.
9473       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9474       continue;
9475     }
9476
9477     // Quit if a non-EXTRACT_VECTOR_ELT
9478     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9479       return SDValue();
9480
9481     // Quit if without a constant index.
9482     SDValue Idx = I->getOperand(1);
9483     if (!isa<ConstantSDNode>(Idx))
9484       return SDValue();
9485
9486     SDValue ExtractedFromVec = I->getOperand(0);
9487     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9488     if (M == VecInMap.end()) {
9489       VT = ExtractedFromVec.getValueType();
9490       // Quit if not 128/256-bit vector.
9491       if (!VT.is128BitVector() && !VT.is256BitVector())
9492         return SDValue();
9493       // Quit if not the same type.
9494       if (VecInMap.begin() != VecInMap.end() &&
9495           VT != VecInMap.begin()->first.getValueType())
9496         return SDValue();
9497       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9498     }
9499     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9500   }
9501
9502   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9503          "Not extracted from 128-/256-bit vector.");
9504
9505   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9506   SmallVector<SDValue, 8> VecIns;
9507
9508   for (DenseMap<SDValue, unsigned>::const_iterator
9509         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9510     // Quit if not all elements are used.
9511     if (I->second != FullMask)
9512       return SDValue();
9513     VecIns.push_back(I->first);
9514   }
9515
9516   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9517
9518   // Cast all vectors into TestVT for PTEST.
9519   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9520     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9521
9522   // If more than one full vectors are evaluated, OR them first before PTEST.
9523   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9524     // Each iteration will OR 2 nodes and append the result until there is only
9525     // 1 node left, i.e. the final OR'd value of all vectors.
9526     SDValue LHS = VecIns[Slot];
9527     SDValue RHS = VecIns[Slot + 1];
9528     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9529   }
9530
9531   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9532                      VecIns.back(), VecIns.back());
9533 }
9534
9535 /// Emit nodes that will be selected as "test Op0,Op0", or something
9536 /// equivalent.
9537 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9538                                     SelectionDAG &DAG) const {
9539   SDLoc dl(Op);
9540
9541   // CF and OF aren't always set the way we want. Determine which
9542   // of these we need.
9543   bool NeedCF = false;
9544   bool NeedOF = false;
9545   switch (X86CC) {
9546   default: break;
9547   case X86::COND_A: case X86::COND_AE:
9548   case X86::COND_B: case X86::COND_BE:
9549     NeedCF = true;
9550     break;
9551   case X86::COND_G: case X86::COND_GE:
9552   case X86::COND_L: case X86::COND_LE:
9553   case X86::COND_O: case X86::COND_NO:
9554     NeedOF = true;
9555     break;
9556   }
9557
9558   // See if we can use the EFLAGS value from the operand instead of
9559   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9560   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9561   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9562     // Emit a CMP with 0, which is the TEST pattern.
9563     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9564                        DAG.getConstant(0, Op.getValueType()));
9565
9566   unsigned Opcode = 0;
9567   unsigned NumOperands = 0;
9568
9569   // Truncate operations may prevent the merge of the SETCC instruction
9570   // and the arithmetic instruction before it. Attempt to truncate the operands
9571   // of the arithmetic instruction and use a reduced bit-width instruction.
9572   bool NeedTruncation = false;
9573   SDValue ArithOp = Op;
9574   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9575     SDValue Arith = Op->getOperand(0);
9576     // Both the trunc and the arithmetic op need to have one user each.
9577     if (Arith->hasOneUse())
9578       switch (Arith.getOpcode()) {
9579         default: break;
9580         case ISD::ADD:
9581         case ISD::SUB:
9582         case ISD::AND:
9583         case ISD::OR:
9584         case ISD::XOR: {
9585           NeedTruncation = true;
9586           ArithOp = Arith;
9587         }
9588       }
9589   }
9590
9591   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9592   // which may be the result of a CAST.  We use the variable 'Op', which is the
9593   // non-casted variable when we check for possible users.
9594   switch (ArithOp.getOpcode()) {
9595   case ISD::ADD:
9596     // Due to an isel shortcoming, be conservative if this add is likely to be
9597     // selected as part of a load-modify-store instruction. When the root node
9598     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9599     // uses of other nodes in the match, such as the ADD in this case. This
9600     // leads to the ADD being left around and reselected, with the result being
9601     // two adds in the output.  Alas, even if none our users are stores, that
9602     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9603     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9604     // climbing the DAG back to the root, and it doesn't seem to be worth the
9605     // effort.
9606     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9607          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9608       if (UI->getOpcode() != ISD::CopyToReg &&
9609           UI->getOpcode() != ISD::SETCC &&
9610           UI->getOpcode() != ISD::STORE)
9611         goto default_case;
9612
9613     if (ConstantSDNode *C =
9614         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9615       // An add of one will be selected as an INC.
9616       if (C->getAPIntValue() == 1) {
9617         Opcode = X86ISD::INC;
9618         NumOperands = 1;
9619         break;
9620       }
9621
9622       // An add of negative one (subtract of one) will be selected as a DEC.
9623       if (C->getAPIntValue().isAllOnesValue()) {
9624         Opcode = X86ISD::DEC;
9625         NumOperands = 1;
9626         break;
9627       }
9628     }
9629
9630     // Otherwise use a regular EFLAGS-setting add.
9631     Opcode = X86ISD::ADD;
9632     NumOperands = 2;
9633     break;
9634   case ISD::AND: {
9635     // If the primary and result isn't used, don't bother using X86ISD::AND,
9636     // because a TEST instruction will be better.
9637     bool NonFlagUse = false;
9638     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9639            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9640       SDNode *User = *UI;
9641       unsigned UOpNo = UI.getOperandNo();
9642       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9643         // Look pass truncate.
9644         UOpNo = User->use_begin().getOperandNo();
9645         User = *User->use_begin();
9646       }
9647
9648       if (User->getOpcode() != ISD::BRCOND &&
9649           User->getOpcode() != ISD::SETCC &&
9650           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9651         NonFlagUse = true;
9652         break;
9653       }
9654     }
9655
9656     if (!NonFlagUse)
9657       break;
9658   }
9659     // FALL THROUGH
9660   case ISD::SUB:
9661   case ISD::OR:
9662   case ISD::XOR:
9663     // Due to the ISEL shortcoming noted above, be conservative if this op is
9664     // likely to be selected as part of a load-modify-store instruction.
9665     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9666            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9667       if (UI->getOpcode() == ISD::STORE)
9668         goto default_case;
9669
9670     // Otherwise use a regular EFLAGS-setting instruction.
9671     switch (ArithOp.getOpcode()) {
9672     default: llvm_unreachable("unexpected operator!");
9673     case ISD::SUB: Opcode = X86ISD::SUB; break;
9674     case ISD::XOR: Opcode = X86ISD::XOR; break;
9675     case ISD::AND: Opcode = X86ISD::AND; break;
9676     case ISD::OR: {
9677       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9678         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9679         if (EFLAGS.getNode())
9680           return EFLAGS;
9681       }
9682       Opcode = X86ISD::OR;
9683       break;
9684     }
9685     }
9686
9687     NumOperands = 2;
9688     break;
9689   case X86ISD::ADD:
9690   case X86ISD::SUB:
9691   case X86ISD::INC:
9692   case X86ISD::DEC:
9693   case X86ISD::OR:
9694   case X86ISD::XOR:
9695   case X86ISD::AND:
9696     return SDValue(Op.getNode(), 1);
9697   default:
9698   default_case:
9699     break;
9700   }
9701
9702   // If we found that truncation is beneficial, perform the truncation and
9703   // update 'Op'.
9704   if (NeedTruncation) {
9705     EVT VT = Op.getValueType();
9706     SDValue WideVal = Op->getOperand(0);
9707     EVT WideVT = WideVal.getValueType();
9708     unsigned ConvertedOp = 0;
9709     // Use a target machine opcode to prevent further DAGCombine
9710     // optimizations that may separate the arithmetic operations
9711     // from the setcc node.
9712     switch (WideVal.getOpcode()) {
9713       default: break;
9714       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9715       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9716       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9717       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9718       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9719     }
9720
9721     if (ConvertedOp) {
9722       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9723       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9724         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9725         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9726         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9727       }
9728     }
9729   }
9730
9731   if (Opcode == 0)
9732     // Emit a CMP with 0, which is the TEST pattern.
9733     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9734                        DAG.getConstant(0, Op.getValueType()));
9735
9736   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9737   SmallVector<SDValue, 4> Ops;
9738   for (unsigned i = 0; i != NumOperands; ++i)
9739     Ops.push_back(Op.getOperand(i));
9740
9741   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9742   DAG.ReplaceAllUsesWith(Op, New);
9743   return SDValue(New.getNode(), 1);
9744 }
9745
9746 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9747 /// equivalent.
9748 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9749                                    SelectionDAG &DAG) const {
9750   SDLoc dl(Op0);
9751   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9752     if (C->getAPIntValue() == 0)
9753       return EmitTest(Op0, X86CC, DAG);
9754
9755      if (Op0.getValueType() == MVT::i1) {
9756       Op0 = DAG.getNode(ISD::XOR, dl, MVT::i1, Op0, DAG.getConstant(-1, MVT::i1));
9757       return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op0, Op0);
9758      }
9759   }
9760  
9761   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9762        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9763     // Do the comparison at i32 if it's smaller. This avoids subregister
9764     // aliasing issues. Keep the smaller reference if we're optimizing for
9765     // size, however, as that'll allow better folding of memory operations.
9766     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9767         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9768              AttributeSet::FunctionIndex, Attribute::MinSize)) {
9769       unsigned ExtendOp =
9770           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9771       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9772       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9773     }
9774     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9775     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9776     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9777                               Op0, Op1);
9778     return SDValue(Sub.getNode(), 1);
9779   }
9780   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9781 }
9782
9783 /// Convert a comparison if required by the subtarget.
9784 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9785                                                  SelectionDAG &DAG) const {
9786   // If the subtarget does not support the FUCOMI instruction, floating-point
9787   // comparisons have to be converted.
9788   if (Subtarget->hasCMov() ||
9789       Cmp.getOpcode() != X86ISD::CMP ||
9790       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9791       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9792     return Cmp;
9793
9794   // The instruction selector will select an FUCOM instruction instead of
9795   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9796   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9797   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9798   SDLoc dl(Cmp);
9799   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9800   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9801   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9802                             DAG.getConstant(8, MVT::i8));
9803   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9804   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9805 }
9806
9807 static bool isAllOnes(SDValue V) {
9808   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9809   return C && C->isAllOnesValue();
9810 }
9811
9812 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9813 /// if it's possible.
9814 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9815                                      SDLoc dl, SelectionDAG &DAG) const {
9816   SDValue Op0 = And.getOperand(0);
9817   SDValue Op1 = And.getOperand(1);
9818   if (Op0.getOpcode() == ISD::TRUNCATE)
9819     Op0 = Op0.getOperand(0);
9820   if (Op1.getOpcode() == ISD::TRUNCATE)
9821     Op1 = Op1.getOperand(0);
9822
9823   SDValue LHS, RHS;
9824   if (Op1.getOpcode() == ISD::SHL)
9825     std::swap(Op0, Op1);
9826   if (Op0.getOpcode() == ISD::SHL) {
9827     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9828       if (And00C->getZExtValue() == 1) {
9829         // If we looked past a truncate, check that it's only truncating away
9830         // known zeros.
9831         unsigned BitWidth = Op0.getValueSizeInBits();
9832         unsigned AndBitWidth = And.getValueSizeInBits();
9833         if (BitWidth > AndBitWidth) {
9834           APInt Zeros, Ones;
9835           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9836           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9837             return SDValue();
9838         }
9839         LHS = Op1;
9840         RHS = Op0.getOperand(1);
9841       }
9842   } else if (Op1.getOpcode() == ISD::Constant) {
9843     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9844     uint64_t AndRHSVal = AndRHS->getZExtValue();
9845     SDValue AndLHS = Op0;
9846
9847     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9848       LHS = AndLHS.getOperand(0);
9849       RHS = AndLHS.getOperand(1);
9850     }
9851
9852     // Use BT if the immediate can't be encoded in a TEST instruction.
9853     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9854       LHS = AndLHS;
9855       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9856     }
9857   }
9858
9859   if (LHS.getNode()) {
9860     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9861     // instruction.  Since the shift amount is in-range-or-undefined, we know
9862     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9863     // the encoding for the i16 version is larger than the i32 version.
9864     // Also promote i16 to i32 for performance / code size reason.
9865     if (LHS.getValueType() == MVT::i8 ||
9866         LHS.getValueType() == MVT::i16)
9867       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9868
9869     // If the operand types disagree, extend the shift amount to match.  Since
9870     // BT ignores high bits (like shifts) we can use anyextend.
9871     if (LHS.getValueType() != RHS.getValueType())
9872       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9873
9874     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9875     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9876     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9877                        DAG.getConstant(Cond, MVT::i8), BT);
9878   }
9879
9880   return SDValue();
9881 }
9882
9883 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9884 /// mask CMPs.
9885 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9886                               SDValue &Op1) {
9887   unsigned SSECC;
9888   bool Swap = false;
9889
9890   // SSE Condition code mapping:
9891   //  0 - EQ
9892   //  1 - LT
9893   //  2 - LE
9894   //  3 - UNORD
9895   //  4 - NEQ
9896   //  5 - NLT
9897   //  6 - NLE
9898   //  7 - ORD
9899   switch (SetCCOpcode) {
9900   default: llvm_unreachable("Unexpected SETCC condition");
9901   case ISD::SETOEQ:
9902   case ISD::SETEQ:  SSECC = 0; break;
9903   case ISD::SETOGT:
9904   case ISD::SETGT:  Swap = true; // Fallthrough
9905   case ISD::SETLT:
9906   case ISD::SETOLT: SSECC = 1; break;
9907   case ISD::SETOGE:
9908   case ISD::SETGE:  Swap = true; // Fallthrough
9909   case ISD::SETLE:
9910   case ISD::SETOLE: SSECC = 2; break;
9911   case ISD::SETUO:  SSECC = 3; break;
9912   case ISD::SETUNE:
9913   case ISD::SETNE:  SSECC = 4; break;
9914   case ISD::SETULE: Swap = true; // Fallthrough
9915   case ISD::SETUGE: SSECC = 5; break;
9916   case ISD::SETULT: Swap = true; // Fallthrough
9917   case ISD::SETUGT: SSECC = 6; break;
9918   case ISD::SETO:   SSECC = 7; break;
9919   case ISD::SETUEQ:
9920   case ISD::SETONE: SSECC = 8; break;
9921   }
9922   if (Swap)
9923     std::swap(Op0, Op1);
9924
9925   return SSECC;
9926 }
9927
9928 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9929 // ones, and then concatenate the result back.
9930 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9931   MVT VT = Op.getSimpleValueType();
9932
9933   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9934          "Unsupported value type for operation");
9935
9936   unsigned NumElems = VT.getVectorNumElements();
9937   SDLoc dl(Op);
9938   SDValue CC = Op.getOperand(2);
9939
9940   // Extract the LHS vectors
9941   SDValue LHS = Op.getOperand(0);
9942   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9943   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9944
9945   // Extract the RHS vectors
9946   SDValue RHS = Op.getOperand(1);
9947   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9948   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9949
9950   // Issue the operation on the smaller types and concatenate the result back
9951   MVT EltVT = VT.getVectorElementType();
9952   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9953   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9954                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9955                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9956 }
9957
9958 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9959   SDValue Op0 = Op.getOperand(0);
9960   SDValue Op1 = Op.getOperand(1);
9961   SDValue CC = Op.getOperand(2);
9962   MVT VT = Op.getSimpleValueType();
9963
9964   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9965          Op.getValueType().getScalarType() == MVT::i1 &&
9966          "Cannot set masked compare for this operation");
9967
9968   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9969   SDLoc dl(Op);
9970
9971   bool Unsigned = false;
9972   unsigned SSECC;
9973   switch (SetCCOpcode) {
9974   default: llvm_unreachable("Unexpected SETCC condition");
9975   case ISD::SETNE:  SSECC = 4; break;
9976   case ISD::SETEQ:  SSECC = 0; break;
9977   case ISD::SETUGT: Unsigned = true;
9978   case ISD::SETGT:  SSECC = 6; break; // NLE
9979   case ISD::SETULT: Unsigned = true;
9980   case ISD::SETLT:  SSECC = 1; break;
9981   case ISD::SETUGE: Unsigned = true;
9982   case ISD::SETGE:  SSECC = 5; break; // NLT
9983   case ISD::SETULE: Unsigned = true;
9984   case ISD::SETLE:  SSECC = 2; break;
9985   }
9986   unsigned  Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9987   return DAG.getNode(Opc, dl, VT, Op0, Op1,
9988                      DAG.getConstant(SSECC, MVT::i8));
9989
9990 }
9991
9992 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9993                            SelectionDAG &DAG) {
9994   SDValue Op0 = Op.getOperand(0);
9995   SDValue Op1 = Op.getOperand(1);
9996   SDValue CC = Op.getOperand(2);
9997   MVT VT = Op.getSimpleValueType();
9998   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9999   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10000   SDLoc dl(Op);
10001
10002   if (isFP) {
10003 #ifndef NDEBUG
10004     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10005     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10006 #endif
10007
10008     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10009     unsigned Opc = X86ISD::CMPP;
10010     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10011       assert(VT.getVectorNumElements() <= 16);
10012       Opc = X86ISD::CMPM;
10013     }
10014     // In the two special cases we can't handle, emit two comparisons.
10015     if (SSECC == 8) {
10016       unsigned CC0, CC1;
10017       unsigned CombineOpc;
10018       if (SetCCOpcode == ISD::SETUEQ) {
10019         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10020       } else {
10021         assert(SetCCOpcode == ISD::SETONE);
10022         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10023       }
10024
10025       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10026                                  DAG.getConstant(CC0, MVT::i8));
10027       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10028                                  DAG.getConstant(CC1, MVT::i8));
10029       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10030     }
10031     // Handle all other FP comparisons here.
10032     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10033                        DAG.getConstant(SSECC, MVT::i8));
10034   }
10035
10036   // Break 256-bit integer vector compare into smaller ones.
10037   if (VT.is256BitVector() && !Subtarget->hasInt256())
10038     return Lower256IntVSETCC(Op, DAG);
10039
10040   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10041   EVT OpVT = Op1.getValueType();
10042   if (Subtarget->hasAVX512()) {
10043     if (Op1.getValueType().is512BitVector() ||
10044         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10045       return LowerIntVSETCC_AVX512(Op, DAG);
10046
10047     // In AVX-512 architecture setcc returns mask with i1 elements,
10048     // But there is no compare instruction for i8 and i16 elements.
10049     // We are not talking about 512-bit operands in this case, these
10050     // types are illegal.
10051     if (MaskResult &&
10052         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10053          OpVT.getVectorElementType().getSizeInBits() >= 8))
10054       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10055                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10056   }
10057
10058   // We are handling one of the integer comparisons here.  Since SSE only has
10059   // GT and EQ comparisons for integer, swapping operands and multiple
10060   // operations may be required for some comparisons.
10061   unsigned Opc;
10062   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10063
10064   switch (SetCCOpcode) {
10065   default: llvm_unreachable("Unexpected SETCC condition");
10066   case ISD::SETNE:  Invert = true;
10067   case ISD::SETEQ:  Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
10068   case ISD::SETLT:  Swap = true;
10069   case ISD::SETGT:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
10070   case ISD::SETGE:  Swap = true;
10071   case ISD::SETLE:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10072                     Invert = true; break;
10073   case ISD::SETULT: Swap = true;
10074   case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10075                     FlipSigns = true; break;
10076   case ISD::SETUGE: Swap = true;
10077   case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10078                     FlipSigns = true; Invert = true; break;
10079   }
10080
10081   // Special case: Use min/max operations for SETULE/SETUGE
10082   MVT VET = VT.getVectorElementType();
10083   bool hasMinMax =
10084        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10085     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10086
10087   if (hasMinMax) {
10088     switch (SetCCOpcode) {
10089     default: break;
10090     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10091     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10092     }
10093
10094     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10095   }
10096
10097   if (Swap)
10098     std::swap(Op0, Op1);
10099
10100   // Check that the operation in question is available (most are plain SSE2,
10101   // but PCMPGTQ and PCMPEQQ have different requirements).
10102   if (VT == MVT::v2i64) {
10103     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10104       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10105
10106       // First cast everything to the right type.
10107       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10108       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10109
10110       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10111       // bits of the inputs before performing those operations. The lower
10112       // compare is always unsigned.
10113       SDValue SB;
10114       if (FlipSigns) {
10115         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10116       } else {
10117         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10118         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10119         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10120                          Sign, Zero, Sign, Zero);
10121       }
10122       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10123       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10124
10125       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10126       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10127       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10128
10129       // Create masks for only the low parts/high parts of the 64 bit integers.
10130       static const int MaskHi[] = { 1, 1, 3, 3 };
10131       static const int MaskLo[] = { 0, 0, 2, 2 };
10132       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10133       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10134       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10135
10136       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10137       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10138
10139       if (Invert)
10140         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10141
10142       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10143     }
10144
10145     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10146       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10147       // pcmpeqd + pshufd + pand.
10148       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10149
10150       // First cast everything to the right type.
10151       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10152       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10153
10154       // Do the compare.
10155       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10156
10157       // Make sure the lower and upper halves are both all-ones.
10158       static const int Mask[] = { 1, 0, 3, 2 };
10159       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10160       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10161
10162       if (Invert)
10163         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10164
10165       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10166     }
10167   }
10168
10169   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10170   // bits of the inputs before performing those operations.
10171   if (FlipSigns) {
10172     EVT EltVT = VT.getVectorElementType();
10173     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10174     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10175     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10176   }
10177
10178   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10179
10180   // If the logical-not of the result is required, perform that now.
10181   if (Invert)
10182     Result = DAG.getNOT(dl, Result, VT);
10183
10184   if (MinMax)
10185     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10186
10187   return Result;
10188 }
10189
10190 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10191
10192   MVT VT = Op.getSimpleValueType();
10193
10194   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10195
10196   assert((VT == MVT::i8 || (Subtarget->hasAVX512() && VT == MVT::i1))
10197          && "SetCC type must be 8-bit or 1-bit integer");
10198   SDValue Op0 = Op.getOperand(0);
10199   SDValue Op1 = Op.getOperand(1);
10200   SDLoc dl(Op);
10201   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10202
10203   // Optimize to BT if possible.
10204   // Lower (X & (1 << N)) == 0 to BT(X, N).
10205   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10206   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10207   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10208       Op1.getOpcode() == ISD::Constant &&
10209       cast<ConstantSDNode>(Op1)->isNullValue() &&
10210       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10211     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10212     if (NewSetCC.getNode())
10213       return NewSetCC;
10214   }
10215
10216   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10217   // these.
10218   if (Op1.getOpcode() == ISD::Constant &&
10219       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10220        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10221       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10222
10223     // If the input is a setcc, then reuse the input setcc or use a new one with
10224     // the inverted condition.
10225     if (Op0.getOpcode() == X86ISD::SETCC) {
10226       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10227       bool Invert = (CC == ISD::SETNE) ^
10228         cast<ConstantSDNode>(Op1)->isNullValue();
10229       if (!Invert) return Op0;
10230
10231       CCode = X86::GetOppositeBranchCondition(CCode);
10232       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10233                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
10234     }
10235   }
10236
10237   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10238   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10239   if (X86CC == X86::COND_INVALID)
10240     return SDValue();
10241
10242   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10243   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10244   MVT SetCCVT = Subtarget->hasAVX512() ? MVT::i1 : MVT::i8;
10245   return DAG.getNode(X86ISD::SETCC, dl, SetCCVT,
10246                       DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10247 }
10248
10249 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10250 static bool isX86LogicalCmp(SDValue Op) {
10251   unsigned Opc = Op.getNode()->getOpcode();
10252   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10253       Opc == X86ISD::SAHF)
10254     return true;
10255   if (Op.getResNo() == 1 &&
10256       (Opc == X86ISD::ADD ||
10257        Opc == X86ISD::SUB ||
10258        Opc == X86ISD::ADC ||
10259        Opc == X86ISD::SBB ||
10260        Opc == X86ISD::SMUL ||
10261        Opc == X86ISD::UMUL ||
10262        Opc == X86ISD::INC ||
10263        Opc == X86ISD::DEC ||
10264        Opc == X86ISD::OR ||
10265        Opc == X86ISD::XOR ||
10266        Opc == X86ISD::AND))
10267     return true;
10268
10269   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10270     return true;
10271
10272   return false;
10273 }
10274
10275 static bool isZero(SDValue V) {
10276   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10277   return C && C->isNullValue();
10278 }
10279
10280 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10281   if (V.getOpcode() != ISD::TRUNCATE)
10282     return false;
10283
10284   SDValue VOp0 = V.getOperand(0);
10285   unsigned InBits = VOp0.getValueSizeInBits();
10286   unsigned Bits = V.getValueSizeInBits();
10287   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10288 }
10289
10290 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10291   bool addTest = true;
10292   SDValue Cond  = Op.getOperand(0);
10293   SDValue Op1 = Op.getOperand(1);
10294   SDValue Op2 = Op.getOperand(2);
10295   SDLoc DL(Op);
10296   EVT VT = Op1.getValueType();
10297   SDValue CC;
10298
10299   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10300   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10301   // sequence later on.
10302   if (Cond.getOpcode() == ISD::SETCC &&
10303       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10304        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10305       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10306     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10307     int SSECC = translateX86FSETCC(
10308         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10309
10310     if (SSECC != 8) {
10311       if (Subtarget->hasAVX512()) {
10312         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10313                                   DAG.getConstant(SSECC, MVT::i8));
10314         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10315       }
10316       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10317                                 DAG.getConstant(SSECC, MVT::i8));
10318       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10319       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10320       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10321     }
10322   }
10323
10324   if (Cond.getOpcode() == ISD::SETCC) {
10325     SDValue NewCond = LowerSETCC(Cond, DAG);
10326     if (NewCond.getNode())
10327       Cond = NewCond;
10328   }
10329
10330   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10331   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10332   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10333   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10334   if (Cond.getOpcode() == X86ISD::SETCC &&
10335       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10336       isZero(Cond.getOperand(1).getOperand(1))) {
10337     SDValue Cmp = Cond.getOperand(1);
10338
10339     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10340
10341     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10342         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10343       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10344
10345       SDValue CmpOp0 = Cmp.getOperand(0);
10346       // Apply further optimizations for special cases
10347       // (select (x != 0), -1, 0) -> neg & sbb
10348       // (select (x == 0), 0, -1) -> neg & sbb
10349       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10350         if (YC->isNullValue() &&
10351             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10352           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10353           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10354                                     DAG.getConstant(0, CmpOp0.getValueType()),
10355                                     CmpOp0);
10356           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10357                                     DAG.getConstant(X86::COND_B, MVT::i8),
10358                                     SDValue(Neg.getNode(), 1));
10359           return Res;
10360         }
10361
10362       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10363                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10364       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10365
10366       SDValue Res =   // Res = 0 or -1.
10367         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10368                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10369
10370       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10371         Res = DAG.getNOT(DL, Res, Res.getValueType());
10372
10373       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10374       if (N2C == 0 || !N2C->isNullValue())
10375         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10376       return Res;
10377     }
10378   }
10379
10380   // Look past (and (setcc_carry (cmp ...)), 1).
10381   if (Cond.getOpcode() == ISD::AND &&
10382       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10383     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10384     if (C && C->getAPIntValue() == 1)
10385       Cond = Cond.getOperand(0);
10386   }
10387
10388   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10389   // setting operand in place of the X86ISD::SETCC.
10390   unsigned CondOpcode = Cond.getOpcode();
10391   if (CondOpcode == X86ISD::SETCC ||
10392       CondOpcode == X86ISD::SETCC_CARRY) {
10393     CC = Cond.getOperand(0);
10394
10395     SDValue Cmp = Cond.getOperand(1);
10396     unsigned Opc = Cmp.getOpcode();
10397     MVT VT = Op.getSimpleValueType();
10398
10399     bool IllegalFPCMov = false;
10400     if (VT.isFloatingPoint() && !VT.isVector() &&
10401         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10402       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10403
10404     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10405         Opc == X86ISD::BT) { // FIXME
10406       Cond = Cmp;
10407       addTest = false;
10408     }
10409   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10410              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10411              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10412               Cond.getOperand(0).getValueType() != MVT::i8)) {
10413     SDValue LHS = Cond.getOperand(0);
10414     SDValue RHS = Cond.getOperand(1);
10415     unsigned X86Opcode;
10416     unsigned X86Cond;
10417     SDVTList VTs;
10418     switch (CondOpcode) {
10419     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10420     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10421     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10422     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10423     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10424     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10425     default: llvm_unreachable("unexpected overflowing operator");
10426     }
10427     if (CondOpcode == ISD::UMULO)
10428       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10429                           MVT::i32);
10430     else
10431       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10432
10433     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10434
10435     if (CondOpcode == ISD::UMULO)
10436       Cond = X86Op.getValue(2);
10437     else
10438       Cond = X86Op.getValue(1);
10439
10440     CC = DAG.getConstant(X86Cond, MVT::i8);
10441     addTest = false;
10442   }
10443
10444   if (addTest) {
10445     // Look pass the truncate if the high bits are known zero.
10446     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10447         Cond = Cond.getOperand(0);
10448
10449     // We know the result of AND is compared against zero. Try to match
10450     // it to BT.
10451     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10452       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10453       if (NewSetCC.getNode()) {
10454         CC = NewSetCC.getOperand(0);
10455         Cond = NewSetCC.getOperand(1);
10456         addTest = false;
10457       }
10458     }
10459   }
10460
10461   if (addTest) {
10462     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10463     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10464   }
10465
10466   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10467   // a <  b ?  0 : -1 -> RES = setcc_carry
10468   // a >= b ? -1 :  0 -> RES = setcc_carry
10469   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10470   if (Cond.getOpcode() == X86ISD::SUB) {
10471     Cond = ConvertCmpIfNecessary(Cond, DAG);
10472     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10473
10474     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10475         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10476       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10477                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10478       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10479         return DAG.getNOT(DL, Res, Res.getValueType());
10480       return Res;
10481     }
10482   }
10483
10484   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10485   // widen the cmov and push the truncate through. This avoids introducing a new
10486   // branch during isel and doesn't add any extensions.
10487   if (Op.getValueType() == MVT::i8 &&
10488       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10489     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10490     if (T1.getValueType() == T2.getValueType() &&
10491         // Blacklist CopyFromReg to avoid partial register stalls.
10492         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10493       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10494       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10495       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10496     }
10497   }
10498
10499   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10500   // condition is true.
10501   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10502   SDValue Ops[] = { Op2, Op1, CC, Cond };
10503   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10504 }
10505
10506 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10507   MVT VT = Op->getSimpleValueType(0);
10508   SDValue In = Op->getOperand(0);
10509   MVT InVT = In.getSimpleValueType();
10510   SDLoc dl(Op);
10511
10512   unsigned int NumElts = VT.getVectorNumElements();
10513   if (NumElts != 8 && NumElts != 16)
10514     return SDValue();
10515
10516   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10517     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10518
10519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10520   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10521
10522   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10523   Constant *C = ConstantInt::get(*DAG.getContext(),
10524     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10525
10526   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10527   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10528   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10529                           MachinePointerInfo::getConstantPool(),
10530                           false, false, false, Alignment);
10531   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10532   if (VT.is512BitVector())
10533     return Brcst;
10534   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10535 }
10536
10537 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10538                                 SelectionDAG &DAG) {
10539   MVT VT = Op->getSimpleValueType(0);
10540   SDValue In = Op->getOperand(0);
10541   MVT InVT = In.getSimpleValueType();
10542   SDLoc dl(Op);
10543
10544   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10545     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10546
10547   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10548       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10549       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10550     return SDValue();
10551
10552   if (Subtarget->hasInt256())
10553     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10554
10555   // Optimize vectors in AVX mode
10556   // Sign extend  v8i16 to v8i32 and
10557   //              v4i32 to v4i64
10558   //
10559   // Divide input vector into two parts
10560   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10561   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10562   // concat the vectors to original VT
10563
10564   unsigned NumElems = InVT.getVectorNumElements();
10565   SDValue Undef = DAG.getUNDEF(InVT);
10566
10567   SmallVector<int,8> ShufMask1(NumElems, -1);
10568   for (unsigned i = 0; i != NumElems/2; ++i)
10569     ShufMask1[i] = i;
10570
10571   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10572
10573   SmallVector<int,8> ShufMask2(NumElems, -1);
10574   for (unsigned i = 0; i != NumElems/2; ++i)
10575     ShufMask2[i] = i + NumElems/2;
10576
10577   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10578
10579   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10580                                 VT.getVectorNumElements()/2);
10581
10582   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10583   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10584
10585   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10586 }
10587
10588 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10589 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10590 // from the AND / OR.
10591 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10592   Opc = Op.getOpcode();
10593   if (Opc != ISD::OR && Opc != ISD::AND)
10594     return false;
10595   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10596           Op.getOperand(0).hasOneUse() &&
10597           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10598           Op.getOperand(1).hasOneUse());
10599 }
10600
10601 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10602 // 1 and that the SETCC node has a single use.
10603 static bool isXor1OfSetCC(SDValue Op) {
10604   if (Op.getOpcode() != ISD::XOR)
10605     return false;
10606   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10607   if (N1C && N1C->getAPIntValue() == 1) {
10608     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10609       Op.getOperand(0).hasOneUse();
10610   }
10611   return false;
10612 }
10613
10614 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10615   bool addTest = true;
10616   SDValue Chain = Op.getOperand(0);
10617   SDValue Cond  = Op.getOperand(1);
10618   SDValue Dest  = Op.getOperand(2);
10619   SDLoc dl(Op);
10620   SDValue CC;
10621   bool Inverted = false;
10622
10623   if (Cond.getOpcode() == ISD::SETCC) {
10624     // Check for setcc([su]{add,sub,mul}o == 0).
10625     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10626         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10627         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10628         Cond.getOperand(0).getResNo() == 1 &&
10629         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10630          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10631          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10632          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10633          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10634          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10635       Inverted = true;
10636       Cond = Cond.getOperand(0);
10637     } else {
10638       SDValue NewCond = LowerSETCC(Cond, DAG);
10639       if (NewCond.getNode())
10640         Cond = NewCond;
10641     }
10642   }
10643 #if 0
10644   // FIXME: LowerXALUO doesn't handle these!!
10645   else if (Cond.getOpcode() == X86ISD::ADD  ||
10646            Cond.getOpcode() == X86ISD::SUB  ||
10647            Cond.getOpcode() == X86ISD::SMUL ||
10648            Cond.getOpcode() == X86ISD::UMUL)
10649     Cond = LowerXALUO(Cond, DAG);
10650 #endif
10651
10652   // Look pass (and (setcc_carry (cmp ...)), 1).
10653   if (Cond.getOpcode() == ISD::AND &&
10654       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10655     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10656     if (C && C->getAPIntValue() == 1)
10657       Cond = Cond.getOperand(0);
10658   }
10659
10660   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10661   // setting operand in place of the X86ISD::SETCC.
10662   unsigned CondOpcode = Cond.getOpcode();
10663   if (CondOpcode == X86ISD::SETCC ||
10664       CondOpcode == X86ISD::SETCC_CARRY) {
10665     CC = Cond.getOperand(0);
10666
10667     SDValue Cmp = Cond.getOperand(1);
10668     unsigned Opc = Cmp.getOpcode();
10669     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10670     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10671       Cond = Cmp;
10672       addTest = false;
10673     } else {
10674       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10675       default: break;
10676       case X86::COND_O:
10677       case X86::COND_B:
10678         // These can only come from an arithmetic instruction with overflow,
10679         // e.g. SADDO, UADDO.
10680         Cond = Cond.getNode()->getOperand(1);
10681         addTest = false;
10682         break;
10683       }
10684     }
10685   }
10686   CondOpcode = Cond.getOpcode();
10687   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10688       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10689       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10690        Cond.getOperand(0).getValueType() != MVT::i8)) {
10691     SDValue LHS = Cond.getOperand(0);
10692     SDValue RHS = Cond.getOperand(1);
10693     unsigned X86Opcode;
10694     unsigned X86Cond;
10695     SDVTList VTs;
10696     switch (CondOpcode) {
10697     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10698     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10699     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10700     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10701     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10702     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10703     default: llvm_unreachable("unexpected overflowing operator");
10704     }
10705     if (Inverted)
10706       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10707     if (CondOpcode == ISD::UMULO)
10708       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10709                           MVT::i32);
10710     else
10711       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10712
10713     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10714
10715     if (CondOpcode == ISD::UMULO)
10716       Cond = X86Op.getValue(2);
10717     else
10718       Cond = X86Op.getValue(1);
10719
10720     CC = DAG.getConstant(X86Cond, MVT::i8);
10721     addTest = false;
10722   } else {
10723     unsigned CondOpc;
10724     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10725       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10726       if (CondOpc == ISD::OR) {
10727         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10728         // two branches instead of an explicit OR instruction with a
10729         // separate test.
10730         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10731             isX86LogicalCmp(Cmp)) {
10732           CC = Cond.getOperand(0).getOperand(0);
10733           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10734                               Chain, Dest, CC, Cmp);
10735           CC = Cond.getOperand(1).getOperand(0);
10736           Cond = Cmp;
10737           addTest = false;
10738         }
10739       } else { // ISD::AND
10740         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10741         // two branches instead of an explicit AND instruction with a
10742         // separate test. However, we only do this if this block doesn't
10743         // have a fall-through edge, because this requires an explicit
10744         // jmp when the condition is false.
10745         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10746             isX86LogicalCmp(Cmp) &&
10747             Op.getNode()->hasOneUse()) {
10748           X86::CondCode CCode =
10749             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10750           CCode = X86::GetOppositeBranchCondition(CCode);
10751           CC = DAG.getConstant(CCode, MVT::i8);
10752           SDNode *User = *Op.getNode()->use_begin();
10753           // Look for an unconditional branch following this conditional branch.
10754           // We need this because we need to reverse the successors in order
10755           // to implement FCMP_OEQ.
10756           if (User->getOpcode() == ISD::BR) {
10757             SDValue FalseBB = User->getOperand(1);
10758             SDNode *NewBR =
10759               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10760             assert(NewBR == User);
10761             (void)NewBR;
10762             Dest = FalseBB;
10763
10764             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10765                                 Chain, Dest, CC, Cmp);
10766             X86::CondCode CCode =
10767               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10768             CCode = X86::GetOppositeBranchCondition(CCode);
10769             CC = DAG.getConstant(CCode, MVT::i8);
10770             Cond = Cmp;
10771             addTest = false;
10772           }
10773         }
10774       }
10775     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10776       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10777       // It should be transformed during dag combiner except when the condition
10778       // is set by a arithmetics with overflow node.
10779       X86::CondCode CCode =
10780         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10781       CCode = X86::GetOppositeBranchCondition(CCode);
10782       CC = DAG.getConstant(CCode, MVT::i8);
10783       Cond = Cond.getOperand(0).getOperand(1);
10784       addTest = false;
10785     } else if (Cond.getOpcode() == ISD::SETCC &&
10786                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10787       // For FCMP_OEQ, we can emit
10788       // two branches instead of an explicit AND instruction with a
10789       // separate test. However, we only do this if this block doesn't
10790       // have a fall-through edge, because this requires an explicit
10791       // jmp when the condition is false.
10792       if (Op.getNode()->hasOneUse()) {
10793         SDNode *User = *Op.getNode()->use_begin();
10794         // Look for an unconditional branch following this conditional branch.
10795         // We need this because we need to reverse the successors in order
10796         // to implement FCMP_OEQ.
10797         if (User->getOpcode() == ISD::BR) {
10798           SDValue FalseBB = User->getOperand(1);
10799           SDNode *NewBR =
10800             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10801           assert(NewBR == User);
10802           (void)NewBR;
10803           Dest = FalseBB;
10804
10805           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10806                                     Cond.getOperand(0), Cond.getOperand(1));
10807           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10808           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10809           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10810                               Chain, Dest, CC, Cmp);
10811           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10812           Cond = Cmp;
10813           addTest = false;
10814         }
10815       }
10816     } else if (Cond.getOpcode() == ISD::SETCC &&
10817                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10818       // For FCMP_UNE, we can emit
10819       // two branches instead of an explicit AND instruction with a
10820       // separate test. However, we only do this if this block doesn't
10821       // have a fall-through edge, because this requires an explicit
10822       // jmp when the condition is false.
10823       if (Op.getNode()->hasOneUse()) {
10824         SDNode *User = *Op.getNode()->use_begin();
10825         // Look for an unconditional branch following this conditional branch.
10826         // We need this because we need to reverse the successors in order
10827         // to implement FCMP_UNE.
10828         if (User->getOpcode() == ISD::BR) {
10829           SDValue FalseBB = User->getOperand(1);
10830           SDNode *NewBR =
10831             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10832           assert(NewBR == User);
10833           (void)NewBR;
10834
10835           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10836                                     Cond.getOperand(0), Cond.getOperand(1));
10837           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10838           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10839           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10840                               Chain, Dest, CC, Cmp);
10841           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10842           Cond = Cmp;
10843           addTest = false;
10844           Dest = FalseBB;
10845         }
10846       }
10847     }
10848   }
10849
10850   if (addTest) {
10851     // Look pass the truncate if the high bits are known zero.
10852     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10853         Cond = Cond.getOperand(0);
10854
10855     // We know the result of AND is compared against zero. Try to match
10856     // it to BT.
10857     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10858       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10859       if (NewSetCC.getNode()) {
10860         CC = NewSetCC.getOperand(0);
10861         Cond = NewSetCC.getOperand(1);
10862         addTest = false;
10863       }
10864     }
10865   }
10866
10867   if (addTest) {
10868     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10869     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10870   }
10871   Cond = ConvertCmpIfNecessary(Cond, DAG);
10872   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10873                      Chain, Dest, CC, Cond);
10874 }
10875
10876 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10877 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10878 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10879 // that the guard pages used by the OS virtual memory manager are allocated in
10880 // correct sequence.
10881 SDValue
10882 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10883                                            SelectionDAG &DAG) const {
10884   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10885           getTargetMachine().Options.EnableSegmentedStacks) &&
10886          "This should be used only on Windows targets or when segmented stacks "
10887          "are being used");
10888   assert(!Subtarget->isTargetMacho() && "Not implemented");
10889   SDLoc dl(Op);
10890
10891   // Get the inputs.
10892   SDValue Chain = Op.getOperand(0);
10893   SDValue Size  = Op.getOperand(1);
10894   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10895   EVT VT = Op.getNode()->getValueType(0);
10896
10897   bool Is64Bit = Subtarget->is64Bit();
10898   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10899
10900   if (getTargetMachine().Options.EnableSegmentedStacks) {
10901     MachineFunction &MF = DAG.getMachineFunction();
10902     MachineRegisterInfo &MRI = MF.getRegInfo();
10903
10904     if (Is64Bit) {
10905       // The 64 bit implementation of segmented stacks needs to clobber both r10
10906       // r11. This makes it impossible to use it along with nested parameters.
10907       const Function *F = MF.getFunction();
10908
10909       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10910            I != E; ++I)
10911         if (I->hasNestAttr())
10912           report_fatal_error("Cannot use segmented stacks with functions that "
10913                              "have nested arguments.");
10914     }
10915
10916     const TargetRegisterClass *AddrRegClass =
10917       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10918     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10919     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10920     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10921                                 DAG.getRegister(Vreg, SPTy));
10922     SDValue Ops1[2] = { Value, Chain };
10923     return DAG.getMergeValues(Ops1, 2, dl);
10924   } else {
10925     SDValue Flag;
10926     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10927
10928     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10929     Flag = Chain.getValue(1);
10930     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10931
10932     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10933
10934     const X86RegisterInfo *RegInfo =
10935       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10936     unsigned SPReg = RegInfo->getStackRegister();
10937     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
10938     Chain = SP.getValue(1);
10939
10940     if (Align) {
10941       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10942                        DAG.getConstant(-(uint64_t)Align, VT));
10943       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
10944     }
10945
10946     SDValue Ops1[2] = { SP, Chain };
10947     return DAG.getMergeValues(Ops1, 2, dl);
10948   }
10949 }
10950
10951 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10952   MachineFunction &MF = DAG.getMachineFunction();
10953   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10954
10955   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10956   SDLoc DL(Op);
10957
10958   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10959     // vastart just stores the address of the VarArgsFrameIndex slot into the
10960     // memory location argument.
10961     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10962                                    getPointerTy());
10963     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10964                         MachinePointerInfo(SV), false, false, 0);
10965   }
10966
10967   // __va_list_tag:
10968   //   gp_offset         (0 - 6 * 8)
10969   //   fp_offset         (48 - 48 + 8 * 16)
10970   //   overflow_arg_area (point to parameters coming in memory).
10971   //   reg_save_area
10972   SmallVector<SDValue, 8> MemOps;
10973   SDValue FIN = Op.getOperand(1);
10974   // Store gp_offset
10975   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10976                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10977                                                MVT::i32),
10978                                FIN, MachinePointerInfo(SV), false, false, 0);
10979   MemOps.push_back(Store);
10980
10981   // Store fp_offset
10982   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10983                     FIN, DAG.getIntPtrConstant(4));
10984   Store = DAG.getStore(Op.getOperand(0), DL,
10985                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10986                                        MVT::i32),
10987                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10988   MemOps.push_back(Store);
10989
10990   // Store ptr to overflow_arg_area
10991   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10992                     FIN, DAG.getIntPtrConstant(4));
10993   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10994                                     getPointerTy());
10995   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10996                        MachinePointerInfo(SV, 8),
10997                        false, false, 0);
10998   MemOps.push_back(Store);
10999
11000   // Store ptr to reg_save_area.
11001   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11002                     FIN, DAG.getIntPtrConstant(8));
11003   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11004                                     getPointerTy());
11005   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11006                        MachinePointerInfo(SV, 16), false, false, 0);
11007   MemOps.push_back(Store);
11008   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11009                      &MemOps[0], MemOps.size());
11010 }
11011
11012 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11013   assert(Subtarget->is64Bit() &&
11014          "LowerVAARG only handles 64-bit va_arg!");
11015   assert((Subtarget->isTargetLinux() ||
11016           Subtarget->isTargetDarwin()) &&
11017           "Unhandled target in LowerVAARG");
11018   assert(Op.getNode()->getNumOperands() == 4);
11019   SDValue Chain = Op.getOperand(0);
11020   SDValue SrcPtr = Op.getOperand(1);
11021   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11022   unsigned Align = Op.getConstantOperandVal(3);
11023   SDLoc dl(Op);
11024
11025   EVT ArgVT = Op.getNode()->getValueType(0);
11026   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11027   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11028   uint8_t ArgMode;
11029
11030   // Decide which area this value should be read from.
11031   // TODO: Implement the AMD64 ABI in its entirety. This simple
11032   // selection mechanism works only for the basic types.
11033   if (ArgVT == MVT::f80) {
11034     llvm_unreachable("va_arg for f80 not yet implemented");
11035   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11036     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11037   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11038     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11039   } else {
11040     llvm_unreachable("Unhandled argument type in LowerVAARG");
11041   }
11042
11043   if (ArgMode == 2) {
11044     // Sanity Check: Make sure using fp_offset makes sense.
11045     assert(!getTargetMachine().Options.UseSoftFloat &&
11046            !(DAG.getMachineFunction()
11047                 .getFunction()->getAttributes()
11048                 .hasAttribute(AttributeSet::FunctionIndex,
11049                               Attribute::NoImplicitFloat)) &&
11050            Subtarget->hasSSE1());
11051   }
11052
11053   // Insert VAARG_64 node into the DAG
11054   // VAARG_64 returns two values: Variable Argument Address, Chain
11055   SmallVector<SDValue, 11> InstOps;
11056   InstOps.push_back(Chain);
11057   InstOps.push_back(SrcPtr);
11058   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11059   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11060   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11061   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11062   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11063                                           VTs, &InstOps[0], InstOps.size(),
11064                                           MVT::i64,
11065                                           MachinePointerInfo(SV),
11066                                           /*Align=*/0,
11067                                           /*Volatile=*/false,
11068                                           /*ReadMem=*/true,
11069                                           /*WriteMem=*/true);
11070   Chain = VAARG.getValue(1);
11071
11072   // Load the next argument and return it
11073   return DAG.getLoad(ArgVT, dl,
11074                      Chain,
11075                      VAARG,
11076                      MachinePointerInfo(),
11077                      false, false, false, 0);
11078 }
11079
11080 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11081                            SelectionDAG &DAG) {
11082   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11083   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11084   SDValue Chain = Op.getOperand(0);
11085   SDValue DstPtr = Op.getOperand(1);
11086   SDValue SrcPtr = Op.getOperand(2);
11087   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11088   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11089   SDLoc DL(Op);
11090
11091   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11092                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11093                        false,
11094                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11095 }
11096
11097 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11098 // amount is a constant. Takes immediate version of shift as input.
11099 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, EVT VT,
11100                                           SDValue SrcOp, uint64_t ShiftAmt,
11101                                           SelectionDAG &DAG) {
11102
11103   // Check for ShiftAmt >= element width
11104   if (ShiftAmt >= VT.getVectorElementType().getSizeInBits()) {
11105     if (Opc == X86ISD::VSRAI)
11106       ShiftAmt = VT.getVectorElementType().getSizeInBits() - 1;
11107     else
11108       return DAG.getConstant(0, VT);
11109   }
11110
11111   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11112          && "Unknown target vector shift-by-constant node");
11113
11114   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11115 }
11116
11117 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11118 // may or may not be a constant. Takes immediate version of shift as input.
11119 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
11120                                    SDValue SrcOp, SDValue ShAmt,
11121                                    SelectionDAG &DAG) {
11122   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11123
11124   // Catch shift-by-constant.
11125   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11126     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11127                                       CShAmt->getZExtValue(), DAG);
11128
11129   // Change opcode to non-immediate version
11130   switch (Opc) {
11131     default: llvm_unreachable("Unknown target vector shift node");
11132     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11133     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11134     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11135   }
11136
11137   // Need to build a vector containing shift amount
11138   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11139   SDValue ShOps[4];
11140   ShOps[0] = ShAmt;
11141   ShOps[1] = DAG.getConstant(0, MVT::i32);
11142   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11143   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11144
11145   // The return type has to be a 128-bit type with the same element
11146   // type as the input type.
11147   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11148   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11149
11150   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11151   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11152 }
11153
11154 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11155   SDLoc dl(Op);
11156   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11157   switch (IntNo) {
11158   default: return SDValue();    // Don't custom lower most intrinsics.
11159   // Comparison intrinsics.
11160   case Intrinsic::x86_sse_comieq_ss:
11161   case Intrinsic::x86_sse_comilt_ss:
11162   case Intrinsic::x86_sse_comile_ss:
11163   case Intrinsic::x86_sse_comigt_ss:
11164   case Intrinsic::x86_sse_comige_ss:
11165   case Intrinsic::x86_sse_comineq_ss:
11166   case Intrinsic::x86_sse_ucomieq_ss:
11167   case Intrinsic::x86_sse_ucomilt_ss:
11168   case Intrinsic::x86_sse_ucomile_ss:
11169   case Intrinsic::x86_sse_ucomigt_ss:
11170   case Intrinsic::x86_sse_ucomige_ss:
11171   case Intrinsic::x86_sse_ucomineq_ss:
11172   case Intrinsic::x86_sse2_comieq_sd:
11173   case Intrinsic::x86_sse2_comilt_sd:
11174   case Intrinsic::x86_sse2_comile_sd:
11175   case Intrinsic::x86_sse2_comigt_sd:
11176   case Intrinsic::x86_sse2_comige_sd:
11177   case Intrinsic::x86_sse2_comineq_sd:
11178   case Intrinsic::x86_sse2_ucomieq_sd:
11179   case Intrinsic::x86_sse2_ucomilt_sd:
11180   case Intrinsic::x86_sse2_ucomile_sd:
11181   case Intrinsic::x86_sse2_ucomigt_sd:
11182   case Intrinsic::x86_sse2_ucomige_sd:
11183   case Intrinsic::x86_sse2_ucomineq_sd: {
11184     unsigned Opc;
11185     ISD::CondCode CC;
11186     switch (IntNo) {
11187     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11188     case Intrinsic::x86_sse_comieq_ss:
11189     case Intrinsic::x86_sse2_comieq_sd:
11190       Opc = X86ISD::COMI;
11191       CC = ISD::SETEQ;
11192       break;
11193     case Intrinsic::x86_sse_comilt_ss:
11194     case Intrinsic::x86_sse2_comilt_sd:
11195       Opc = X86ISD::COMI;
11196       CC = ISD::SETLT;
11197       break;
11198     case Intrinsic::x86_sse_comile_ss:
11199     case Intrinsic::x86_sse2_comile_sd:
11200       Opc = X86ISD::COMI;
11201       CC = ISD::SETLE;
11202       break;
11203     case Intrinsic::x86_sse_comigt_ss:
11204     case Intrinsic::x86_sse2_comigt_sd:
11205       Opc = X86ISD::COMI;
11206       CC = ISD::SETGT;
11207       break;
11208     case Intrinsic::x86_sse_comige_ss:
11209     case Intrinsic::x86_sse2_comige_sd:
11210       Opc = X86ISD::COMI;
11211       CC = ISD::SETGE;
11212       break;
11213     case Intrinsic::x86_sse_comineq_ss:
11214     case Intrinsic::x86_sse2_comineq_sd:
11215       Opc = X86ISD::COMI;
11216       CC = ISD::SETNE;
11217       break;
11218     case Intrinsic::x86_sse_ucomieq_ss:
11219     case Intrinsic::x86_sse2_ucomieq_sd:
11220       Opc = X86ISD::UCOMI;
11221       CC = ISD::SETEQ;
11222       break;
11223     case Intrinsic::x86_sse_ucomilt_ss:
11224     case Intrinsic::x86_sse2_ucomilt_sd:
11225       Opc = X86ISD::UCOMI;
11226       CC = ISD::SETLT;
11227       break;
11228     case Intrinsic::x86_sse_ucomile_ss:
11229     case Intrinsic::x86_sse2_ucomile_sd:
11230       Opc = X86ISD::UCOMI;
11231       CC = ISD::SETLE;
11232       break;
11233     case Intrinsic::x86_sse_ucomigt_ss:
11234     case Intrinsic::x86_sse2_ucomigt_sd:
11235       Opc = X86ISD::UCOMI;
11236       CC = ISD::SETGT;
11237       break;
11238     case Intrinsic::x86_sse_ucomige_ss:
11239     case Intrinsic::x86_sse2_ucomige_sd:
11240       Opc = X86ISD::UCOMI;
11241       CC = ISD::SETGE;
11242       break;
11243     case Intrinsic::x86_sse_ucomineq_ss:
11244     case Intrinsic::x86_sse2_ucomineq_sd:
11245       Opc = X86ISD::UCOMI;
11246       CC = ISD::SETNE;
11247       break;
11248     }
11249
11250     SDValue LHS = Op.getOperand(1);
11251     SDValue RHS = Op.getOperand(2);
11252     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11253     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11254     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11255     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11256                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11257     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11258   }
11259
11260   // Arithmetic intrinsics.
11261   case Intrinsic::x86_sse2_pmulu_dq:
11262   case Intrinsic::x86_avx2_pmulu_dq:
11263     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11264                        Op.getOperand(1), Op.getOperand(2));
11265
11266   // SSE2/AVX2 sub with unsigned saturation intrinsics
11267   case Intrinsic::x86_sse2_psubus_b:
11268   case Intrinsic::x86_sse2_psubus_w:
11269   case Intrinsic::x86_avx2_psubus_b:
11270   case Intrinsic::x86_avx2_psubus_w:
11271     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11272                        Op.getOperand(1), Op.getOperand(2));
11273
11274   // SSE3/AVX horizontal add/sub intrinsics
11275   case Intrinsic::x86_sse3_hadd_ps:
11276   case Intrinsic::x86_sse3_hadd_pd:
11277   case Intrinsic::x86_avx_hadd_ps_256:
11278   case Intrinsic::x86_avx_hadd_pd_256:
11279   case Intrinsic::x86_sse3_hsub_ps:
11280   case Intrinsic::x86_sse3_hsub_pd:
11281   case Intrinsic::x86_avx_hsub_ps_256:
11282   case Intrinsic::x86_avx_hsub_pd_256:
11283   case Intrinsic::x86_ssse3_phadd_w_128:
11284   case Intrinsic::x86_ssse3_phadd_d_128:
11285   case Intrinsic::x86_avx2_phadd_w:
11286   case Intrinsic::x86_avx2_phadd_d:
11287   case Intrinsic::x86_ssse3_phsub_w_128:
11288   case Intrinsic::x86_ssse3_phsub_d_128:
11289   case Intrinsic::x86_avx2_phsub_w:
11290   case Intrinsic::x86_avx2_phsub_d: {
11291     unsigned Opcode;
11292     switch (IntNo) {
11293     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11294     case Intrinsic::x86_sse3_hadd_ps:
11295     case Intrinsic::x86_sse3_hadd_pd:
11296     case Intrinsic::x86_avx_hadd_ps_256:
11297     case Intrinsic::x86_avx_hadd_pd_256:
11298       Opcode = X86ISD::FHADD;
11299       break;
11300     case Intrinsic::x86_sse3_hsub_ps:
11301     case Intrinsic::x86_sse3_hsub_pd:
11302     case Intrinsic::x86_avx_hsub_ps_256:
11303     case Intrinsic::x86_avx_hsub_pd_256:
11304       Opcode = X86ISD::FHSUB;
11305       break;
11306     case Intrinsic::x86_ssse3_phadd_w_128:
11307     case Intrinsic::x86_ssse3_phadd_d_128:
11308     case Intrinsic::x86_avx2_phadd_w:
11309     case Intrinsic::x86_avx2_phadd_d:
11310       Opcode = X86ISD::HADD;
11311       break;
11312     case Intrinsic::x86_ssse3_phsub_w_128:
11313     case Intrinsic::x86_ssse3_phsub_d_128:
11314     case Intrinsic::x86_avx2_phsub_w:
11315     case Intrinsic::x86_avx2_phsub_d:
11316       Opcode = X86ISD::HSUB;
11317       break;
11318     }
11319     return DAG.getNode(Opcode, dl, Op.getValueType(),
11320                        Op.getOperand(1), Op.getOperand(2));
11321   }
11322
11323   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11324   case Intrinsic::x86_sse2_pmaxu_b:
11325   case Intrinsic::x86_sse41_pmaxuw:
11326   case Intrinsic::x86_sse41_pmaxud:
11327   case Intrinsic::x86_avx2_pmaxu_b:
11328   case Intrinsic::x86_avx2_pmaxu_w:
11329   case Intrinsic::x86_avx2_pmaxu_d:
11330   case Intrinsic::x86_avx512_pmaxu_d:
11331   case Intrinsic::x86_avx512_pmaxu_q:
11332   case Intrinsic::x86_sse2_pminu_b:
11333   case Intrinsic::x86_sse41_pminuw:
11334   case Intrinsic::x86_sse41_pminud:
11335   case Intrinsic::x86_avx2_pminu_b:
11336   case Intrinsic::x86_avx2_pminu_w:
11337   case Intrinsic::x86_avx2_pminu_d:
11338   case Intrinsic::x86_avx512_pminu_d:
11339   case Intrinsic::x86_avx512_pminu_q:
11340   case Intrinsic::x86_sse41_pmaxsb:
11341   case Intrinsic::x86_sse2_pmaxs_w:
11342   case Intrinsic::x86_sse41_pmaxsd:
11343   case Intrinsic::x86_avx2_pmaxs_b:
11344   case Intrinsic::x86_avx2_pmaxs_w:
11345   case Intrinsic::x86_avx2_pmaxs_d:
11346   case Intrinsic::x86_avx512_pmaxs_d:
11347   case Intrinsic::x86_avx512_pmaxs_q:
11348   case Intrinsic::x86_sse41_pminsb:
11349   case Intrinsic::x86_sse2_pmins_w:
11350   case Intrinsic::x86_sse41_pminsd:
11351   case Intrinsic::x86_avx2_pmins_b:
11352   case Intrinsic::x86_avx2_pmins_w:
11353   case Intrinsic::x86_avx2_pmins_d:
11354   case Intrinsic::x86_avx512_pmins_d:
11355   case Intrinsic::x86_avx512_pmins_q: {
11356     unsigned Opcode;
11357     switch (IntNo) {
11358     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11359     case Intrinsic::x86_sse2_pmaxu_b:
11360     case Intrinsic::x86_sse41_pmaxuw:
11361     case Intrinsic::x86_sse41_pmaxud:
11362     case Intrinsic::x86_avx2_pmaxu_b:
11363     case Intrinsic::x86_avx2_pmaxu_w:
11364     case Intrinsic::x86_avx2_pmaxu_d:
11365     case Intrinsic::x86_avx512_pmaxu_d:
11366     case Intrinsic::x86_avx512_pmaxu_q:
11367       Opcode = X86ISD::UMAX;
11368       break;
11369     case Intrinsic::x86_sse2_pminu_b:
11370     case Intrinsic::x86_sse41_pminuw:
11371     case Intrinsic::x86_sse41_pminud:
11372     case Intrinsic::x86_avx2_pminu_b:
11373     case Intrinsic::x86_avx2_pminu_w:
11374     case Intrinsic::x86_avx2_pminu_d:
11375     case Intrinsic::x86_avx512_pminu_d:
11376     case Intrinsic::x86_avx512_pminu_q:
11377       Opcode = X86ISD::UMIN;
11378       break;
11379     case Intrinsic::x86_sse41_pmaxsb:
11380     case Intrinsic::x86_sse2_pmaxs_w:
11381     case Intrinsic::x86_sse41_pmaxsd:
11382     case Intrinsic::x86_avx2_pmaxs_b:
11383     case Intrinsic::x86_avx2_pmaxs_w:
11384     case Intrinsic::x86_avx2_pmaxs_d:
11385     case Intrinsic::x86_avx512_pmaxs_d:
11386     case Intrinsic::x86_avx512_pmaxs_q:
11387       Opcode = X86ISD::SMAX;
11388       break;
11389     case Intrinsic::x86_sse41_pminsb:
11390     case Intrinsic::x86_sse2_pmins_w:
11391     case Intrinsic::x86_sse41_pminsd:
11392     case Intrinsic::x86_avx2_pmins_b:
11393     case Intrinsic::x86_avx2_pmins_w:
11394     case Intrinsic::x86_avx2_pmins_d:
11395     case Intrinsic::x86_avx512_pmins_d:
11396     case Intrinsic::x86_avx512_pmins_q:
11397       Opcode = X86ISD::SMIN;
11398       break;
11399     }
11400     return DAG.getNode(Opcode, dl, Op.getValueType(),
11401                        Op.getOperand(1), Op.getOperand(2));
11402   }
11403
11404   // SSE/SSE2/AVX floating point max/min intrinsics.
11405   case Intrinsic::x86_sse_max_ps:
11406   case Intrinsic::x86_sse2_max_pd:
11407   case Intrinsic::x86_avx_max_ps_256:
11408   case Intrinsic::x86_avx_max_pd_256:
11409   case Intrinsic::x86_avx512_max_ps_512:
11410   case Intrinsic::x86_avx512_max_pd_512:
11411   case Intrinsic::x86_sse_min_ps:
11412   case Intrinsic::x86_sse2_min_pd:
11413   case Intrinsic::x86_avx_min_ps_256:
11414   case Intrinsic::x86_avx_min_pd_256:
11415   case Intrinsic::x86_avx512_min_ps_512:
11416   case Intrinsic::x86_avx512_min_pd_512:  {
11417     unsigned Opcode;
11418     switch (IntNo) {
11419     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11420     case Intrinsic::x86_sse_max_ps:
11421     case Intrinsic::x86_sse2_max_pd:
11422     case Intrinsic::x86_avx_max_ps_256:
11423     case Intrinsic::x86_avx_max_pd_256:
11424     case Intrinsic::x86_avx512_max_ps_512:
11425     case Intrinsic::x86_avx512_max_pd_512:
11426       Opcode = X86ISD::FMAX;
11427       break;
11428     case Intrinsic::x86_sse_min_ps:
11429     case Intrinsic::x86_sse2_min_pd:
11430     case Intrinsic::x86_avx_min_ps_256:
11431     case Intrinsic::x86_avx_min_pd_256:
11432     case Intrinsic::x86_avx512_min_ps_512:
11433     case Intrinsic::x86_avx512_min_pd_512:
11434       Opcode = X86ISD::FMIN;
11435       break;
11436     }
11437     return DAG.getNode(Opcode, dl, Op.getValueType(),
11438                        Op.getOperand(1), Op.getOperand(2));
11439   }
11440
11441   // AVX2 variable shift intrinsics
11442   case Intrinsic::x86_avx2_psllv_d:
11443   case Intrinsic::x86_avx2_psllv_q:
11444   case Intrinsic::x86_avx2_psllv_d_256:
11445   case Intrinsic::x86_avx2_psllv_q_256:
11446   case Intrinsic::x86_avx2_psrlv_d:
11447   case Intrinsic::x86_avx2_psrlv_q:
11448   case Intrinsic::x86_avx2_psrlv_d_256:
11449   case Intrinsic::x86_avx2_psrlv_q_256:
11450   case Intrinsic::x86_avx2_psrav_d:
11451   case Intrinsic::x86_avx2_psrav_d_256: {
11452     unsigned Opcode;
11453     switch (IntNo) {
11454     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11455     case Intrinsic::x86_avx2_psllv_d:
11456     case Intrinsic::x86_avx2_psllv_q:
11457     case Intrinsic::x86_avx2_psllv_d_256:
11458     case Intrinsic::x86_avx2_psllv_q_256:
11459       Opcode = ISD::SHL;
11460       break;
11461     case Intrinsic::x86_avx2_psrlv_d:
11462     case Intrinsic::x86_avx2_psrlv_q:
11463     case Intrinsic::x86_avx2_psrlv_d_256:
11464     case Intrinsic::x86_avx2_psrlv_q_256:
11465       Opcode = ISD::SRL;
11466       break;
11467     case Intrinsic::x86_avx2_psrav_d:
11468     case Intrinsic::x86_avx2_psrav_d_256:
11469       Opcode = ISD::SRA;
11470       break;
11471     }
11472     return DAG.getNode(Opcode, dl, Op.getValueType(),
11473                        Op.getOperand(1), Op.getOperand(2));
11474   }
11475
11476   case Intrinsic::x86_ssse3_pshuf_b_128:
11477   case Intrinsic::x86_avx2_pshuf_b:
11478     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11479                        Op.getOperand(1), Op.getOperand(2));
11480
11481   case Intrinsic::x86_ssse3_psign_b_128:
11482   case Intrinsic::x86_ssse3_psign_w_128:
11483   case Intrinsic::x86_ssse3_psign_d_128:
11484   case Intrinsic::x86_avx2_psign_b:
11485   case Intrinsic::x86_avx2_psign_w:
11486   case Intrinsic::x86_avx2_psign_d:
11487     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11488                        Op.getOperand(1), Op.getOperand(2));
11489
11490   case Intrinsic::x86_sse41_insertps:
11491     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11492                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11493
11494   case Intrinsic::x86_avx_vperm2f128_ps_256:
11495   case Intrinsic::x86_avx_vperm2f128_pd_256:
11496   case Intrinsic::x86_avx_vperm2f128_si_256:
11497   case Intrinsic::x86_avx2_vperm2i128:
11498     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11499                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11500
11501   case Intrinsic::x86_avx2_permd:
11502   case Intrinsic::x86_avx2_permps:
11503     // Operands intentionally swapped. Mask is last operand to intrinsic,
11504     // but second operand for node/instruction.
11505     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11506                        Op.getOperand(2), Op.getOperand(1));
11507
11508   case Intrinsic::x86_sse_sqrt_ps:
11509   case Intrinsic::x86_sse2_sqrt_pd:
11510   case Intrinsic::x86_avx_sqrt_ps_256:
11511   case Intrinsic::x86_avx_sqrt_pd_256:
11512     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11513
11514   // ptest and testp intrinsics. The intrinsic these come from are designed to
11515   // return an integer value, not just an instruction so lower it to the ptest
11516   // or testp pattern and a setcc for the result.
11517   case Intrinsic::x86_sse41_ptestz:
11518   case Intrinsic::x86_sse41_ptestc:
11519   case Intrinsic::x86_sse41_ptestnzc:
11520   case Intrinsic::x86_avx_ptestz_256:
11521   case Intrinsic::x86_avx_ptestc_256:
11522   case Intrinsic::x86_avx_ptestnzc_256:
11523   case Intrinsic::x86_avx_vtestz_ps:
11524   case Intrinsic::x86_avx_vtestc_ps:
11525   case Intrinsic::x86_avx_vtestnzc_ps:
11526   case Intrinsic::x86_avx_vtestz_pd:
11527   case Intrinsic::x86_avx_vtestc_pd:
11528   case Intrinsic::x86_avx_vtestnzc_pd:
11529   case Intrinsic::x86_avx_vtestz_ps_256:
11530   case Intrinsic::x86_avx_vtestc_ps_256:
11531   case Intrinsic::x86_avx_vtestnzc_ps_256:
11532   case Intrinsic::x86_avx_vtestz_pd_256:
11533   case Intrinsic::x86_avx_vtestc_pd_256:
11534   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11535     bool IsTestPacked = false;
11536     unsigned X86CC;
11537     switch (IntNo) {
11538     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11539     case Intrinsic::x86_avx_vtestz_ps:
11540     case Intrinsic::x86_avx_vtestz_pd:
11541     case Intrinsic::x86_avx_vtestz_ps_256:
11542     case Intrinsic::x86_avx_vtestz_pd_256:
11543       IsTestPacked = true; // Fallthrough
11544     case Intrinsic::x86_sse41_ptestz:
11545     case Intrinsic::x86_avx_ptestz_256:
11546       // ZF = 1
11547       X86CC = X86::COND_E;
11548       break;
11549     case Intrinsic::x86_avx_vtestc_ps:
11550     case Intrinsic::x86_avx_vtestc_pd:
11551     case Intrinsic::x86_avx_vtestc_ps_256:
11552     case Intrinsic::x86_avx_vtestc_pd_256:
11553       IsTestPacked = true; // Fallthrough
11554     case Intrinsic::x86_sse41_ptestc:
11555     case Intrinsic::x86_avx_ptestc_256:
11556       // CF = 1
11557       X86CC = X86::COND_B;
11558       break;
11559     case Intrinsic::x86_avx_vtestnzc_ps:
11560     case Intrinsic::x86_avx_vtestnzc_pd:
11561     case Intrinsic::x86_avx_vtestnzc_ps_256:
11562     case Intrinsic::x86_avx_vtestnzc_pd_256:
11563       IsTestPacked = true; // Fallthrough
11564     case Intrinsic::x86_sse41_ptestnzc:
11565     case Intrinsic::x86_avx_ptestnzc_256:
11566       // ZF and CF = 0
11567       X86CC = X86::COND_A;
11568       break;
11569     }
11570
11571     SDValue LHS = Op.getOperand(1);
11572     SDValue RHS = Op.getOperand(2);
11573     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11574     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11575     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11576     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11577     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11578   }
11579   case Intrinsic::x86_avx512_kortestz_w:
11580   case Intrinsic::x86_avx512_kortestc_w: {
11581     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11582     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11583     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11584     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11585     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11586     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11587     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11588   }
11589
11590   // SSE/AVX shift intrinsics
11591   case Intrinsic::x86_sse2_psll_w:
11592   case Intrinsic::x86_sse2_psll_d:
11593   case Intrinsic::x86_sse2_psll_q:
11594   case Intrinsic::x86_avx2_psll_w:
11595   case Intrinsic::x86_avx2_psll_d:
11596   case Intrinsic::x86_avx2_psll_q:
11597   case Intrinsic::x86_sse2_psrl_w:
11598   case Intrinsic::x86_sse2_psrl_d:
11599   case Intrinsic::x86_sse2_psrl_q:
11600   case Intrinsic::x86_avx2_psrl_w:
11601   case Intrinsic::x86_avx2_psrl_d:
11602   case Intrinsic::x86_avx2_psrl_q:
11603   case Intrinsic::x86_sse2_psra_w:
11604   case Intrinsic::x86_sse2_psra_d:
11605   case Intrinsic::x86_avx2_psra_w:
11606   case Intrinsic::x86_avx2_psra_d: {
11607     unsigned Opcode;
11608     switch (IntNo) {
11609     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11610     case Intrinsic::x86_sse2_psll_w:
11611     case Intrinsic::x86_sse2_psll_d:
11612     case Intrinsic::x86_sse2_psll_q:
11613     case Intrinsic::x86_avx2_psll_w:
11614     case Intrinsic::x86_avx2_psll_d:
11615     case Intrinsic::x86_avx2_psll_q:
11616       Opcode = X86ISD::VSHL;
11617       break;
11618     case Intrinsic::x86_sse2_psrl_w:
11619     case Intrinsic::x86_sse2_psrl_d:
11620     case Intrinsic::x86_sse2_psrl_q:
11621     case Intrinsic::x86_avx2_psrl_w:
11622     case Intrinsic::x86_avx2_psrl_d:
11623     case Intrinsic::x86_avx2_psrl_q:
11624       Opcode = X86ISD::VSRL;
11625       break;
11626     case Intrinsic::x86_sse2_psra_w:
11627     case Intrinsic::x86_sse2_psra_d:
11628     case Intrinsic::x86_avx2_psra_w:
11629     case Intrinsic::x86_avx2_psra_d:
11630       Opcode = X86ISD::VSRA;
11631       break;
11632     }
11633     return DAG.getNode(Opcode, dl, Op.getValueType(),
11634                        Op.getOperand(1), Op.getOperand(2));
11635   }
11636
11637   // SSE/AVX immediate shift intrinsics
11638   case Intrinsic::x86_sse2_pslli_w:
11639   case Intrinsic::x86_sse2_pslli_d:
11640   case Intrinsic::x86_sse2_pslli_q:
11641   case Intrinsic::x86_avx2_pslli_w:
11642   case Intrinsic::x86_avx2_pslli_d:
11643   case Intrinsic::x86_avx2_pslli_q:
11644   case Intrinsic::x86_sse2_psrli_w:
11645   case Intrinsic::x86_sse2_psrli_d:
11646   case Intrinsic::x86_sse2_psrli_q:
11647   case Intrinsic::x86_avx2_psrli_w:
11648   case Intrinsic::x86_avx2_psrli_d:
11649   case Intrinsic::x86_avx2_psrli_q:
11650   case Intrinsic::x86_sse2_psrai_w:
11651   case Intrinsic::x86_sse2_psrai_d:
11652   case Intrinsic::x86_avx2_psrai_w:
11653   case Intrinsic::x86_avx2_psrai_d: {
11654     unsigned Opcode;
11655     switch (IntNo) {
11656     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11657     case Intrinsic::x86_sse2_pslli_w:
11658     case Intrinsic::x86_sse2_pslli_d:
11659     case Intrinsic::x86_sse2_pslli_q:
11660     case Intrinsic::x86_avx2_pslli_w:
11661     case Intrinsic::x86_avx2_pslli_d:
11662     case Intrinsic::x86_avx2_pslli_q:
11663       Opcode = X86ISD::VSHLI;
11664       break;
11665     case Intrinsic::x86_sse2_psrli_w:
11666     case Intrinsic::x86_sse2_psrli_d:
11667     case Intrinsic::x86_sse2_psrli_q:
11668     case Intrinsic::x86_avx2_psrli_w:
11669     case Intrinsic::x86_avx2_psrli_d:
11670     case Intrinsic::x86_avx2_psrli_q:
11671       Opcode = X86ISD::VSRLI;
11672       break;
11673     case Intrinsic::x86_sse2_psrai_w:
11674     case Intrinsic::x86_sse2_psrai_d:
11675     case Intrinsic::x86_avx2_psrai_w:
11676     case Intrinsic::x86_avx2_psrai_d:
11677       Opcode = X86ISD::VSRAI;
11678       break;
11679     }
11680     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11681                                Op.getOperand(1), Op.getOperand(2), DAG);
11682   }
11683
11684   case Intrinsic::x86_sse42_pcmpistria128:
11685   case Intrinsic::x86_sse42_pcmpestria128:
11686   case Intrinsic::x86_sse42_pcmpistric128:
11687   case Intrinsic::x86_sse42_pcmpestric128:
11688   case Intrinsic::x86_sse42_pcmpistrio128:
11689   case Intrinsic::x86_sse42_pcmpestrio128:
11690   case Intrinsic::x86_sse42_pcmpistris128:
11691   case Intrinsic::x86_sse42_pcmpestris128:
11692   case Intrinsic::x86_sse42_pcmpistriz128:
11693   case Intrinsic::x86_sse42_pcmpestriz128: {
11694     unsigned Opcode;
11695     unsigned X86CC;
11696     switch (IntNo) {
11697     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11698     case Intrinsic::x86_sse42_pcmpistria128:
11699       Opcode = X86ISD::PCMPISTRI;
11700       X86CC = X86::COND_A;
11701       break;
11702     case Intrinsic::x86_sse42_pcmpestria128:
11703       Opcode = X86ISD::PCMPESTRI;
11704       X86CC = X86::COND_A;
11705       break;
11706     case Intrinsic::x86_sse42_pcmpistric128:
11707       Opcode = X86ISD::PCMPISTRI;
11708       X86CC = X86::COND_B;
11709       break;
11710     case Intrinsic::x86_sse42_pcmpestric128:
11711       Opcode = X86ISD::PCMPESTRI;
11712       X86CC = X86::COND_B;
11713       break;
11714     case Intrinsic::x86_sse42_pcmpistrio128:
11715       Opcode = X86ISD::PCMPISTRI;
11716       X86CC = X86::COND_O;
11717       break;
11718     case Intrinsic::x86_sse42_pcmpestrio128:
11719       Opcode = X86ISD::PCMPESTRI;
11720       X86CC = X86::COND_O;
11721       break;
11722     case Intrinsic::x86_sse42_pcmpistris128:
11723       Opcode = X86ISD::PCMPISTRI;
11724       X86CC = X86::COND_S;
11725       break;
11726     case Intrinsic::x86_sse42_pcmpestris128:
11727       Opcode = X86ISD::PCMPESTRI;
11728       X86CC = X86::COND_S;
11729       break;
11730     case Intrinsic::x86_sse42_pcmpistriz128:
11731       Opcode = X86ISD::PCMPISTRI;
11732       X86CC = X86::COND_E;
11733       break;
11734     case Intrinsic::x86_sse42_pcmpestriz128:
11735       Opcode = X86ISD::PCMPESTRI;
11736       X86CC = X86::COND_E;
11737       break;
11738     }
11739     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11740     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11741     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11742     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11743                                 DAG.getConstant(X86CC, MVT::i8),
11744                                 SDValue(PCMP.getNode(), 1));
11745     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11746   }
11747
11748   case Intrinsic::x86_sse42_pcmpistri128:
11749   case Intrinsic::x86_sse42_pcmpestri128: {
11750     unsigned Opcode;
11751     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11752       Opcode = X86ISD::PCMPISTRI;
11753     else
11754       Opcode = X86ISD::PCMPESTRI;
11755
11756     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11757     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11758     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11759   }
11760   case Intrinsic::x86_fma_vfmadd_ps:
11761   case Intrinsic::x86_fma_vfmadd_pd:
11762   case Intrinsic::x86_fma_vfmsub_ps:
11763   case Intrinsic::x86_fma_vfmsub_pd:
11764   case Intrinsic::x86_fma_vfnmadd_ps:
11765   case Intrinsic::x86_fma_vfnmadd_pd:
11766   case Intrinsic::x86_fma_vfnmsub_ps:
11767   case Intrinsic::x86_fma_vfnmsub_pd:
11768   case Intrinsic::x86_fma_vfmaddsub_ps:
11769   case Intrinsic::x86_fma_vfmaddsub_pd:
11770   case Intrinsic::x86_fma_vfmsubadd_ps:
11771   case Intrinsic::x86_fma_vfmsubadd_pd:
11772   case Intrinsic::x86_fma_vfmadd_ps_256:
11773   case Intrinsic::x86_fma_vfmadd_pd_256:
11774   case Intrinsic::x86_fma_vfmsub_ps_256:
11775   case Intrinsic::x86_fma_vfmsub_pd_256:
11776   case Intrinsic::x86_fma_vfnmadd_ps_256:
11777   case Intrinsic::x86_fma_vfnmadd_pd_256:
11778   case Intrinsic::x86_fma_vfnmsub_ps_256:
11779   case Intrinsic::x86_fma_vfnmsub_pd_256:
11780   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11781   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11782   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11783   case Intrinsic::x86_fma_vfmsubadd_pd_256:
11784   case Intrinsic::x86_fma_vfmadd_ps_512:
11785   case Intrinsic::x86_fma_vfmadd_pd_512:
11786   case Intrinsic::x86_fma_vfmsub_ps_512:
11787   case Intrinsic::x86_fma_vfmsub_pd_512:
11788   case Intrinsic::x86_fma_vfnmadd_ps_512:
11789   case Intrinsic::x86_fma_vfnmadd_pd_512:
11790   case Intrinsic::x86_fma_vfnmsub_ps_512:
11791   case Intrinsic::x86_fma_vfnmsub_pd_512:
11792   case Intrinsic::x86_fma_vfmaddsub_ps_512:
11793   case Intrinsic::x86_fma_vfmaddsub_pd_512:
11794   case Intrinsic::x86_fma_vfmsubadd_ps_512:
11795   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11796     unsigned Opc;
11797     switch (IntNo) {
11798     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11799     case Intrinsic::x86_fma_vfmadd_ps:
11800     case Intrinsic::x86_fma_vfmadd_pd:
11801     case Intrinsic::x86_fma_vfmadd_ps_256:
11802     case Intrinsic::x86_fma_vfmadd_pd_256:
11803     case Intrinsic::x86_fma_vfmadd_ps_512:
11804     case Intrinsic::x86_fma_vfmadd_pd_512:
11805       Opc = X86ISD::FMADD;
11806       break;
11807     case Intrinsic::x86_fma_vfmsub_ps:
11808     case Intrinsic::x86_fma_vfmsub_pd:
11809     case Intrinsic::x86_fma_vfmsub_ps_256:
11810     case Intrinsic::x86_fma_vfmsub_pd_256:
11811     case Intrinsic::x86_fma_vfmsub_ps_512:
11812     case Intrinsic::x86_fma_vfmsub_pd_512:
11813       Opc = X86ISD::FMSUB;
11814       break;
11815     case Intrinsic::x86_fma_vfnmadd_ps:
11816     case Intrinsic::x86_fma_vfnmadd_pd:
11817     case Intrinsic::x86_fma_vfnmadd_ps_256:
11818     case Intrinsic::x86_fma_vfnmadd_pd_256:
11819     case Intrinsic::x86_fma_vfnmadd_ps_512:
11820     case Intrinsic::x86_fma_vfnmadd_pd_512:
11821       Opc = X86ISD::FNMADD;
11822       break;
11823     case Intrinsic::x86_fma_vfnmsub_ps:
11824     case Intrinsic::x86_fma_vfnmsub_pd:
11825     case Intrinsic::x86_fma_vfnmsub_ps_256:
11826     case Intrinsic::x86_fma_vfnmsub_pd_256:
11827     case Intrinsic::x86_fma_vfnmsub_ps_512:
11828     case Intrinsic::x86_fma_vfnmsub_pd_512:
11829       Opc = X86ISD::FNMSUB;
11830       break;
11831     case Intrinsic::x86_fma_vfmaddsub_ps:
11832     case Intrinsic::x86_fma_vfmaddsub_pd:
11833     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11834     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11835     case Intrinsic::x86_fma_vfmaddsub_ps_512:
11836     case Intrinsic::x86_fma_vfmaddsub_pd_512:
11837       Opc = X86ISD::FMADDSUB;
11838       break;
11839     case Intrinsic::x86_fma_vfmsubadd_ps:
11840     case Intrinsic::x86_fma_vfmsubadd_pd:
11841     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11842     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11843     case Intrinsic::x86_fma_vfmsubadd_ps_512:
11844     case Intrinsic::x86_fma_vfmsubadd_pd_512:
11845       Opc = X86ISD::FMSUBADD;
11846       break;
11847     }
11848
11849     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11850                        Op.getOperand(2), Op.getOperand(3));
11851   }
11852   }
11853 }
11854
11855 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11856                              SDValue Base, SDValue Index,
11857                              SDValue ScaleOp, SDValue Chain,
11858                              const X86Subtarget * Subtarget) {
11859   SDLoc dl(Op);
11860   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11861   assert(C && "Invalid scale type");
11862   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11863   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11864   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11865                                 Index.getValueType().getVectorNumElements());
11866   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11867   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11868   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11869   SDValue Segment = DAG.getRegister(0, MVT::i32);
11870   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11871   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11872   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11873   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11874 }
11875
11876 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11877                               SDValue Src, SDValue Mask, SDValue Base,
11878                               SDValue Index, SDValue ScaleOp, SDValue Chain,
11879                               const X86Subtarget * Subtarget) {
11880   SDLoc dl(Op);
11881   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11882   assert(C && "Invalid scale type");
11883   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11884   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11885                                 Index.getValueType().getVectorNumElements());
11886   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11887   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11888   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11889   SDValue Segment = DAG.getRegister(0, MVT::i32);
11890   if (Src.getOpcode() == ISD::UNDEF)
11891     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11892   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11893   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11894   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11895   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11896 }
11897
11898 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11899                               SDValue Src, SDValue Base, SDValue Index,
11900                               SDValue ScaleOp, SDValue Chain) {
11901   SDLoc dl(Op);
11902   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11903   assert(C && "Invalid scale type");
11904   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11905   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11906   SDValue Segment = DAG.getRegister(0, MVT::i32);
11907   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11908                                 Index.getValueType().getVectorNumElements());
11909   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11910   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11911   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11912   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11913   return SDValue(Res, 1);
11914 }
11915
11916 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11917                                SDValue Src, SDValue Mask, SDValue Base,
11918                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
11919   SDLoc dl(Op);
11920   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11921   assert(C && "Invalid scale type");
11922   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11923   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11924   SDValue Segment = DAG.getRegister(0, MVT::i32);
11925   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11926                                 Index.getValueType().getVectorNumElements());
11927   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11928   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11929   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11930   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11931   return SDValue(Res, 1);
11932 }
11933
11934 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
11935                                       SelectionDAG &DAG) {
11936   SDLoc dl(Op);
11937   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11938   switch (IntNo) {
11939   default: return SDValue();    // Don't custom lower most intrinsics.
11940
11941   // RDRAND/RDSEED intrinsics.
11942   case Intrinsic::x86_rdrand_16:
11943   case Intrinsic::x86_rdrand_32:
11944   case Intrinsic::x86_rdrand_64:
11945   case Intrinsic::x86_rdseed_16:
11946   case Intrinsic::x86_rdseed_32:
11947   case Intrinsic::x86_rdseed_64: {
11948     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11949                        IntNo == Intrinsic::x86_rdseed_32 ||
11950                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11951                                                             X86ISD::RDRAND;
11952     // Emit the node with the right value type.
11953     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11954     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11955
11956     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11957     // Otherwise return the value from Rand, which is always 0, casted to i32.
11958     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11959                       DAG.getConstant(1, Op->getValueType(1)),
11960                       DAG.getConstant(X86::COND_B, MVT::i32),
11961                       SDValue(Result.getNode(), 1) };
11962     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11963                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11964                                   Ops, array_lengthof(Ops));
11965
11966     // Return { result, isValid, chain }.
11967     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11968                        SDValue(Result.getNode(), 2));
11969   }
11970   //int_gather(index, base, scale);
11971   case Intrinsic::x86_avx512_gather_qpd_512:
11972   case Intrinsic::x86_avx512_gather_qps_512:
11973   case Intrinsic::x86_avx512_gather_dpd_512:
11974   case Intrinsic::x86_avx512_gather_qpi_512:
11975   case Intrinsic::x86_avx512_gather_qpq_512:
11976   case Intrinsic::x86_avx512_gather_dpq_512:
11977   case Intrinsic::x86_avx512_gather_dps_512:
11978   case Intrinsic::x86_avx512_gather_dpi_512: {
11979     unsigned Opc;
11980     switch (IntNo) {
11981       default: llvm_unreachable("Unexpected intrinsic!");
11982       case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
11983       case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
11984       case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
11985       case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
11986       case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
11987       case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
11988       case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
11989       case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
11990     }
11991     SDValue Chain = Op.getOperand(0);
11992     SDValue Index = Op.getOperand(2);
11993     SDValue Base  = Op.getOperand(3);
11994     SDValue Scale = Op.getOperand(4);
11995     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
11996   }
11997   //int_gather_mask(v1, mask, index, base, scale);
11998   case Intrinsic::x86_avx512_gather_qps_mask_512:
11999   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12000   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12001   case Intrinsic::x86_avx512_gather_dps_mask_512:
12002   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12003   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12004   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12005   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12006     unsigned Opc;
12007     switch (IntNo) {
12008       default: llvm_unreachable("Unexpected intrinsic!");
12009       case Intrinsic::x86_avx512_gather_qps_mask_512:
12010         Opc = X86::VGATHERQPSZrm; break;
12011       case Intrinsic::x86_avx512_gather_qpd_mask_512:
12012         Opc = X86::VGATHERQPDZrm; break;
12013       case Intrinsic::x86_avx512_gather_dpd_mask_512:
12014         Opc = X86::VGATHERDPDZrm; break;
12015       case Intrinsic::x86_avx512_gather_dps_mask_512:
12016         Opc = X86::VGATHERDPSZrm; break;
12017       case Intrinsic::x86_avx512_gather_qpi_mask_512:
12018         Opc = X86::VPGATHERQDZrm; break;
12019       case Intrinsic::x86_avx512_gather_qpq_mask_512:
12020         Opc = X86::VPGATHERQQZrm; break;
12021       case Intrinsic::x86_avx512_gather_dpi_mask_512:
12022         Opc = X86::VPGATHERDDZrm; break;
12023       case Intrinsic::x86_avx512_gather_dpq_mask_512:
12024         Opc = X86::VPGATHERDQZrm; break;
12025     }
12026     SDValue Chain = Op.getOperand(0);
12027     SDValue Src   = Op.getOperand(2);
12028     SDValue Mask  = Op.getOperand(3);
12029     SDValue Index = Op.getOperand(4);
12030     SDValue Base  = Op.getOperand(5);
12031     SDValue Scale = Op.getOperand(6);
12032     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12033                           Subtarget);
12034   }
12035   //int_scatter(base, index, v1, scale);
12036   case Intrinsic::x86_avx512_scatter_qpd_512:
12037   case Intrinsic::x86_avx512_scatter_qps_512:
12038   case Intrinsic::x86_avx512_scatter_dpd_512:
12039   case Intrinsic::x86_avx512_scatter_qpi_512:
12040   case Intrinsic::x86_avx512_scatter_qpq_512:
12041   case Intrinsic::x86_avx512_scatter_dpq_512:
12042   case Intrinsic::x86_avx512_scatter_dps_512:
12043   case Intrinsic::x86_avx512_scatter_dpi_512: {
12044     unsigned Opc;
12045     switch (IntNo) {
12046       default: llvm_unreachable("Unexpected intrinsic!");
12047       case Intrinsic::x86_avx512_scatter_qpd_512:
12048         Opc = X86::VSCATTERQPDZmr; break;
12049       case Intrinsic::x86_avx512_scatter_qps_512:
12050         Opc = X86::VSCATTERQPSZmr; break;
12051       case Intrinsic::x86_avx512_scatter_dpd_512:
12052         Opc = X86::VSCATTERDPDZmr; break;
12053       case Intrinsic::x86_avx512_scatter_dps_512:
12054         Opc = X86::VSCATTERDPSZmr; break;
12055       case Intrinsic::x86_avx512_scatter_qpi_512:
12056         Opc = X86::VPSCATTERQDZmr; break;
12057       case Intrinsic::x86_avx512_scatter_qpq_512:
12058         Opc = X86::VPSCATTERQQZmr; break;
12059       case Intrinsic::x86_avx512_scatter_dpq_512:
12060         Opc = X86::VPSCATTERDQZmr; break;
12061       case Intrinsic::x86_avx512_scatter_dpi_512:
12062         Opc = X86::VPSCATTERDDZmr; break;
12063     }
12064     SDValue Chain = Op.getOperand(0);
12065     SDValue Base  = Op.getOperand(2);
12066     SDValue Index = Op.getOperand(3);
12067     SDValue Src   = Op.getOperand(4);
12068     SDValue Scale = Op.getOperand(5);
12069     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12070   }
12071   //int_scatter_mask(base, mask, index, v1, scale);
12072   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12073   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12074   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12075   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12076   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12077   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12078   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12079   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12080     unsigned Opc;
12081     switch (IntNo) {
12082       default: llvm_unreachable("Unexpected intrinsic!");
12083       case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12084         Opc = X86::VSCATTERQPDZmr; break;
12085       case Intrinsic::x86_avx512_scatter_qps_mask_512:
12086         Opc = X86::VSCATTERQPSZmr; break;
12087       case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12088         Opc = X86::VSCATTERDPDZmr; break;
12089       case Intrinsic::x86_avx512_scatter_dps_mask_512:
12090         Opc = X86::VSCATTERDPSZmr; break;
12091       case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12092         Opc = X86::VPSCATTERQDZmr; break;
12093       case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12094         Opc = X86::VPSCATTERQQZmr; break;
12095       case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12096         Opc = X86::VPSCATTERDQZmr; break;
12097       case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12098         Opc = X86::VPSCATTERDDZmr; break;
12099     }
12100     SDValue Chain = Op.getOperand(0);
12101     SDValue Base  = Op.getOperand(2);
12102     SDValue Mask  = Op.getOperand(3);
12103     SDValue Index = Op.getOperand(4);
12104     SDValue Src   = Op.getOperand(5);
12105     SDValue Scale = Op.getOperand(6);
12106     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12107   }
12108   // XTEST intrinsics.
12109   case Intrinsic::x86_xtest: {
12110     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12111     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12112     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12113                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12114                                 InTrans);
12115     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12116     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12117                        Ret, SDValue(InTrans.getNode(), 1));
12118   }
12119   }
12120 }
12121
12122 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12123                                            SelectionDAG &DAG) const {
12124   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12125   MFI->setReturnAddressIsTaken(true);
12126
12127   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12128   SDLoc dl(Op);
12129   EVT PtrVT = getPointerTy();
12130
12131   if (Depth > 0) {
12132     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12133     const X86RegisterInfo *RegInfo =
12134       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12135     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12136     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12137                        DAG.getNode(ISD::ADD, dl, PtrVT,
12138                                    FrameAddr, Offset),
12139                        MachinePointerInfo(), false, false, false, 0);
12140   }
12141
12142   // Just load the return address.
12143   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12144   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12145                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12146 }
12147
12148 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12149   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12150   MFI->setFrameAddressIsTaken(true);
12151
12152   EVT VT = Op.getValueType();
12153   SDLoc dl(Op);  // FIXME probably not meaningful
12154   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12155   const X86RegisterInfo *RegInfo =
12156     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12157   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12158   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12159           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12160          "Invalid Frame Register!");
12161   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12162   while (Depth--)
12163     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12164                             MachinePointerInfo(),
12165                             false, false, false, 0);
12166   return FrameAddr;
12167 }
12168
12169 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12170                                                      SelectionDAG &DAG) const {
12171   const X86RegisterInfo *RegInfo =
12172     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12173   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12174 }
12175
12176 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12177   SDValue Chain     = Op.getOperand(0);
12178   SDValue Offset    = Op.getOperand(1);
12179   SDValue Handler   = Op.getOperand(2);
12180   SDLoc dl      (Op);
12181
12182   EVT PtrVT = getPointerTy();
12183   const X86RegisterInfo *RegInfo =
12184     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12185   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12186   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12187           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12188          "Invalid Frame Register!");
12189   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12190   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12191
12192   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12193                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12194   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12195   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12196                        false, false, 0);
12197   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12198
12199   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12200                      DAG.getRegister(StoreAddrReg, PtrVT));
12201 }
12202
12203 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12204                                                SelectionDAG &DAG) const {
12205   SDLoc DL(Op);
12206   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12207                      DAG.getVTList(MVT::i32, MVT::Other),
12208                      Op.getOperand(0), Op.getOperand(1));
12209 }
12210
12211 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12212                                                 SelectionDAG &DAG) const {
12213   SDLoc DL(Op);
12214   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12215                      Op.getOperand(0), Op.getOperand(1));
12216 }
12217
12218 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12219   return Op.getOperand(0);
12220 }
12221
12222 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12223                                                 SelectionDAG &DAG) const {
12224   SDValue Root = Op.getOperand(0);
12225   SDValue Trmp = Op.getOperand(1); // trampoline
12226   SDValue FPtr = Op.getOperand(2); // nested function
12227   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12228   SDLoc dl (Op);
12229
12230   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12231   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12232
12233   if (Subtarget->is64Bit()) {
12234     SDValue OutChains[6];
12235
12236     // Large code-model.
12237     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12238     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12239
12240     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12241     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12242
12243     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12244
12245     // Load the pointer to the nested function into R11.
12246     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12247     SDValue Addr = Trmp;
12248     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12249                                 Addr, MachinePointerInfo(TrmpAddr),
12250                                 false, false, 0);
12251
12252     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12253                        DAG.getConstant(2, MVT::i64));
12254     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12255                                 MachinePointerInfo(TrmpAddr, 2),
12256                                 false, false, 2);
12257
12258     // Load the 'nest' parameter value into R10.
12259     // R10 is specified in X86CallingConv.td
12260     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12261     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12262                        DAG.getConstant(10, MVT::i64));
12263     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12264                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12265                                 false, false, 0);
12266
12267     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12268                        DAG.getConstant(12, MVT::i64));
12269     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12270                                 MachinePointerInfo(TrmpAddr, 12),
12271                                 false, false, 2);
12272
12273     // Jump to the nested function.
12274     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12275     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12276                        DAG.getConstant(20, MVT::i64));
12277     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12278                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12279                                 false, false, 0);
12280
12281     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12282     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12283                        DAG.getConstant(22, MVT::i64));
12284     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12285                                 MachinePointerInfo(TrmpAddr, 22),
12286                                 false, false, 0);
12287
12288     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12289   } else {
12290     const Function *Func =
12291       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12292     CallingConv::ID CC = Func->getCallingConv();
12293     unsigned NestReg;
12294
12295     switch (CC) {
12296     default:
12297       llvm_unreachable("Unsupported calling convention");
12298     case CallingConv::C:
12299     case CallingConv::X86_StdCall: {
12300       // Pass 'nest' parameter in ECX.
12301       // Must be kept in sync with X86CallingConv.td
12302       NestReg = X86::ECX;
12303
12304       // Check that ECX wasn't needed by an 'inreg' parameter.
12305       FunctionType *FTy = Func->getFunctionType();
12306       const AttributeSet &Attrs = Func->getAttributes();
12307
12308       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12309         unsigned InRegCount = 0;
12310         unsigned Idx = 1;
12311
12312         for (FunctionType::param_iterator I = FTy->param_begin(),
12313              E = FTy->param_end(); I != E; ++I, ++Idx)
12314           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12315             // FIXME: should only count parameters that are lowered to integers.
12316             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12317
12318         if (InRegCount > 2) {
12319           report_fatal_error("Nest register in use - reduce number of inreg"
12320                              " parameters!");
12321         }
12322       }
12323       break;
12324     }
12325     case CallingConv::X86_FastCall:
12326     case CallingConv::X86_ThisCall:
12327     case CallingConv::Fast:
12328       // Pass 'nest' parameter in EAX.
12329       // Must be kept in sync with X86CallingConv.td
12330       NestReg = X86::EAX;
12331       break;
12332     }
12333
12334     SDValue OutChains[4];
12335     SDValue Addr, Disp;
12336
12337     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12338                        DAG.getConstant(10, MVT::i32));
12339     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12340
12341     // This is storing the opcode for MOV32ri.
12342     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12343     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12344     OutChains[0] = DAG.getStore(Root, dl,
12345                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12346                                 Trmp, MachinePointerInfo(TrmpAddr),
12347                                 false, false, 0);
12348
12349     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12350                        DAG.getConstant(1, MVT::i32));
12351     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12352                                 MachinePointerInfo(TrmpAddr, 1),
12353                                 false, false, 1);
12354
12355     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12356     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12357                        DAG.getConstant(5, MVT::i32));
12358     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12359                                 MachinePointerInfo(TrmpAddr, 5),
12360                                 false, false, 1);
12361
12362     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12363                        DAG.getConstant(6, MVT::i32));
12364     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12365                                 MachinePointerInfo(TrmpAddr, 6),
12366                                 false, false, 1);
12367
12368     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12369   }
12370 }
12371
12372 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12373                                             SelectionDAG &DAG) const {
12374   /*
12375    The rounding mode is in bits 11:10 of FPSR, and has the following
12376    settings:
12377      00 Round to nearest
12378      01 Round to -inf
12379      10 Round to +inf
12380      11 Round to 0
12381
12382   FLT_ROUNDS, on the other hand, expects the following:
12383     -1 Undefined
12384      0 Round to 0
12385      1 Round to nearest
12386      2 Round to +inf
12387      3 Round to -inf
12388
12389   To perform the conversion, we do:
12390     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12391   */
12392
12393   MachineFunction &MF = DAG.getMachineFunction();
12394   const TargetMachine &TM = MF.getTarget();
12395   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12396   unsigned StackAlignment = TFI.getStackAlignment();
12397   EVT VT = Op.getValueType();
12398   SDLoc DL(Op);
12399
12400   // Save FP Control Word to stack slot
12401   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12402   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12403
12404   MachineMemOperand *MMO =
12405    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12406                            MachineMemOperand::MOStore, 2, 2);
12407
12408   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12409   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12410                                           DAG.getVTList(MVT::Other),
12411                                           Ops, array_lengthof(Ops), MVT::i16,
12412                                           MMO);
12413
12414   // Load FP Control Word from stack slot
12415   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12416                             MachinePointerInfo(), false, false, false, 0);
12417
12418   // Transform as necessary
12419   SDValue CWD1 =
12420     DAG.getNode(ISD::SRL, DL, MVT::i16,
12421                 DAG.getNode(ISD::AND, DL, MVT::i16,
12422                             CWD, DAG.getConstant(0x800, MVT::i16)),
12423                 DAG.getConstant(11, MVT::i8));
12424   SDValue CWD2 =
12425     DAG.getNode(ISD::SRL, DL, MVT::i16,
12426                 DAG.getNode(ISD::AND, DL, MVT::i16,
12427                             CWD, DAG.getConstant(0x400, MVT::i16)),
12428                 DAG.getConstant(9, MVT::i8));
12429
12430   SDValue RetVal =
12431     DAG.getNode(ISD::AND, DL, MVT::i16,
12432                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12433                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12434                             DAG.getConstant(1, MVT::i16)),
12435                 DAG.getConstant(3, MVT::i16));
12436
12437   return DAG.getNode((VT.getSizeInBits() < 16 ?
12438                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12439 }
12440
12441 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12442   EVT VT = Op.getValueType();
12443   EVT OpVT = VT;
12444   unsigned NumBits = VT.getSizeInBits();
12445   SDLoc dl(Op);
12446
12447   Op = Op.getOperand(0);
12448   if (VT == MVT::i8) {
12449     // Zero extend to i32 since there is not an i8 bsr.
12450     OpVT = MVT::i32;
12451     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12452   }
12453
12454   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12455   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12456   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12457
12458   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12459   SDValue Ops[] = {
12460     Op,
12461     DAG.getConstant(NumBits+NumBits-1, OpVT),
12462     DAG.getConstant(X86::COND_E, MVT::i8),
12463     Op.getValue(1)
12464   };
12465   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12466
12467   // Finally xor with NumBits-1.
12468   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12469
12470   if (VT == MVT::i8)
12471     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12472   return Op;
12473 }
12474
12475 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12476   EVT VT = Op.getValueType();
12477   EVT OpVT = VT;
12478   unsigned NumBits = VT.getSizeInBits();
12479   SDLoc dl(Op);
12480
12481   Op = Op.getOperand(0);
12482   if (VT == MVT::i8) {
12483     // Zero extend to i32 since there is not an i8 bsr.
12484     OpVT = MVT::i32;
12485     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12486   }
12487
12488   // Issue a bsr (scan bits in reverse).
12489   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12490   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12491
12492   // And xor with NumBits-1.
12493   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12494
12495   if (VT == MVT::i8)
12496     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12497   return Op;
12498 }
12499
12500 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12501   EVT VT = Op.getValueType();
12502   unsigned NumBits = VT.getSizeInBits();
12503   SDLoc dl(Op);
12504   Op = Op.getOperand(0);
12505
12506   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12507   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12508   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12509
12510   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12511   SDValue Ops[] = {
12512     Op,
12513     DAG.getConstant(NumBits, VT),
12514     DAG.getConstant(X86::COND_E, MVT::i8),
12515     Op.getValue(1)
12516   };
12517   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12518 }
12519
12520 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12521 // ones, and then concatenate the result back.
12522 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12523   EVT VT = Op.getValueType();
12524
12525   assert(VT.is256BitVector() && VT.isInteger() &&
12526          "Unsupported value type for operation");
12527
12528   unsigned NumElems = VT.getVectorNumElements();
12529   SDLoc dl(Op);
12530
12531   // Extract the LHS vectors
12532   SDValue LHS = Op.getOperand(0);
12533   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12534   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12535
12536   // Extract the RHS vectors
12537   SDValue RHS = Op.getOperand(1);
12538   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12539   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12540
12541   MVT EltVT = VT.getVectorElementType().getSimpleVT();
12542   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12543
12544   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12545                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12546                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12547 }
12548
12549 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12550   assert(Op.getValueType().is256BitVector() &&
12551          Op.getValueType().isInteger() &&
12552          "Only handle AVX 256-bit vector integer operation");
12553   return Lower256IntArith(Op, DAG);
12554 }
12555
12556 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12557   assert(Op.getValueType().is256BitVector() &&
12558          Op.getValueType().isInteger() &&
12559          "Only handle AVX 256-bit vector integer operation");
12560   return Lower256IntArith(Op, DAG);
12561 }
12562
12563 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12564                         SelectionDAG &DAG) {
12565   SDLoc dl(Op);
12566   EVT VT = Op.getValueType();
12567
12568   // Decompose 256-bit ops into smaller 128-bit ops.
12569   if (VT.is256BitVector() && !Subtarget->hasInt256())
12570     return Lower256IntArith(Op, DAG);
12571
12572   SDValue A = Op.getOperand(0);
12573   SDValue B = Op.getOperand(1);
12574
12575   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12576   if (VT == MVT::v4i32) {
12577     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12578            "Should not custom lower when pmuldq is available!");
12579
12580     // Extract the odd parts.
12581     static const int UnpackMask[] = { 1, -1, 3, -1 };
12582     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12583     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12584
12585     // Multiply the even parts.
12586     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12587     // Now multiply odd parts.
12588     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12589
12590     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12591     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12592
12593     // Merge the two vectors back together with a shuffle. This expands into 2
12594     // shuffles.
12595     static const int ShufMask[] = { 0, 4, 2, 6 };
12596     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12597   }
12598
12599   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12600          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12601
12602   //  Ahi = psrlqi(a, 32);
12603   //  Bhi = psrlqi(b, 32);
12604   //
12605   //  AloBlo = pmuludq(a, b);
12606   //  AloBhi = pmuludq(a, Bhi);
12607   //  AhiBlo = pmuludq(Ahi, b);
12608
12609   //  AloBhi = psllqi(AloBhi, 32);
12610   //  AhiBlo = psllqi(AhiBlo, 32);
12611   //  return AloBlo + AloBhi + AhiBlo;
12612
12613   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12614   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12615
12616   // Bit cast to 32-bit vectors for MULUDQ
12617   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12618                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12619   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12620   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12621   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12622   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12623
12624   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12625   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12626   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12627
12628   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12629   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12630
12631   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12632   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12633 }
12634
12635 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12636   EVT VT = Op.getValueType();
12637   EVT EltTy = VT.getVectorElementType();
12638   unsigned NumElts = VT.getVectorNumElements();
12639   SDValue N0 = Op.getOperand(0);
12640   SDLoc dl(Op);
12641
12642   // Lower sdiv X, pow2-const.
12643   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12644   if (!C)
12645     return SDValue();
12646
12647   APInt SplatValue, SplatUndef;
12648   unsigned SplatBitSize;
12649   bool HasAnyUndefs;
12650   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12651                           HasAnyUndefs) ||
12652       EltTy.getSizeInBits() < SplatBitSize)
12653     return SDValue();
12654
12655   if ((SplatValue != 0) &&
12656       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12657     unsigned Lg2 = SplatValue.countTrailingZeros();
12658     // Splat the sign bit.
12659     SmallVector<SDValue, 16> Sz(NumElts,
12660                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12661                                                 EltTy));
12662     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12663                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12664                                           NumElts));
12665     // Add (N0 < 0) ? abs2 - 1 : 0;
12666     SmallVector<SDValue, 16> Amt(NumElts,
12667                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12668                                                  EltTy));
12669     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12670                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12671                                           NumElts));
12672     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12673     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12674     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12675                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12676                                           NumElts));
12677
12678     // If we're dividing by a positive value, we're done.  Otherwise, we must
12679     // negate the result.
12680     if (SplatValue.isNonNegative())
12681       return SRA;
12682
12683     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12684     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12685     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12686   }
12687   return SDValue();
12688 }
12689
12690 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12691                                          const X86Subtarget *Subtarget) {
12692   EVT VT = Op.getValueType();
12693   SDLoc dl(Op);
12694   SDValue R = Op.getOperand(0);
12695   SDValue Amt = Op.getOperand(1);
12696
12697   // Optimize shl/srl/sra with constant shift amount.
12698   if (isSplatVector(Amt.getNode())) {
12699     SDValue SclrAmt = Amt->getOperand(0);
12700     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12701       uint64_t ShiftAmt = C->getZExtValue();
12702
12703       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12704           (Subtarget->hasInt256() &&
12705            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12706           (Subtarget->hasAVX512() &&
12707            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12708         if (Op.getOpcode() == ISD::SHL)
12709           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12710                                             DAG);
12711         if (Op.getOpcode() == ISD::SRL)
12712           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12713                                             DAG);
12714         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12715           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12716                                             DAG);
12717       }
12718
12719       if (VT == MVT::v16i8) {
12720         if (Op.getOpcode() == ISD::SHL) {
12721           // Make a large shift.
12722           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12723                                                    MVT::v8i16, R, ShiftAmt,
12724                                                    DAG);
12725           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12726           // Zero out the rightmost bits.
12727           SmallVector<SDValue, 16> V(16,
12728                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12729                                                      MVT::i8));
12730           return DAG.getNode(ISD::AND, dl, VT, SHL,
12731                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12732         }
12733         if (Op.getOpcode() == ISD::SRL) {
12734           // Make a large shift.
12735           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12736                                                    MVT::v8i16, R, ShiftAmt,
12737                                                    DAG);
12738           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12739           // Zero out the leftmost bits.
12740           SmallVector<SDValue, 16> V(16,
12741                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12742                                                      MVT::i8));
12743           return DAG.getNode(ISD::AND, dl, VT, SRL,
12744                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12745         }
12746         if (Op.getOpcode() == ISD::SRA) {
12747           if (ShiftAmt == 7) {
12748             // R s>> 7  ===  R s< 0
12749             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12750             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12751           }
12752
12753           // R s>> a === ((R u>> a) ^ m) - m
12754           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12755           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12756                                                          MVT::i8));
12757           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12758           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12759           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12760           return Res;
12761         }
12762         llvm_unreachable("Unknown shift opcode.");
12763       }
12764
12765       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12766         if (Op.getOpcode() == ISD::SHL) {
12767           // Make a large shift.
12768           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12769                                                    MVT::v16i16, R, ShiftAmt,
12770                                                    DAG);
12771           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12772           // Zero out the rightmost bits.
12773           SmallVector<SDValue, 32> V(32,
12774                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12775                                                      MVT::i8));
12776           return DAG.getNode(ISD::AND, dl, VT, SHL,
12777                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12778         }
12779         if (Op.getOpcode() == ISD::SRL) {
12780           // Make a large shift.
12781           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12782                                                    MVT::v16i16, R, ShiftAmt,
12783                                                    DAG);
12784           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12785           // Zero out the leftmost bits.
12786           SmallVector<SDValue, 32> V(32,
12787                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12788                                                      MVT::i8));
12789           return DAG.getNode(ISD::AND, dl, VT, SRL,
12790                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12791         }
12792         if (Op.getOpcode() == ISD::SRA) {
12793           if (ShiftAmt == 7) {
12794             // R s>> 7  ===  R s< 0
12795             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12796             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12797           }
12798
12799           // R s>> a === ((R u>> a) ^ m) - m
12800           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12801           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12802                                                          MVT::i8));
12803           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12804           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12805           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12806           return Res;
12807         }
12808         llvm_unreachable("Unknown shift opcode.");
12809       }
12810     }
12811   }
12812
12813   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12814   if (!Subtarget->is64Bit() &&
12815       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12816       Amt.getOpcode() == ISD::BITCAST &&
12817       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12818     Amt = Amt.getOperand(0);
12819     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12820                      VT.getVectorNumElements();
12821     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12822     uint64_t ShiftAmt = 0;
12823     for (unsigned i = 0; i != Ratio; ++i) {
12824       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12825       if (C == 0)
12826         return SDValue();
12827       // 6 == Log2(64)
12828       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12829     }
12830     // Check remaining shift amounts.
12831     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12832       uint64_t ShAmt = 0;
12833       for (unsigned j = 0; j != Ratio; ++j) {
12834         ConstantSDNode *C =
12835           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12836         if (C == 0)
12837           return SDValue();
12838         // 6 == Log2(64)
12839         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12840       }
12841       if (ShAmt != ShiftAmt)
12842         return SDValue();
12843     }
12844     switch (Op.getOpcode()) {
12845     default:
12846       llvm_unreachable("Unknown shift opcode!");
12847     case ISD::SHL:
12848       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12849                                         DAG);
12850     case ISD::SRL:
12851       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12852                                         DAG);
12853     case ISD::SRA:
12854       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12855                                         DAG);
12856     }
12857   }
12858
12859   return SDValue();
12860 }
12861
12862 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12863                                         const X86Subtarget* Subtarget) {
12864   EVT VT = Op.getValueType();
12865   SDLoc dl(Op);
12866   SDValue R = Op.getOperand(0);
12867   SDValue Amt = Op.getOperand(1);
12868
12869   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12870       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12871       (Subtarget->hasInt256() &&
12872        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12873         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12874        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12875     SDValue BaseShAmt;
12876     EVT EltVT = VT.getVectorElementType();
12877
12878     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12879       unsigned NumElts = VT.getVectorNumElements();
12880       unsigned i, j;
12881       for (i = 0; i != NumElts; ++i) {
12882         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12883           continue;
12884         break;
12885       }
12886       for (j = i; j != NumElts; ++j) {
12887         SDValue Arg = Amt.getOperand(j);
12888         if (Arg.getOpcode() == ISD::UNDEF) continue;
12889         if (Arg != Amt.getOperand(i))
12890           break;
12891       }
12892       if (i != NumElts && j == NumElts)
12893         BaseShAmt = Amt.getOperand(i);
12894     } else {
12895       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12896         Amt = Amt.getOperand(0);
12897       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12898                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12899         SDValue InVec = Amt.getOperand(0);
12900         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12901           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12902           unsigned i = 0;
12903           for (; i != NumElts; ++i) {
12904             SDValue Arg = InVec.getOperand(i);
12905             if (Arg.getOpcode() == ISD::UNDEF) continue;
12906             BaseShAmt = Arg;
12907             break;
12908           }
12909         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12910            if (ConstantSDNode *C =
12911                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12912              unsigned SplatIdx =
12913                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12914              if (C->getZExtValue() == SplatIdx)
12915                BaseShAmt = InVec.getOperand(1);
12916            }
12917         }
12918         if (BaseShAmt.getNode() == 0)
12919           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12920                                   DAG.getIntPtrConstant(0));
12921       }
12922     }
12923
12924     if (BaseShAmt.getNode()) {
12925       if (EltVT.bitsGT(MVT::i32))
12926         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12927       else if (EltVT.bitsLT(MVT::i32))
12928         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12929
12930       switch (Op.getOpcode()) {
12931       default:
12932         llvm_unreachable("Unknown shift opcode!");
12933       case ISD::SHL:
12934         switch (VT.getSimpleVT().SimpleTy) {
12935         default: return SDValue();
12936         case MVT::v2i64:
12937         case MVT::v4i32:
12938         case MVT::v8i16:
12939         case MVT::v4i64:
12940         case MVT::v8i32:
12941         case MVT::v16i16:
12942         case MVT::v16i32:
12943         case MVT::v8i64:
12944           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12945         }
12946       case ISD::SRA:
12947         switch (VT.getSimpleVT().SimpleTy) {
12948         default: return SDValue();
12949         case MVT::v4i32:
12950         case MVT::v8i16:
12951         case MVT::v8i32:
12952         case MVT::v16i16:
12953         case MVT::v16i32:
12954         case MVT::v8i64:
12955           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12956         }
12957       case ISD::SRL:
12958         switch (VT.getSimpleVT().SimpleTy) {
12959         default: return SDValue();
12960         case MVT::v2i64:
12961         case MVT::v4i32:
12962         case MVT::v8i16:
12963         case MVT::v4i64:
12964         case MVT::v8i32:
12965         case MVT::v16i16:
12966         case MVT::v16i32:
12967         case MVT::v8i64:
12968           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12969         }
12970       }
12971     }
12972   }
12973
12974   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12975   if (!Subtarget->is64Bit() &&
12976       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
12977       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
12978       Amt.getOpcode() == ISD::BITCAST &&
12979       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12980     Amt = Amt.getOperand(0);
12981     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12982                      VT.getVectorNumElements();
12983     std::vector<SDValue> Vals(Ratio);
12984     for (unsigned i = 0; i != Ratio; ++i)
12985       Vals[i] = Amt.getOperand(i);
12986     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12987       for (unsigned j = 0; j != Ratio; ++j)
12988         if (Vals[j] != Amt.getOperand(i + j))
12989           return SDValue();
12990     }
12991     switch (Op.getOpcode()) {
12992     default:
12993       llvm_unreachable("Unknown shift opcode!");
12994     case ISD::SHL:
12995       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12996     case ISD::SRL:
12997       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12998     case ISD::SRA:
12999       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13000     }
13001   }
13002
13003   return SDValue();
13004 }
13005
13006 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13007                           SelectionDAG &DAG) {
13008
13009   EVT VT = Op.getValueType();
13010   SDLoc dl(Op);
13011   SDValue R = Op.getOperand(0);
13012   SDValue Amt = Op.getOperand(1);
13013   SDValue V;
13014
13015   if (!Subtarget->hasSSE2())
13016     return SDValue();
13017
13018   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13019   if (V.getNode())
13020     return V;
13021
13022   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13023   if (V.getNode())
13024       return V;
13025
13026   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13027     return Op;
13028   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13029   if (Subtarget->hasInt256()) {
13030     if (Op.getOpcode() == ISD::SRL &&
13031         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13032          VT == MVT::v4i64 || VT == MVT::v8i32))
13033       return Op;
13034     if (Op.getOpcode() == ISD::SHL &&
13035         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13036          VT == MVT::v4i64 || VT == MVT::v8i32))
13037       return Op;
13038     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13039       return Op;
13040   }
13041
13042   // Lower SHL with variable shift amount.
13043   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13044     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13045
13046     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13047     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13048     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13049     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13050   }
13051   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13052     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13053
13054     // a = a << 5;
13055     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13056     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13057
13058     // Turn 'a' into a mask suitable for VSELECT
13059     SDValue VSelM = DAG.getConstant(0x80, VT);
13060     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13061     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13062
13063     SDValue CM1 = DAG.getConstant(0x0f, VT);
13064     SDValue CM2 = DAG.getConstant(0x3f, VT);
13065
13066     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13067     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13068     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13069     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13070     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13071
13072     // a += a
13073     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13074     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13075     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13076
13077     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13078     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13079     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13080     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13081     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13082
13083     // a += a
13084     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13085     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13086     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13087
13088     // return VSELECT(r, r+r, a);
13089     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13090                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13091     return R;
13092   }
13093
13094   // Decompose 256-bit shifts into smaller 128-bit shifts.
13095   if (VT.is256BitVector()) {
13096     unsigned NumElems = VT.getVectorNumElements();
13097     MVT EltVT = VT.getVectorElementType().getSimpleVT();
13098     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13099
13100     // Extract the two vectors
13101     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13102     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13103
13104     // Recreate the shift amount vectors
13105     SDValue Amt1, Amt2;
13106     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13107       // Constant shift amount
13108       SmallVector<SDValue, 4> Amt1Csts;
13109       SmallVector<SDValue, 4> Amt2Csts;
13110       for (unsigned i = 0; i != NumElems/2; ++i)
13111         Amt1Csts.push_back(Amt->getOperand(i));
13112       for (unsigned i = NumElems/2; i != NumElems; ++i)
13113         Amt2Csts.push_back(Amt->getOperand(i));
13114
13115       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13116                                  &Amt1Csts[0], NumElems/2);
13117       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13118                                  &Amt2Csts[0], NumElems/2);
13119     } else {
13120       // Variable shift amount
13121       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13122       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13123     }
13124
13125     // Issue new vector shifts for the smaller types
13126     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13127     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13128
13129     // Concatenate the result back
13130     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13131   }
13132
13133   return SDValue();
13134 }
13135
13136 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13137   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13138   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13139   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13140   // has only one use.
13141   SDNode *N = Op.getNode();
13142   SDValue LHS = N->getOperand(0);
13143   SDValue RHS = N->getOperand(1);
13144   unsigned BaseOp = 0;
13145   unsigned Cond = 0;
13146   SDLoc DL(Op);
13147   switch (Op.getOpcode()) {
13148   default: llvm_unreachable("Unknown ovf instruction!");
13149   case ISD::SADDO:
13150     // A subtract of one will be selected as a INC. Note that INC doesn't
13151     // set CF, so we can't do this for UADDO.
13152     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13153       if (C->isOne()) {
13154         BaseOp = X86ISD::INC;
13155         Cond = X86::COND_O;
13156         break;
13157       }
13158     BaseOp = X86ISD::ADD;
13159     Cond = X86::COND_O;
13160     break;
13161   case ISD::UADDO:
13162     BaseOp = X86ISD::ADD;
13163     Cond = X86::COND_B;
13164     break;
13165   case ISD::SSUBO:
13166     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13167     // set CF, so we can't do this for USUBO.
13168     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13169       if (C->isOne()) {
13170         BaseOp = X86ISD::DEC;
13171         Cond = X86::COND_O;
13172         break;
13173       }
13174     BaseOp = X86ISD::SUB;
13175     Cond = X86::COND_O;
13176     break;
13177   case ISD::USUBO:
13178     BaseOp = X86ISD::SUB;
13179     Cond = X86::COND_B;
13180     break;
13181   case ISD::SMULO:
13182     BaseOp = X86ISD::SMUL;
13183     Cond = X86::COND_O;
13184     break;
13185   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13186     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13187                                  MVT::i32);
13188     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13189
13190     SDValue SetCC =
13191       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13192                   DAG.getConstant(X86::COND_O, MVT::i32),
13193                   SDValue(Sum.getNode(), 2));
13194
13195     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13196   }
13197   }
13198
13199   // Also sets EFLAGS.
13200   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13201   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13202
13203   SDValue SetCC =
13204     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13205                 DAG.getConstant(Cond, MVT::i32),
13206                 SDValue(Sum.getNode(), 1));
13207
13208   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13209 }
13210
13211 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13212                                                   SelectionDAG &DAG) const {
13213   SDLoc dl(Op);
13214   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13215   EVT VT = Op.getValueType();
13216
13217   if (!Subtarget->hasSSE2() || !VT.isVector())
13218     return SDValue();
13219
13220   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13221                       ExtraVT.getScalarType().getSizeInBits();
13222
13223   switch (VT.getSimpleVT().SimpleTy) {
13224     default: return SDValue();
13225     case MVT::v8i32:
13226     case MVT::v16i16:
13227       if (!Subtarget->hasFp256())
13228         return SDValue();
13229       if (!Subtarget->hasInt256()) {
13230         // needs to be split
13231         unsigned NumElems = VT.getVectorNumElements();
13232
13233         // Extract the LHS vectors
13234         SDValue LHS = Op.getOperand(0);
13235         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13236         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13237
13238         MVT EltVT = VT.getVectorElementType().getSimpleVT();
13239         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13240
13241         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13242         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13243         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13244                                    ExtraNumElems/2);
13245         SDValue Extra = DAG.getValueType(ExtraVT);
13246
13247         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13248         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13249
13250         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13251       }
13252       // fall through
13253     case MVT::v4i32:
13254     case MVT::v8i16: {
13255       SDValue Op0 = Op.getOperand(0);
13256       SDValue Op00 = Op0.getOperand(0);
13257       SDValue Tmp1;
13258       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13259       if (Op0.getOpcode() == ISD::BITCAST &&
13260           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13261         // (sext (vzext x)) -> (vsext x)
13262         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13263         if (Tmp1.getNode()) {
13264           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13265           // This folding is only valid when the in-reg type is a vector of i8,
13266           // i16, or i32.
13267           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13268               ExtraEltVT == MVT::i32) {
13269             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13270             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13271                    "This optimization is invalid without a VZEXT.");
13272             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13273           }
13274           Op0 = Tmp1;
13275         }
13276       }
13277
13278       // If the above didn't work, then just use Shift-Left + Shift-Right.
13279       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13280                                         DAG);
13281       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13282                                         DAG);
13283     }
13284   }
13285 }
13286
13287 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13288                                  SelectionDAG &DAG) {
13289   SDLoc dl(Op);
13290   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13291     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13292   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13293     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13294
13295   // The only fence that needs an instruction is a sequentially-consistent
13296   // cross-thread fence.
13297   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13298     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13299     // no-sse2). There isn't any reason to disable it if the target processor
13300     // supports it.
13301     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13302       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13303
13304     SDValue Chain = Op.getOperand(0);
13305     SDValue Zero = DAG.getConstant(0, MVT::i32);
13306     SDValue Ops[] = {
13307       DAG.getRegister(X86::ESP, MVT::i32), // Base
13308       DAG.getTargetConstant(1, MVT::i8),   // Scale
13309       DAG.getRegister(0, MVT::i32),        // Index
13310       DAG.getTargetConstant(0, MVT::i32),  // Disp
13311       DAG.getRegister(0, MVT::i32),        // Segment.
13312       Zero,
13313       Chain
13314     };
13315     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13316     return SDValue(Res, 0);
13317   }
13318
13319   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13320   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13321 }
13322
13323 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13324                              SelectionDAG &DAG) {
13325   EVT T = Op.getValueType();
13326   SDLoc DL(Op);
13327   unsigned Reg = 0;
13328   unsigned size = 0;
13329   switch(T.getSimpleVT().SimpleTy) {
13330   default: llvm_unreachable("Invalid value type!");
13331   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13332   case MVT::i16: Reg = X86::AX;  size = 2; break;
13333   case MVT::i32: Reg = X86::EAX; size = 4; break;
13334   case MVT::i64:
13335     assert(Subtarget->is64Bit() && "Node not type legal!");
13336     Reg = X86::RAX; size = 8;
13337     break;
13338   }
13339   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13340                                     Op.getOperand(2), SDValue());
13341   SDValue Ops[] = { cpIn.getValue(0),
13342                     Op.getOperand(1),
13343                     Op.getOperand(3),
13344                     DAG.getTargetConstant(size, MVT::i8),
13345                     cpIn.getValue(1) };
13346   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13347   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13348   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13349                                            Ops, array_lengthof(Ops), T, MMO);
13350   SDValue cpOut =
13351     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13352   return cpOut;
13353 }
13354
13355 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13356                                      SelectionDAG &DAG) {
13357   assert(Subtarget->is64Bit() && "Result not type legalized?");
13358   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13359   SDValue TheChain = Op.getOperand(0);
13360   SDLoc dl(Op);
13361   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13362   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13363   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13364                                    rax.getValue(2));
13365   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13366                             DAG.getConstant(32, MVT::i8));
13367   SDValue Ops[] = {
13368     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13369     rdx.getValue(1)
13370   };
13371   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13372 }
13373
13374 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13375                             SelectionDAG &DAG) {
13376   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13377   MVT DstVT = Op.getSimpleValueType();
13378   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13379          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13380   assert((DstVT == MVT::i64 ||
13381           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13382          "Unexpected custom BITCAST");
13383   // i64 <=> MMX conversions are Legal.
13384   if (SrcVT==MVT::i64 && DstVT.isVector())
13385     return Op;
13386   if (DstVT==MVT::i64 && SrcVT.isVector())
13387     return Op;
13388   // MMX <=> MMX conversions are Legal.
13389   if (SrcVT.isVector() && DstVT.isVector())
13390     return Op;
13391   // All other conversions need to be expanded.
13392   return SDValue();
13393 }
13394
13395 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13396   SDNode *Node = Op.getNode();
13397   SDLoc dl(Node);
13398   EVT T = Node->getValueType(0);
13399   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13400                               DAG.getConstant(0, T), Node->getOperand(2));
13401   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13402                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13403                        Node->getOperand(0),
13404                        Node->getOperand(1), negOp,
13405                        cast<AtomicSDNode>(Node)->getSrcValue(),
13406                        cast<AtomicSDNode>(Node)->getAlignment(),
13407                        cast<AtomicSDNode>(Node)->getOrdering(),
13408                        cast<AtomicSDNode>(Node)->getSynchScope());
13409 }
13410
13411 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13412   SDNode *Node = Op.getNode();
13413   SDLoc dl(Node);
13414   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13415
13416   // Convert seq_cst store -> xchg
13417   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13418   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13419   //        (The only way to get a 16-byte store is cmpxchg16b)
13420   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13421   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13422       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13423     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13424                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13425                                  Node->getOperand(0),
13426                                  Node->getOperand(1), Node->getOperand(2),
13427                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13428                                  cast<AtomicSDNode>(Node)->getOrdering(),
13429                                  cast<AtomicSDNode>(Node)->getSynchScope());
13430     return Swap.getValue(1);
13431   }
13432   // Other atomic stores have a simple pattern.
13433   return Op;
13434 }
13435
13436 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13437   EVT VT = Op.getNode()->getValueType(0);
13438
13439   // Let legalize expand this if it isn't a legal type yet.
13440   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13441     return SDValue();
13442
13443   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13444
13445   unsigned Opc;
13446   bool ExtraOp = false;
13447   switch (Op.getOpcode()) {
13448   default: llvm_unreachable("Invalid code");
13449   case ISD::ADDC: Opc = X86ISD::ADD; break;
13450   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13451   case ISD::SUBC: Opc = X86ISD::SUB; break;
13452   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13453   }
13454
13455   if (!ExtraOp)
13456     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13457                        Op.getOperand(1));
13458   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13459                      Op.getOperand(1), Op.getOperand(2));
13460 }
13461
13462 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13463                             SelectionDAG &DAG) {
13464   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13465
13466   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13467   // which returns the values as { float, float } (in XMM0) or
13468   // { double, double } (which is returned in XMM0, XMM1).
13469   SDLoc dl(Op);
13470   SDValue Arg = Op.getOperand(0);
13471   EVT ArgVT = Arg.getValueType();
13472   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13473
13474   TargetLowering::ArgListTy Args;
13475   TargetLowering::ArgListEntry Entry;
13476
13477   Entry.Node = Arg;
13478   Entry.Ty = ArgTy;
13479   Entry.isSExt = false;
13480   Entry.isZExt = false;
13481   Args.push_back(Entry);
13482
13483   bool isF64 = ArgVT == MVT::f64;
13484   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13485   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13486   // the results are returned via SRet in memory.
13487   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13489   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13490
13491   Type *RetTy = isF64
13492     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13493     : (Type*)VectorType::get(ArgTy, 4);
13494   TargetLowering::
13495     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13496                          false, false, false, false, 0,
13497                          CallingConv::C, /*isTaillCall=*/false,
13498                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13499                          Callee, Args, DAG, dl);
13500   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13501
13502   if (isF64)
13503     // Returned in xmm0 and xmm1.
13504     return CallResult.first;
13505
13506   // Returned in bits 0:31 and 32:64 xmm0.
13507   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13508                                CallResult.first, DAG.getIntPtrConstant(0));
13509   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13510                                CallResult.first, DAG.getIntPtrConstant(1));
13511   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13512   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13513 }
13514
13515 /// LowerOperation - Provide custom lowering hooks for some operations.
13516 ///
13517 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13518   switch (Op.getOpcode()) {
13519   default: llvm_unreachable("Should not custom lower this!");
13520   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13521   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13522   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13523   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13524   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13525   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13526   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13527   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13528   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13529   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13530   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13531   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13532   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13533   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13534   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13535   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13536   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13537   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13538   case ISD::SHL_PARTS:
13539   case ISD::SRA_PARTS:
13540   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13541   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13542   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13543   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13544   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13545   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13546   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13547   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13548   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13549   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13550   case ISD::FABS:               return LowerFABS(Op, DAG);
13551   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13552   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13553   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13554   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13555   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13556   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13557   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13558   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13559   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13560   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13561   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13562   case ISD::INTRINSIC_VOID:
13563   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13564   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13565   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13566   case ISD::FRAME_TO_ARGS_OFFSET:
13567                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13568   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13569   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13570   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13571   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13572   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13573   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13574   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13575   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13576   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13577   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13578   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13579   case ISD::SRA:
13580   case ISD::SRL:
13581   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13582   case ISD::SADDO:
13583   case ISD::UADDO:
13584   case ISD::SSUBO:
13585   case ISD::USUBO:
13586   case ISD::SMULO:
13587   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13588   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13589   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13590   case ISD::ADDC:
13591   case ISD::ADDE:
13592   case ISD::SUBC:
13593   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13594   case ISD::ADD:                return LowerADD(Op, DAG);
13595   case ISD::SUB:                return LowerSUB(Op, DAG);
13596   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13597   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13598   }
13599 }
13600
13601 static void ReplaceATOMIC_LOAD(SDNode *Node,
13602                                   SmallVectorImpl<SDValue> &Results,
13603                                   SelectionDAG &DAG) {
13604   SDLoc dl(Node);
13605   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13606
13607   // Convert wide load -> cmpxchg8b/cmpxchg16b
13608   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13609   //        (The only way to get a 16-byte load is cmpxchg16b)
13610   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13611   SDValue Zero = DAG.getConstant(0, VT);
13612   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13613                                Node->getOperand(0),
13614                                Node->getOperand(1), Zero, Zero,
13615                                cast<AtomicSDNode>(Node)->getMemOperand(),
13616                                cast<AtomicSDNode>(Node)->getOrdering(),
13617                                cast<AtomicSDNode>(Node)->getSynchScope());
13618   Results.push_back(Swap.getValue(0));
13619   Results.push_back(Swap.getValue(1));
13620 }
13621
13622 static void
13623 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13624                         SelectionDAG &DAG, unsigned NewOp) {
13625   SDLoc dl(Node);
13626   assert (Node->getValueType(0) == MVT::i64 &&
13627           "Only know how to expand i64 atomics");
13628
13629   SDValue Chain = Node->getOperand(0);
13630   SDValue In1 = Node->getOperand(1);
13631   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13632                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13633   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13634                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13635   SDValue Ops[] = { Chain, In1, In2L, In2H };
13636   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13637   SDValue Result =
13638     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13639                             cast<MemSDNode>(Node)->getMemOperand());
13640   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13641   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13642   Results.push_back(Result.getValue(2));
13643 }
13644
13645 /// ReplaceNodeResults - Replace a node with an illegal result type
13646 /// with a new node built out of custom code.
13647 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13648                                            SmallVectorImpl<SDValue>&Results,
13649                                            SelectionDAG &DAG) const {
13650   SDLoc dl(N);
13651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13652   switch (N->getOpcode()) {
13653   default:
13654     llvm_unreachable("Do not know how to custom type legalize this operation!");
13655   case ISD::SIGN_EXTEND_INREG:
13656   case ISD::ADDC:
13657   case ISD::ADDE:
13658   case ISD::SUBC:
13659   case ISD::SUBE:
13660     // We don't want to expand or promote these.
13661     return;
13662   case ISD::FP_TO_SINT:
13663   case ISD::FP_TO_UINT: {
13664     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13665
13666     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13667       return;
13668
13669     std::pair<SDValue,SDValue> Vals =
13670         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13671     SDValue FIST = Vals.first, StackSlot = Vals.second;
13672     if (FIST.getNode() != 0) {
13673       EVT VT = N->getValueType(0);
13674       // Return a load from the stack slot.
13675       if (StackSlot.getNode() != 0)
13676         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13677                                       MachinePointerInfo(),
13678                                       false, false, false, 0));
13679       else
13680         Results.push_back(FIST);
13681     }
13682     return;
13683   }
13684   case ISD::UINT_TO_FP: {
13685     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13686     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13687         N->getValueType(0) != MVT::v2f32)
13688       return;
13689     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13690                                  N->getOperand(0));
13691     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13692                                      MVT::f64);
13693     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13694     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13695                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13696     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13697     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13698     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13699     return;
13700   }
13701   case ISD::FP_ROUND: {
13702     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13703         return;
13704     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13705     Results.push_back(V);
13706     return;
13707   }
13708   case ISD::READCYCLECOUNTER: {
13709     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13710     SDValue TheChain = N->getOperand(0);
13711     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13712     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13713                                      rd.getValue(1));
13714     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13715                                      eax.getValue(2));
13716     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13717     SDValue Ops[] = { eax, edx };
13718     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13719                                   array_lengthof(Ops)));
13720     Results.push_back(edx.getValue(1));
13721     return;
13722   }
13723   case ISD::ATOMIC_CMP_SWAP: {
13724     EVT T = N->getValueType(0);
13725     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13726     bool Regs64bit = T == MVT::i128;
13727     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13728     SDValue cpInL, cpInH;
13729     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13730                         DAG.getConstant(0, HalfT));
13731     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13732                         DAG.getConstant(1, HalfT));
13733     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13734                              Regs64bit ? X86::RAX : X86::EAX,
13735                              cpInL, SDValue());
13736     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13737                              Regs64bit ? X86::RDX : X86::EDX,
13738                              cpInH, cpInL.getValue(1));
13739     SDValue swapInL, swapInH;
13740     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13741                           DAG.getConstant(0, HalfT));
13742     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13743                           DAG.getConstant(1, HalfT));
13744     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13745                                Regs64bit ? X86::RBX : X86::EBX,
13746                                swapInL, cpInH.getValue(1));
13747     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13748                                Regs64bit ? X86::RCX : X86::ECX,
13749                                swapInH, swapInL.getValue(1));
13750     SDValue Ops[] = { swapInH.getValue(0),
13751                       N->getOperand(1),
13752                       swapInH.getValue(1) };
13753     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13754     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13755     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13756                                   X86ISD::LCMPXCHG8_DAG;
13757     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13758                                              Ops, array_lengthof(Ops), T, MMO);
13759     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13760                                         Regs64bit ? X86::RAX : X86::EAX,
13761                                         HalfT, Result.getValue(1));
13762     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13763                                         Regs64bit ? X86::RDX : X86::EDX,
13764                                         HalfT, cpOutL.getValue(2));
13765     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13766     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13767     Results.push_back(cpOutH.getValue(1));
13768     return;
13769   }
13770   case ISD::ATOMIC_LOAD_ADD:
13771   case ISD::ATOMIC_LOAD_AND:
13772   case ISD::ATOMIC_LOAD_NAND:
13773   case ISD::ATOMIC_LOAD_OR:
13774   case ISD::ATOMIC_LOAD_SUB:
13775   case ISD::ATOMIC_LOAD_XOR:
13776   case ISD::ATOMIC_LOAD_MAX:
13777   case ISD::ATOMIC_LOAD_MIN:
13778   case ISD::ATOMIC_LOAD_UMAX:
13779   case ISD::ATOMIC_LOAD_UMIN:
13780   case ISD::ATOMIC_SWAP: {
13781     unsigned Opc;
13782     switch (N->getOpcode()) {
13783     default: llvm_unreachable("Unexpected opcode");
13784     case ISD::ATOMIC_LOAD_ADD:
13785       Opc = X86ISD::ATOMADD64_DAG;
13786       break;
13787     case ISD::ATOMIC_LOAD_AND:
13788       Opc = X86ISD::ATOMAND64_DAG;
13789       break;
13790     case ISD::ATOMIC_LOAD_NAND:
13791       Opc = X86ISD::ATOMNAND64_DAG;
13792       break;
13793     case ISD::ATOMIC_LOAD_OR:
13794       Opc = X86ISD::ATOMOR64_DAG;
13795       break;
13796     case ISD::ATOMIC_LOAD_SUB:
13797       Opc = X86ISD::ATOMSUB64_DAG;
13798       break;
13799     case ISD::ATOMIC_LOAD_XOR:
13800       Opc = X86ISD::ATOMXOR64_DAG;
13801       break;
13802     case ISD::ATOMIC_LOAD_MAX:
13803       Opc = X86ISD::ATOMMAX64_DAG;
13804       break;
13805     case ISD::ATOMIC_LOAD_MIN:
13806       Opc = X86ISD::ATOMMIN64_DAG;
13807       break;
13808     case ISD::ATOMIC_LOAD_UMAX:
13809       Opc = X86ISD::ATOMUMAX64_DAG;
13810       break;
13811     case ISD::ATOMIC_LOAD_UMIN:
13812       Opc = X86ISD::ATOMUMIN64_DAG;
13813       break;
13814     case ISD::ATOMIC_SWAP:
13815       Opc = X86ISD::ATOMSWAP64_DAG;
13816       break;
13817     }
13818     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13819     return;
13820   }
13821   case ISD::ATOMIC_LOAD:
13822     ReplaceATOMIC_LOAD(N, Results, DAG);
13823   }
13824 }
13825
13826 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13827   switch (Opcode) {
13828   default: return NULL;
13829   case X86ISD::BSF:                return "X86ISD::BSF";
13830   case X86ISD::BSR:                return "X86ISD::BSR";
13831   case X86ISD::SHLD:               return "X86ISD::SHLD";
13832   case X86ISD::SHRD:               return "X86ISD::SHRD";
13833   case X86ISD::FAND:               return "X86ISD::FAND";
13834   case X86ISD::FANDN:              return "X86ISD::FANDN";
13835   case X86ISD::FOR:                return "X86ISD::FOR";
13836   case X86ISD::FXOR:               return "X86ISD::FXOR";
13837   case X86ISD::FSRL:               return "X86ISD::FSRL";
13838   case X86ISD::FILD:               return "X86ISD::FILD";
13839   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13840   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13841   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13842   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13843   case X86ISD::FLD:                return "X86ISD::FLD";
13844   case X86ISD::FST:                return "X86ISD::FST";
13845   case X86ISD::CALL:               return "X86ISD::CALL";
13846   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13847   case X86ISD::BT:                 return "X86ISD::BT";
13848   case X86ISD::CMP:                return "X86ISD::CMP";
13849   case X86ISD::COMI:               return "X86ISD::COMI";
13850   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13851   case X86ISD::CMPM:               return "X86ISD::CMPM";
13852   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
13853   case X86ISD::SETCC:              return "X86ISD::SETCC";
13854   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13855   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
13856   case X86ISD::CMOV:               return "X86ISD::CMOV";
13857   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13858   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13859   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13860   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13861   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13862   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13863   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13864   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13865   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13866   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13867   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13868   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13869   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13870   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13871   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13872   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13873   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13874   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13875   case X86ISD::HADD:               return "X86ISD::HADD";
13876   case X86ISD::HSUB:               return "X86ISD::HSUB";
13877   case X86ISD::FHADD:              return "X86ISD::FHADD";
13878   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13879   case X86ISD::UMAX:               return "X86ISD::UMAX";
13880   case X86ISD::UMIN:               return "X86ISD::UMIN";
13881   case X86ISD::SMAX:               return "X86ISD::SMAX";
13882   case X86ISD::SMIN:               return "X86ISD::SMIN";
13883   case X86ISD::FMAX:               return "X86ISD::FMAX";
13884   case X86ISD::FMIN:               return "X86ISD::FMIN";
13885   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13886   case X86ISD::FMINC:              return "X86ISD::FMINC";
13887   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13888   case X86ISD::FRCP:               return "X86ISD::FRCP";
13889   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13890   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13891   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13892   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13893   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13894   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13895   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13896   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13897   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13898   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13899   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13900   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13901   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13902   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13903   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13904   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13905   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13906   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13907   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13908   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13909   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13910   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13911   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
13912   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
13913   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
13914   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13915   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13916   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13917   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13918   case X86ISD::VSHL:               return "X86ISD::VSHL";
13919   case X86ISD::VSRL:               return "X86ISD::VSRL";
13920   case X86ISD::VSRA:               return "X86ISD::VSRA";
13921   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13922   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13923   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13924   case X86ISD::CMPP:               return "X86ISD::CMPP";
13925   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13926   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13927   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
13928   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
13929   case X86ISD::ADD:                return "X86ISD::ADD";
13930   case X86ISD::SUB:                return "X86ISD::SUB";
13931   case X86ISD::ADC:                return "X86ISD::ADC";
13932   case X86ISD::SBB:                return "X86ISD::SBB";
13933   case X86ISD::SMUL:               return "X86ISD::SMUL";
13934   case X86ISD::UMUL:               return "X86ISD::UMUL";
13935   case X86ISD::INC:                return "X86ISD::INC";
13936   case X86ISD::DEC:                return "X86ISD::DEC";
13937   case X86ISD::OR:                 return "X86ISD::OR";
13938   case X86ISD::XOR:                return "X86ISD::XOR";
13939   case X86ISD::AND:                return "X86ISD::AND";
13940   case X86ISD::BLSI:               return "X86ISD::BLSI";
13941   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13942   case X86ISD::BLSR:               return "X86ISD::BLSR";
13943   case X86ISD::BZHI:               return "X86ISD::BZHI";
13944   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
13945   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13946   case X86ISD::PTEST:              return "X86ISD::PTEST";
13947   case X86ISD::TESTP:              return "X86ISD::TESTP";
13948   case X86ISD::TESTM:              return "X86ISD::TESTM";
13949   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
13950   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13951   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13952   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13953   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13954   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13955   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13956   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13957   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13958   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13959   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13960   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13961   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13962   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13963   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13964   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13965   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13966   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13967   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13968   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
13969   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13970   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13971   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13972   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
13973   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13974   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13975   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13976   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13977   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13978   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13979   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13980   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13981   case X86ISD::SAHF:               return "X86ISD::SAHF";
13982   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13983   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13984   case X86ISD::FMADD:              return "X86ISD::FMADD";
13985   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13986   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13987   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13988   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13989   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13990   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13991   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13992   case X86ISD::XTEST:              return "X86ISD::XTEST";
13993   }
13994 }
13995
13996 // isLegalAddressingMode - Return true if the addressing mode represented
13997 // by AM is legal for this target, for a load/store of the specified type.
13998 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13999                                               Type *Ty) const {
14000   // X86 supports extremely general addressing modes.
14001   CodeModel::Model M = getTargetMachine().getCodeModel();
14002   Reloc::Model R = getTargetMachine().getRelocationModel();
14003
14004   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14005   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14006     return false;
14007
14008   if (AM.BaseGV) {
14009     unsigned GVFlags =
14010       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14011
14012     // If a reference to this global requires an extra load, we can't fold it.
14013     if (isGlobalStubReference(GVFlags))
14014       return false;
14015
14016     // If BaseGV requires a register for the PIC base, we cannot also have a
14017     // BaseReg specified.
14018     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14019       return false;
14020
14021     // If lower 4G is not available, then we must use rip-relative addressing.
14022     if ((M != CodeModel::Small || R != Reloc::Static) &&
14023         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14024       return false;
14025   }
14026
14027   switch (AM.Scale) {
14028   case 0:
14029   case 1:
14030   case 2:
14031   case 4:
14032   case 8:
14033     // These scales always work.
14034     break;
14035   case 3:
14036   case 5:
14037   case 9:
14038     // These scales are formed with basereg+scalereg.  Only accept if there is
14039     // no basereg yet.
14040     if (AM.HasBaseReg)
14041       return false;
14042     break;
14043   default:  // Other stuff never works.
14044     return false;
14045   }
14046
14047   return true;
14048 }
14049
14050 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14051   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14052     return false;
14053   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14054   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14055   return NumBits1 > NumBits2;
14056 }
14057
14058 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14059   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14060     return false;
14061
14062   if (!isTypeLegal(EVT::getEVT(Ty1)))
14063     return false;
14064
14065   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14066
14067   // Assuming the caller doesn't have a zeroext or signext return parameter,
14068   // truncation all the way down to i1 is valid.
14069   return true;
14070 }
14071
14072 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14073   return isInt<32>(Imm);
14074 }
14075
14076 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14077   // Can also use sub to handle negated immediates.
14078   return isInt<32>(Imm);
14079 }
14080
14081 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14082   if (!VT1.isInteger() || !VT2.isInteger())
14083     return false;
14084   unsigned NumBits1 = VT1.getSizeInBits();
14085   unsigned NumBits2 = VT2.getSizeInBits();
14086   return NumBits1 > NumBits2;
14087 }
14088
14089 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14090   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14091   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14092 }
14093
14094 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14095   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14096   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14097 }
14098
14099 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14100   EVT VT1 = Val.getValueType();
14101   if (isZExtFree(VT1, VT2))
14102     return true;
14103
14104   if (Val.getOpcode() != ISD::LOAD)
14105     return false;
14106
14107   if (!VT1.isSimple() || !VT1.isInteger() ||
14108       !VT2.isSimple() || !VT2.isInteger())
14109     return false;
14110
14111   switch (VT1.getSimpleVT().SimpleTy) {
14112   default: break;
14113   case MVT::i8:
14114   case MVT::i16:
14115   case MVT::i32:
14116     // X86 has 8, 16, and 32-bit zero-extending loads.
14117     return true;
14118   }
14119
14120   return false;
14121 }
14122
14123 bool
14124 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14125   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14126     return false;
14127
14128   VT = VT.getScalarType();
14129
14130   if (!VT.isSimple())
14131     return false;
14132
14133   switch (VT.getSimpleVT().SimpleTy) {
14134   case MVT::f32:
14135   case MVT::f64:
14136     return true;
14137   default:
14138     break;
14139   }
14140
14141   return false;
14142 }
14143
14144 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14145   // i16 instructions are longer (0x66 prefix) and potentially slower.
14146   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14147 }
14148
14149 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14150 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14151 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14152 /// are assumed to be legal.
14153 bool
14154 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14155                                       EVT VT) const {
14156   if (!VT.isSimple())
14157     return false;
14158
14159   MVT SVT = VT.getSimpleVT();
14160
14161   // Very little shuffling can be done for 64-bit vectors right now.
14162   if (VT.getSizeInBits() == 64)
14163     return false;
14164
14165   // FIXME: pshufb, blends, shifts.
14166   return (SVT.getVectorNumElements() == 2 ||
14167           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14168           isMOVLMask(M, SVT) ||
14169           isSHUFPMask(M, SVT) ||
14170           isPSHUFDMask(M, SVT) ||
14171           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14172           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14173           isPALIGNRMask(M, SVT, Subtarget) ||
14174           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14175           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14176           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14177           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14178 }
14179
14180 bool
14181 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14182                                           EVT VT) const {
14183   if (!VT.isSimple())
14184     return false;
14185
14186   MVT SVT = VT.getSimpleVT();
14187   unsigned NumElts = SVT.getVectorNumElements();
14188   // FIXME: This collection of masks seems suspect.
14189   if (NumElts == 2)
14190     return true;
14191   if (NumElts == 4 && SVT.is128BitVector()) {
14192     return (isMOVLMask(Mask, SVT)  ||
14193             isCommutedMOVLMask(Mask, SVT, true) ||
14194             isSHUFPMask(Mask, SVT) ||
14195             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14196   }
14197   return false;
14198 }
14199
14200 //===----------------------------------------------------------------------===//
14201 //                           X86 Scheduler Hooks
14202 //===----------------------------------------------------------------------===//
14203
14204 /// Utility function to emit xbegin specifying the start of an RTM region.
14205 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14206                                      const TargetInstrInfo *TII) {
14207   DebugLoc DL = MI->getDebugLoc();
14208
14209   const BasicBlock *BB = MBB->getBasicBlock();
14210   MachineFunction::iterator I = MBB;
14211   ++I;
14212
14213   // For the v = xbegin(), we generate
14214   //
14215   // thisMBB:
14216   //  xbegin sinkMBB
14217   //
14218   // mainMBB:
14219   //  eax = -1
14220   //
14221   // sinkMBB:
14222   //  v = eax
14223
14224   MachineBasicBlock *thisMBB = MBB;
14225   MachineFunction *MF = MBB->getParent();
14226   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14227   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14228   MF->insert(I, mainMBB);
14229   MF->insert(I, sinkMBB);
14230
14231   // Transfer the remainder of BB and its successor edges to sinkMBB.
14232   sinkMBB->splice(sinkMBB->begin(), MBB,
14233                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14234   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14235
14236   // thisMBB:
14237   //  xbegin sinkMBB
14238   //  # fallthrough to mainMBB
14239   //  # abortion to sinkMBB
14240   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14241   thisMBB->addSuccessor(mainMBB);
14242   thisMBB->addSuccessor(sinkMBB);
14243
14244   // mainMBB:
14245   //  EAX = -1
14246   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14247   mainMBB->addSuccessor(sinkMBB);
14248
14249   // sinkMBB:
14250   // EAX is live into the sinkMBB
14251   sinkMBB->addLiveIn(X86::EAX);
14252   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14253           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14254     .addReg(X86::EAX);
14255
14256   MI->eraseFromParent();
14257   return sinkMBB;
14258 }
14259
14260 // Get CMPXCHG opcode for the specified data type.
14261 static unsigned getCmpXChgOpcode(EVT VT) {
14262   switch (VT.getSimpleVT().SimpleTy) {
14263   case MVT::i8:  return X86::LCMPXCHG8;
14264   case MVT::i16: return X86::LCMPXCHG16;
14265   case MVT::i32: return X86::LCMPXCHG32;
14266   case MVT::i64: return X86::LCMPXCHG64;
14267   default:
14268     break;
14269   }
14270   llvm_unreachable("Invalid operand size!");
14271 }
14272
14273 // Get LOAD opcode for the specified data type.
14274 static unsigned getLoadOpcode(EVT VT) {
14275   switch (VT.getSimpleVT().SimpleTy) {
14276   case MVT::i8:  return X86::MOV8rm;
14277   case MVT::i16: return X86::MOV16rm;
14278   case MVT::i32: return X86::MOV32rm;
14279   case MVT::i64: return X86::MOV64rm;
14280   default:
14281     break;
14282   }
14283   llvm_unreachable("Invalid operand size!");
14284 }
14285
14286 // Get opcode of the non-atomic one from the specified atomic instruction.
14287 static unsigned getNonAtomicOpcode(unsigned Opc) {
14288   switch (Opc) {
14289   case X86::ATOMAND8:  return X86::AND8rr;
14290   case X86::ATOMAND16: return X86::AND16rr;
14291   case X86::ATOMAND32: return X86::AND32rr;
14292   case X86::ATOMAND64: return X86::AND64rr;
14293   case X86::ATOMOR8:   return X86::OR8rr;
14294   case X86::ATOMOR16:  return X86::OR16rr;
14295   case X86::ATOMOR32:  return X86::OR32rr;
14296   case X86::ATOMOR64:  return X86::OR64rr;
14297   case X86::ATOMXOR8:  return X86::XOR8rr;
14298   case X86::ATOMXOR16: return X86::XOR16rr;
14299   case X86::ATOMXOR32: return X86::XOR32rr;
14300   case X86::ATOMXOR64: return X86::XOR64rr;
14301   }
14302   llvm_unreachable("Unhandled atomic-load-op opcode!");
14303 }
14304
14305 // Get opcode of the non-atomic one from the specified atomic instruction with
14306 // extra opcode.
14307 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14308                                                unsigned &ExtraOpc) {
14309   switch (Opc) {
14310   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14311   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14312   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14313   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14314   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14315   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14316   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14317   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14318   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14319   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14320   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14321   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14322   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14323   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14324   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14325   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14326   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14327   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14328   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14329   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14330   }
14331   llvm_unreachable("Unhandled atomic-load-op opcode!");
14332 }
14333
14334 // Get opcode of the non-atomic one from the specified atomic instruction for
14335 // 64-bit data type on 32-bit target.
14336 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14337   switch (Opc) {
14338   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14339   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14340   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14341   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14342   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14343   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14344   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14345   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14346   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14347   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14348   }
14349   llvm_unreachable("Unhandled atomic-load-op opcode!");
14350 }
14351
14352 // Get opcode of the non-atomic one from the specified atomic instruction for
14353 // 64-bit data type on 32-bit target with extra opcode.
14354 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14355                                                    unsigned &HiOpc,
14356                                                    unsigned &ExtraOpc) {
14357   switch (Opc) {
14358   case X86::ATOMNAND6432:
14359     ExtraOpc = X86::NOT32r;
14360     HiOpc = X86::AND32rr;
14361     return X86::AND32rr;
14362   }
14363   llvm_unreachable("Unhandled atomic-load-op opcode!");
14364 }
14365
14366 // Get pseudo CMOV opcode from the specified data type.
14367 static unsigned getPseudoCMOVOpc(EVT VT) {
14368   switch (VT.getSimpleVT().SimpleTy) {
14369   case MVT::i8:  return X86::CMOV_GR8;
14370   case MVT::i16: return X86::CMOV_GR16;
14371   case MVT::i32: return X86::CMOV_GR32;
14372   default:
14373     break;
14374   }
14375   llvm_unreachable("Unknown CMOV opcode!");
14376 }
14377
14378 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14379 // They will be translated into a spin-loop or compare-exchange loop from
14380 //
14381 //    ...
14382 //    dst = atomic-fetch-op MI.addr, MI.val
14383 //    ...
14384 //
14385 // to
14386 //
14387 //    ...
14388 //    t1 = LOAD MI.addr
14389 // loop:
14390 //    t4 = phi(t1, t3 / loop)
14391 //    t2 = OP MI.val, t4
14392 //    EAX = t4
14393 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14394 //    t3 = EAX
14395 //    JNE loop
14396 // sink:
14397 //    dst = t3
14398 //    ...
14399 MachineBasicBlock *
14400 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14401                                        MachineBasicBlock *MBB) const {
14402   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14403   DebugLoc DL = MI->getDebugLoc();
14404
14405   MachineFunction *MF = MBB->getParent();
14406   MachineRegisterInfo &MRI = MF->getRegInfo();
14407
14408   const BasicBlock *BB = MBB->getBasicBlock();
14409   MachineFunction::iterator I = MBB;
14410   ++I;
14411
14412   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14413          "Unexpected number of operands");
14414
14415   assert(MI->hasOneMemOperand() &&
14416          "Expected atomic-load-op to have one memoperand");
14417
14418   // Memory Reference
14419   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14420   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14421
14422   unsigned DstReg, SrcReg;
14423   unsigned MemOpndSlot;
14424
14425   unsigned CurOp = 0;
14426
14427   DstReg = MI->getOperand(CurOp++).getReg();
14428   MemOpndSlot = CurOp;
14429   CurOp += X86::AddrNumOperands;
14430   SrcReg = MI->getOperand(CurOp++).getReg();
14431
14432   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14433   MVT::SimpleValueType VT = *RC->vt_begin();
14434   unsigned t1 = MRI.createVirtualRegister(RC);
14435   unsigned t2 = MRI.createVirtualRegister(RC);
14436   unsigned t3 = MRI.createVirtualRegister(RC);
14437   unsigned t4 = MRI.createVirtualRegister(RC);
14438   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14439
14440   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14441   unsigned LOADOpc = getLoadOpcode(VT);
14442
14443   // For the atomic load-arith operator, we generate
14444   //
14445   //  thisMBB:
14446   //    t1 = LOAD [MI.addr]
14447   //  mainMBB:
14448   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14449   //    t1 = OP MI.val, EAX
14450   //    EAX = t4
14451   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14452   //    t3 = EAX
14453   //    JNE mainMBB
14454   //  sinkMBB:
14455   //    dst = t3
14456
14457   MachineBasicBlock *thisMBB = MBB;
14458   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14459   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14460   MF->insert(I, mainMBB);
14461   MF->insert(I, sinkMBB);
14462
14463   MachineInstrBuilder MIB;
14464
14465   // Transfer the remainder of BB and its successor edges to sinkMBB.
14466   sinkMBB->splice(sinkMBB->begin(), MBB,
14467                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14468   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14469
14470   // thisMBB:
14471   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14472   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14473     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14474     if (NewMO.isReg())
14475       NewMO.setIsKill(false);
14476     MIB.addOperand(NewMO);
14477   }
14478   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14479     unsigned flags = (*MMOI)->getFlags();
14480     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14481     MachineMemOperand *MMO =
14482       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14483                                (*MMOI)->getSize(),
14484                                (*MMOI)->getBaseAlignment(),
14485                                (*MMOI)->getTBAAInfo(),
14486                                (*MMOI)->getRanges());
14487     MIB.addMemOperand(MMO);
14488   }
14489
14490   thisMBB->addSuccessor(mainMBB);
14491
14492   // mainMBB:
14493   MachineBasicBlock *origMainMBB = mainMBB;
14494
14495   // Add a PHI.
14496   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14497                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14498
14499   unsigned Opc = MI->getOpcode();
14500   switch (Opc) {
14501   default:
14502     llvm_unreachable("Unhandled atomic-load-op opcode!");
14503   case X86::ATOMAND8:
14504   case X86::ATOMAND16:
14505   case X86::ATOMAND32:
14506   case X86::ATOMAND64:
14507   case X86::ATOMOR8:
14508   case X86::ATOMOR16:
14509   case X86::ATOMOR32:
14510   case X86::ATOMOR64:
14511   case X86::ATOMXOR8:
14512   case X86::ATOMXOR16:
14513   case X86::ATOMXOR32:
14514   case X86::ATOMXOR64: {
14515     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14516     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14517       .addReg(t4);
14518     break;
14519   }
14520   case X86::ATOMNAND8:
14521   case X86::ATOMNAND16:
14522   case X86::ATOMNAND32:
14523   case X86::ATOMNAND64: {
14524     unsigned Tmp = MRI.createVirtualRegister(RC);
14525     unsigned NOTOpc;
14526     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14527     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14528       .addReg(t4);
14529     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14530     break;
14531   }
14532   case X86::ATOMMAX8:
14533   case X86::ATOMMAX16:
14534   case X86::ATOMMAX32:
14535   case X86::ATOMMAX64:
14536   case X86::ATOMMIN8:
14537   case X86::ATOMMIN16:
14538   case X86::ATOMMIN32:
14539   case X86::ATOMMIN64:
14540   case X86::ATOMUMAX8:
14541   case X86::ATOMUMAX16:
14542   case X86::ATOMUMAX32:
14543   case X86::ATOMUMAX64:
14544   case X86::ATOMUMIN8:
14545   case X86::ATOMUMIN16:
14546   case X86::ATOMUMIN32:
14547   case X86::ATOMUMIN64: {
14548     unsigned CMPOpc;
14549     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14550
14551     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14552       .addReg(SrcReg)
14553       .addReg(t4);
14554
14555     if (Subtarget->hasCMov()) {
14556       if (VT != MVT::i8) {
14557         // Native support
14558         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14559           .addReg(SrcReg)
14560           .addReg(t4);
14561       } else {
14562         // Promote i8 to i32 to use CMOV32
14563         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14564         const TargetRegisterClass *RC32 =
14565           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14566         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14567         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14568         unsigned Tmp = MRI.createVirtualRegister(RC32);
14569
14570         unsigned Undef = MRI.createVirtualRegister(RC32);
14571         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14572
14573         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14574           .addReg(Undef)
14575           .addReg(SrcReg)
14576           .addImm(X86::sub_8bit);
14577         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14578           .addReg(Undef)
14579           .addReg(t4)
14580           .addImm(X86::sub_8bit);
14581
14582         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14583           .addReg(SrcReg32)
14584           .addReg(AccReg32);
14585
14586         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14587           .addReg(Tmp, 0, X86::sub_8bit);
14588       }
14589     } else {
14590       // Use pseudo select and lower them.
14591       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14592              "Invalid atomic-load-op transformation!");
14593       unsigned SelOpc = getPseudoCMOVOpc(VT);
14594       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14595       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14596       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14597               .addReg(SrcReg).addReg(t4)
14598               .addImm(CC);
14599       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14600       // Replace the original PHI node as mainMBB is changed after CMOV
14601       // lowering.
14602       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14603         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14604       Phi->eraseFromParent();
14605     }
14606     break;
14607   }
14608   }
14609
14610   // Copy PhyReg back from virtual register.
14611   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14612     .addReg(t4);
14613
14614   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14615   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14616     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14617     if (NewMO.isReg())
14618       NewMO.setIsKill(false);
14619     MIB.addOperand(NewMO);
14620   }
14621   MIB.addReg(t2);
14622   MIB.setMemRefs(MMOBegin, MMOEnd);
14623
14624   // Copy PhyReg back to virtual register.
14625   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14626     .addReg(PhyReg);
14627
14628   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14629
14630   mainMBB->addSuccessor(origMainMBB);
14631   mainMBB->addSuccessor(sinkMBB);
14632
14633   // sinkMBB:
14634   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14635           TII->get(TargetOpcode::COPY), DstReg)
14636     .addReg(t3);
14637
14638   MI->eraseFromParent();
14639   return sinkMBB;
14640 }
14641
14642 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14643 // instructions. They will be translated into a spin-loop or compare-exchange
14644 // loop from
14645 //
14646 //    ...
14647 //    dst = atomic-fetch-op MI.addr, MI.val
14648 //    ...
14649 //
14650 // to
14651 //
14652 //    ...
14653 //    t1L = LOAD [MI.addr + 0]
14654 //    t1H = LOAD [MI.addr + 4]
14655 // loop:
14656 //    t4L = phi(t1L, t3L / loop)
14657 //    t4H = phi(t1H, t3H / loop)
14658 //    t2L = OP MI.val.lo, t4L
14659 //    t2H = OP MI.val.hi, t4H
14660 //    EAX = t4L
14661 //    EDX = t4H
14662 //    EBX = t2L
14663 //    ECX = t2H
14664 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14665 //    t3L = EAX
14666 //    t3H = EDX
14667 //    JNE loop
14668 // sink:
14669 //    dstL = t3L
14670 //    dstH = t3H
14671 //    ...
14672 MachineBasicBlock *
14673 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14674                                            MachineBasicBlock *MBB) const {
14675   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14676   DebugLoc DL = MI->getDebugLoc();
14677
14678   MachineFunction *MF = MBB->getParent();
14679   MachineRegisterInfo &MRI = MF->getRegInfo();
14680
14681   const BasicBlock *BB = MBB->getBasicBlock();
14682   MachineFunction::iterator I = MBB;
14683   ++I;
14684
14685   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14686          "Unexpected number of operands");
14687
14688   assert(MI->hasOneMemOperand() &&
14689          "Expected atomic-load-op32 to have one memoperand");
14690
14691   // Memory Reference
14692   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14693   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14694
14695   unsigned DstLoReg, DstHiReg;
14696   unsigned SrcLoReg, SrcHiReg;
14697   unsigned MemOpndSlot;
14698
14699   unsigned CurOp = 0;
14700
14701   DstLoReg = MI->getOperand(CurOp++).getReg();
14702   DstHiReg = MI->getOperand(CurOp++).getReg();
14703   MemOpndSlot = CurOp;
14704   CurOp += X86::AddrNumOperands;
14705   SrcLoReg = MI->getOperand(CurOp++).getReg();
14706   SrcHiReg = MI->getOperand(CurOp++).getReg();
14707
14708   const TargetRegisterClass *RC = &X86::GR32RegClass;
14709   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14710
14711   unsigned t1L = MRI.createVirtualRegister(RC);
14712   unsigned t1H = MRI.createVirtualRegister(RC);
14713   unsigned t2L = MRI.createVirtualRegister(RC);
14714   unsigned t2H = MRI.createVirtualRegister(RC);
14715   unsigned t3L = MRI.createVirtualRegister(RC);
14716   unsigned t3H = MRI.createVirtualRegister(RC);
14717   unsigned t4L = MRI.createVirtualRegister(RC);
14718   unsigned t4H = MRI.createVirtualRegister(RC);
14719
14720   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14721   unsigned LOADOpc = X86::MOV32rm;
14722
14723   // For the atomic load-arith operator, we generate
14724   //
14725   //  thisMBB:
14726   //    t1L = LOAD [MI.addr + 0]
14727   //    t1H = LOAD [MI.addr + 4]
14728   //  mainMBB:
14729   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14730   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14731   //    t2L = OP MI.val.lo, t4L
14732   //    t2H = OP MI.val.hi, t4H
14733   //    EBX = t2L
14734   //    ECX = t2H
14735   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14736   //    t3L = EAX
14737   //    t3H = EDX
14738   //    JNE loop
14739   //  sinkMBB:
14740   //    dstL = t3L
14741   //    dstH = t3H
14742
14743   MachineBasicBlock *thisMBB = MBB;
14744   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14745   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14746   MF->insert(I, mainMBB);
14747   MF->insert(I, sinkMBB);
14748
14749   MachineInstrBuilder MIB;
14750
14751   // Transfer the remainder of BB and its successor edges to sinkMBB.
14752   sinkMBB->splice(sinkMBB->begin(), MBB,
14753                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14754   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14755
14756   // thisMBB:
14757   // Lo
14758   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14759   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14760     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14761     if (NewMO.isReg())
14762       NewMO.setIsKill(false);
14763     MIB.addOperand(NewMO);
14764   }
14765   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14766     unsigned flags = (*MMOI)->getFlags();
14767     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14768     MachineMemOperand *MMO =
14769       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14770                                (*MMOI)->getSize(),
14771                                (*MMOI)->getBaseAlignment(),
14772                                (*MMOI)->getTBAAInfo(),
14773                                (*MMOI)->getRanges());
14774     MIB.addMemOperand(MMO);
14775   };
14776   MachineInstr *LowMI = MIB;
14777
14778   // Hi
14779   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14780   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14781     if (i == X86::AddrDisp) {
14782       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14783     } else {
14784       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14785       if (NewMO.isReg())
14786         NewMO.setIsKill(false);
14787       MIB.addOperand(NewMO);
14788     }
14789   }
14790   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14791
14792   thisMBB->addSuccessor(mainMBB);
14793
14794   // mainMBB:
14795   MachineBasicBlock *origMainMBB = mainMBB;
14796
14797   // Add PHIs.
14798   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14799                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14800   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14801                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14802
14803   unsigned Opc = MI->getOpcode();
14804   switch (Opc) {
14805   default:
14806     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14807   case X86::ATOMAND6432:
14808   case X86::ATOMOR6432:
14809   case X86::ATOMXOR6432:
14810   case X86::ATOMADD6432:
14811   case X86::ATOMSUB6432: {
14812     unsigned HiOpc;
14813     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14814     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14815       .addReg(SrcLoReg);
14816     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14817       .addReg(SrcHiReg);
14818     break;
14819   }
14820   case X86::ATOMNAND6432: {
14821     unsigned HiOpc, NOTOpc;
14822     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14823     unsigned TmpL = MRI.createVirtualRegister(RC);
14824     unsigned TmpH = MRI.createVirtualRegister(RC);
14825     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14826       .addReg(t4L);
14827     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14828       .addReg(t4H);
14829     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14830     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14831     break;
14832   }
14833   case X86::ATOMMAX6432:
14834   case X86::ATOMMIN6432:
14835   case X86::ATOMUMAX6432:
14836   case X86::ATOMUMIN6432: {
14837     unsigned HiOpc;
14838     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14839     unsigned cL = MRI.createVirtualRegister(RC8);
14840     unsigned cH = MRI.createVirtualRegister(RC8);
14841     unsigned cL32 = MRI.createVirtualRegister(RC);
14842     unsigned cH32 = MRI.createVirtualRegister(RC);
14843     unsigned cc = MRI.createVirtualRegister(RC);
14844     // cl := cmp src_lo, lo
14845     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14846       .addReg(SrcLoReg).addReg(t4L);
14847     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14848     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14849     // ch := cmp src_hi, hi
14850     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14851       .addReg(SrcHiReg).addReg(t4H);
14852     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14853     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14854     // cc := if (src_hi == hi) ? cl : ch;
14855     if (Subtarget->hasCMov()) {
14856       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14857         .addReg(cH32).addReg(cL32);
14858     } else {
14859       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14860               .addReg(cH32).addReg(cL32)
14861               .addImm(X86::COND_E);
14862       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14863     }
14864     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14865     if (Subtarget->hasCMov()) {
14866       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14867         .addReg(SrcLoReg).addReg(t4L);
14868       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14869         .addReg(SrcHiReg).addReg(t4H);
14870     } else {
14871       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14872               .addReg(SrcLoReg).addReg(t4L)
14873               .addImm(X86::COND_NE);
14874       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14875       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14876       // 2nd CMOV lowering.
14877       mainMBB->addLiveIn(X86::EFLAGS);
14878       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14879               .addReg(SrcHiReg).addReg(t4H)
14880               .addImm(X86::COND_NE);
14881       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14882       // Replace the original PHI node as mainMBB is changed after CMOV
14883       // lowering.
14884       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14885         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14886       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14887         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14888       PhiL->eraseFromParent();
14889       PhiH->eraseFromParent();
14890     }
14891     break;
14892   }
14893   case X86::ATOMSWAP6432: {
14894     unsigned HiOpc;
14895     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14896     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14897     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14898     break;
14899   }
14900   }
14901
14902   // Copy EDX:EAX back from HiReg:LoReg
14903   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14904   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14905   // Copy ECX:EBX from t1H:t1L
14906   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14907   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14908
14909   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14910   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14911     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14912     if (NewMO.isReg())
14913       NewMO.setIsKill(false);
14914     MIB.addOperand(NewMO);
14915   }
14916   MIB.setMemRefs(MMOBegin, MMOEnd);
14917
14918   // Copy EDX:EAX back to t3H:t3L
14919   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14920   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14921
14922   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14923
14924   mainMBB->addSuccessor(origMainMBB);
14925   mainMBB->addSuccessor(sinkMBB);
14926
14927   // sinkMBB:
14928   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14929           TII->get(TargetOpcode::COPY), DstLoReg)
14930     .addReg(t3L);
14931   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14932           TII->get(TargetOpcode::COPY), DstHiReg)
14933     .addReg(t3H);
14934
14935   MI->eraseFromParent();
14936   return sinkMBB;
14937 }
14938
14939 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14940 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14941 // in the .td file.
14942 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14943                                        const TargetInstrInfo *TII) {
14944   unsigned Opc;
14945   switch (MI->getOpcode()) {
14946   default: llvm_unreachable("illegal opcode!");
14947   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14948   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14949   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14950   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14951   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14952   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14953   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14954   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14955   }
14956
14957   DebugLoc dl = MI->getDebugLoc();
14958   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14959
14960   unsigned NumArgs = MI->getNumOperands();
14961   for (unsigned i = 1; i < NumArgs; ++i) {
14962     MachineOperand &Op = MI->getOperand(i);
14963     if (!(Op.isReg() && Op.isImplicit()))
14964       MIB.addOperand(Op);
14965   }
14966   if (MI->hasOneMemOperand())
14967     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14968
14969   BuildMI(*BB, MI, dl,
14970     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14971     .addReg(X86::XMM0);
14972
14973   MI->eraseFromParent();
14974   return BB;
14975 }
14976
14977 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14978 // defs in an instruction pattern
14979 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14980                                        const TargetInstrInfo *TII) {
14981   unsigned Opc;
14982   switch (MI->getOpcode()) {
14983   default: llvm_unreachable("illegal opcode!");
14984   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14985   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14986   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14987   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14988   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14989   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14990   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14991   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14992   }
14993
14994   DebugLoc dl = MI->getDebugLoc();
14995   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14996
14997   unsigned NumArgs = MI->getNumOperands(); // remove the results
14998   for (unsigned i = 1; i < NumArgs; ++i) {
14999     MachineOperand &Op = MI->getOperand(i);
15000     if (!(Op.isReg() && Op.isImplicit()))
15001       MIB.addOperand(Op);
15002   }
15003   if (MI->hasOneMemOperand())
15004     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15005
15006   BuildMI(*BB, MI, dl,
15007     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15008     .addReg(X86::ECX);
15009
15010   MI->eraseFromParent();
15011   return BB;
15012 }
15013
15014 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15015                                        const TargetInstrInfo *TII,
15016                                        const X86Subtarget* Subtarget) {
15017   DebugLoc dl = MI->getDebugLoc();
15018
15019   // Address into RAX/EAX, other two args into ECX, EDX.
15020   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15021   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15022   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15023   for (int i = 0; i < X86::AddrNumOperands; ++i)
15024     MIB.addOperand(MI->getOperand(i));
15025
15026   unsigned ValOps = X86::AddrNumOperands;
15027   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15028     .addReg(MI->getOperand(ValOps).getReg());
15029   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15030     .addReg(MI->getOperand(ValOps+1).getReg());
15031
15032   // The instruction doesn't actually take any operands though.
15033   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15034
15035   MI->eraseFromParent(); // The pseudo is gone now.
15036   return BB;
15037 }
15038
15039 MachineBasicBlock *
15040 X86TargetLowering::EmitVAARG64WithCustomInserter(
15041                    MachineInstr *MI,
15042                    MachineBasicBlock *MBB) const {
15043   // Emit va_arg instruction on X86-64.
15044
15045   // Operands to this pseudo-instruction:
15046   // 0  ) Output        : destination address (reg)
15047   // 1-5) Input         : va_list address (addr, i64mem)
15048   // 6  ) ArgSize       : Size (in bytes) of vararg type
15049   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15050   // 8  ) Align         : Alignment of type
15051   // 9  ) EFLAGS (implicit-def)
15052
15053   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15054   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15055
15056   unsigned DestReg = MI->getOperand(0).getReg();
15057   MachineOperand &Base = MI->getOperand(1);
15058   MachineOperand &Scale = MI->getOperand(2);
15059   MachineOperand &Index = MI->getOperand(3);
15060   MachineOperand &Disp = MI->getOperand(4);
15061   MachineOperand &Segment = MI->getOperand(5);
15062   unsigned ArgSize = MI->getOperand(6).getImm();
15063   unsigned ArgMode = MI->getOperand(7).getImm();
15064   unsigned Align = MI->getOperand(8).getImm();
15065
15066   // Memory Reference
15067   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15068   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15069   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15070
15071   // Machine Information
15072   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15073   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15074   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15075   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15076   DebugLoc DL = MI->getDebugLoc();
15077
15078   // struct va_list {
15079   //   i32   gp_offset
15080   //   i32   fp_offset
15081   //   i64   overflow_area (address)
15082   //   i64   reg_save_area (address)
15083   // }
15084   // sizeof(va_list) = 24
15085   // alignment(va_list) = 8
15086
15087   unsigned TotalNumIntRegs = 6;
15088   unsigned TotalNumXMMRegs = 8;
15089   bool UseGPOffset = (ArgMode == 1);
15090   bool UseFPOffset = (ArgMode == 2);
15091   unsigned MaxOffset = TotalNumIntRegs * 8 +
15092                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15093
15094   /* Align ArgSize to a multiple of 8 */
15095   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15096   bool NeedsAlign = (Align > 8);
15097
15098   MachineBasicBlock *thisMBB = MBB;
15099   MachineBasicBlock *overflowMBB;
15100   MachineBasicBlock *offsetMBB;
15101   MachineBasicBlock *endMBB;
15102
15103   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15104   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15105   unsigned OffsetReg = 0;
15106
15107   if (!UseGPOffset && !UseFPOffset) {
15108     // If we only pull from the overflow region, we don't create a branch.
15109     // We don't need to alter control flow.
15110     OffsetDestReg = 0; // unused
15111     OverflowDestReg = DestReg;
15112
15113     offsetMBB = NULL;
15114     overflowMBB = thisMBB;
15115     endMBB = thisMBB;
15116   } else {
15117     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15118     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15119     // If not, pull from overflow_area. (branch to overflowMBB)
15120     //
15121     //       thisMBB
15122     //         |     .
15123     //         |        .
15124     //     offsetMBB   overflowMBB
15125     //         |        .
15126     //         |     .
15127     //        endMBB
15128
15129     // Registers for the PHI in endMBB
15130     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15131     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15132
15133     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15134     MachineFunction *MF = MBB->getParent();
15135     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15136     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15137     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15138
15139     MachineFunction::iterator MBBIter = MBB;
15140     ++MBBIter;
15141
15142     // Insert the new basic blocks
15143     MF->insert(MBBIter, offsetMBB);
15144     MF->insert(MBBIter, overflowMBB);
15145     MF->insert(MBBIter, endMBB);
15146
15147     // Transfer the remainder of MBB and its successor edges to endMBB.
15148     endMBB->splice(endMBB->begin(), thisMBB,
15149                     llvm::next(MachineBasicBlock::iterator(MI)),
15150                     thisMBB->end());
15151     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15152
15153     // Make offsetMBB and overflowMBB successors of thisMBB
15154     thisMBB->addSuccessor(offsetMBB);
15155     thisMBB->addSuccessor(overflowMBB);
15156
15157     // endMBB is a successor of both offsetMBB and overflowMBB
15158     offsetMBB->addSuccessor(endMBB);
15159     overflowMBB->addSuccessor(endMBB);
15160
15161     // Load the offset value into a register
15162     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15163     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15164       .addOperand(Base)
15165       .addOperand(Scale)
15166       .addOperand(Index)
15167       .addDisp(Disp, UseFPOffset ? 4 : 0)
15168       .addOperand(Segment)
15169       .setMemRefs(MMOBegin, MMOEnd);
15170
15171     // Check if there is enough room left to pull this argument.
15172     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15173       .addReg(OffsetReg)
15174       .addImm(MaxOffset + 8 - ArgSizeA8);
15175
15176     // Branch to "overflowMBB" if offset >= max
15177     // Fall through to "offsetMBB" otherwise
15178     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15179       .addMBB(overflowMBB);
15180   }
15181
15182   // In offsetMBB, emit code to use the reg_save_area.
15183   if (offsetMBB) {
15184     assert(OffsetReg != 0);
15185
15186     // Read the reg_save_area address.
15187     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15188     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15189       .addOperand(Base)
15190       .addOperand(Scale)
15191       .addOperand(Index)
15192       .addDisp(Disp, 16)
15193       .addOperand(Segment)
15194       .setMemRefs(MMOBegin, MMOEnd);
15195
15196     // Zero-extend the offset
15197     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15198       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15199         .addImm(0)
15200         .addReg(OffsetReg)
15201         .addImm(X86::sub_32bit);
15202
15203     // Add the offset to the reg_save_area to get the final address.
15204     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15205       .addReg(OffsetReg64)
15206       .addReg(RegSaveReg);
15207
15208     // Compute the offset for the next argument
15209     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15210     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15211       .addReg(OffsetReg)
15212       .addImm(UseFPOffset ? 16 : 8);
15213
15214     // Store it back into the va_list.
15215     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15216       .addOperand(Base)
15217       .addOperand(Scale)
15218       .addOperand(Index)
15219       .addDisp(Disp, UseFPOffset ? 4 : 0)
15220       .addOperand(Segment)
15221       .addReg(NextOffsetReg)
15222       .setMemRefs(MMOBegin, MMOEnd);
15223
15224     // Jump to endMBB
15225     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15226       .addMBB(endMBB);
15227   }
15228
15229   //
15230   // Emit code to use overflow area
15231   //
15232
15233   // Load the overflow_area address into a register.
15234   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15235   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15236     .addOperand(Base)
15237     .addOperand(Scale)
15238     .addOperand(Index)
15239     .addDisp(Disp, 8)
15240     .addOperand(Segment)
15241     .setMemRefs(MMOBegin, MMOEnd);
15242
15243   // If we need to align it, do so. Otherwise, just copy the address
15244   // to OverflowDestReg.
15245   if (NeedsAlign) {
15246     // Align the overflow address
15247     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15248     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15249
15250     // aligned_addr = (addr + (align-1)) & ~(align-1)
15251     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15252       .addReg(OverflowAddrReg)
15253       .addImm(Align-1);
15254
15255     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15256       .addReg(TmpReg)
15257       .addImm(~(uint64_t)(Align-1));
15258   } else {
15259     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15260       .addReg(OverflowAddrReg);
15261   }
15262
15263   // Compute the next overflow address after this argument.
15264   // (the overflow address should be kept 8-byte aligned)
15265   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15266   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15267     .addReg(OverflowDestReg)
15268     .addImm(ArgSizeA8);
15269
15270   // Store the new overflow address.
15271   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15272     .addOperand(Base)
15273     .addOperand(Scale)
15274     .addOperand(Index)
15275     .addDisp(Disp, 8)
15276     .addOperand(Segment)
15277     .addReg(NextAddrReg)
15278     .setMemRefs(MMOBegin, MMOEnd);
15279
15280   // If we branched, emit the PHI to the front of endMBB.
15281   if (offsetMBB) {
15282     BuildMI(*endMBB, endMBB->begin(), DL,
15283             TII->get(X86::PHI), DestReg)
15284       .addReg(OffsetDestReg).addMBB(offsetMBB)
15285       .addReg(OverflowDestReg).addMBB(overflowMBB);
15286   }
15287
15288   // Erase the pseudo instruction
15289   MI->eraseFromParent();
15290
15291   return endMBB;
15292 }
15293
15294 MachineBasicBlock *
15295 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15296                                                  MachineInstr *MI,
15297                                                  MachineBasicBlock *MBB) const {
15298   // Emit code to save XMM registers to the stack. The ABI says that the
15299   // number of registers to save is given in %al, so it's theoretically
15300   // possible to do an indirect jump trick to avoid saving all of them,
15301   // however this code takes a simpler approach and just executes all
15302   // of the stores if %al is non-zero. It's less code, and it's probably
15303   // easier on the hardware branch predictor, and stores aren't all that
15304   // expensive anyway.
15305
15306   // Create the new basic blocks. One block contains all the XMM stores,
15307   // and one block is the final destination regardless of whether any
15308   // stores were performed.
15309   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15310   MachineFunction *F = MBB->getParent();
15311   MachineFunction::iterator MBBIter = MBB;
15312   ++MBBIter;
15313   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15314   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15315   F->insert(MBBIter, XMMSaveMBB);
15316   F->insert(MBBIter, EndMBB);
15317
15318   // Transfer the remainder of MBB and its successor edges to EndMBB.
15319   EndMBB->splice(EndMBB->begin(), MBB,
15320                  llvm::next(MachineBasicBlock::iterator(MI)),
15321                  MBB->end());
15322   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15323
15324   // The original block will now fall through to the XMM save block.
15325   MBB->addSuccessor(XMMSaveMBB);
15326   // The XMMSaveMBB will fall through to the end block.
15327   XMMSaveMBB->addSuccessor(EndMBB);
15328
15329   // Now add the instructions.
15330   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15331   DebugLoc DL = MI->getDebugLoc();
15332
15333   unsigned CountReg = MI->getOperand(0).getReg();
15334   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15335   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15336
15337   if (!Subtarget->isTargetWin64()) {
15338     // If %al is 0, branch around the XMM save block.
15339     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15340     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15341     MBB->addSuccessor(EndMBB);
15342   }
15343
15344   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15345   // that was just emitted, but clearly shouldn't be "saved".
15346   assert((MI->getNumOperands() <= 3 ||
15347           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15348           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15349          && "Expected last argument to be EFLAGS");
15350   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15351   // In the XMM save block, save all the XMM argument registers.
15352   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15353     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15354     MachineMemOperand *MMO =
15355       F->getMachineMemOperand(
15356           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15357         MachineMemOperand::MOStore,
15358         /*Size=*/16, /*Align=*/16);
15359     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15360       .addFrameIndex(RegSaveFrameIndex)
15361       .addImm(/*Scale=*/1)
15362       .addReg(/*IndexReg=*/0)
15363       .addImm(/*Disp=*/Offset)
15364       .addReg(/*Segment=*/0)
15365       .addReg(MI->getOperand(i).getReg())
15366       .addMemOperand(MMO);
15367   }
15368
15369   MI->eraseFromParent();   // The pseudo instruction is gone now.
15370
15371   return EndMBB;
15372 }
15373
15374 // The EFLAGS operand of SelectItr might be missing a kill marker
15375 // because there were multiple uses of EFLAGS, and ISel didn't know
15376 // which to mark. Figure out whether SelectItr should have had a
15377 // kill marker, and set it if it should. Returns the correct kill
15378 // marker value.
15379 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15380                                      MachineBasicBlock* BB,
15381                                      const TargetRegisterInfo* TRI) {
15382   // Scan forward through BB for a use/def of EFLAGS.
15383   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
15384   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15385     const MachineInstr& mi = *miI;
15386     if (mi.readsRegister(X86::EFLAGS))
15387       return false;
15388     if (mi.definesRegister(X86::EFLAGS))
15389       break; // Should have kill-flag - update below.
15390   }
15391
15392   // If we hit the end of the block, check whether EFLAGS is live into a
15393   // successor.
15394   if (miI == BB->end()) {
15395     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15396                                           sEnd = BB->succ_end();
15397          sItr != sEnd; ++sItr) {
15398       MachineBasicBlock* succ = *sItr;
15399       if (succ->isLiveIn(X86::EFLAGS))
15400         return false;
15401     }
15402   }
15403
15404   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15405   // out. SelectMI should have a kill flag on EFLAGS.
15406   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15407   return true;
15408 }
15409
15410 MachineBasicBlock *
15411 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15412                                      MachineBasicBlock *BB) const {
15413   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15414   DebugLoc DL = MI->getDebugLoc();
15415
15416   // To "insert" a SELECT_CC instruction, we actually have to insert the
15417   // diamond control-flow pattern.  The incoming instruction knows the
15418   // destination vreg to set, the condition code register to branch on, the
15419   // true/false values to select between, and a branch opcode to use.
15420   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15421   MachineFunction::iterator It = BB;
15422   ++It;
15423
15424   //  thisMBB:
15425   //  ...
15426   //   TrueVal = ...
15427   //   cmpTY ccX, r1, r2
15428   //   bCC copy1MBB
15429   //   fallthrough --> copy0MBB
15430   MachineBasicBlock *thisMBB = BB;
15431   MachineFunction *F = BB->getParent();
15432   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15433   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15434   F->insert(It, copy0MBB);
15435   F->insert(It, sinkMBB);
15436
15437   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15438   // live into the sink and copy blocks.
15439   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15440   if (!MI->killsRegister(X86::EFLAGS) &&
15441       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15442     copy0MBB->addLiveIn(X86::EFLAGS);
15443     sinkMBB->addLiveIn(X86::EFLAGS);
15444   }
15445
15446   // Transfer the remainder of BB and its successor edges to sinkMBB.
15447   sinkMBB->splice(sinkMBB->begin(), BB,
15448                   llvm::next(MachineBasicBlock::iterator(MI)),
15449                   BB->end());
15450   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15451
15452   // Add the true and fallthrough blocks as its successors.
15453   BB->addSuccessor(copy0MBB);
15454   BB->addSuccessor(sinkMBB);
15455
15456   // Create the conditional branch instruction.
15457   unsigned Opc =
15458     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15459   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15460
15461   //  copy0MBB:
15462   //   %FalseValue = ...
15463   //   # fallthrough to sinkMBB
15464   copy0MBB->addSuccessor(sinkMBB);
15465
15466   //  sinkMBB:
15467   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15468   //  ...
15469   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15470           TII->get(X86::PHI), MI->getOperand(0).getReg())
15471     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15472     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15473
15474   MI->eraseFromParent();   // The pseudo instruction is gone now.
15475   return sinkMBB;
15476 }
15477
15478 MachineBasicBlock *
15479 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15480                                         bool Is64Bit) const {
15481   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15482   DebugLoc DL = MI->getDebugLoc();
15483   MachineFunction *MF = BB->getParent();
15484   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15485
15486   assert(getTargetMachine().Options.EnableSegmentedStacks);
15487
15488   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15489   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15490
15491   // BB:
15492   //  ... [Till the alloca]
15493   // If stacklet is not large enough, jump to mallocMBB
15494   //
15495   // bumpMBB:
15496   //  Allocate by subtracting from RSP
15497   //  Jump to continueMBB
15498   //
15499   // mallocMBB:
15500   //  Allocate by call to runtime
15501   //
15502   // continueMBB:
15503   //  ...
15504   //  [rest of original BB]
15505   //
15506
15507   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15508   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15509   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15510
15511   MachineRegisterInfo &MRI = MF->getRegInfo();
15512   const TargetRegisterClass *AddrRegClass =
15513     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15514
15515   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15516     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15517     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15518     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15519     sizeVReg = MI->getOperand(1).getReg(),
15520     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15521
15522   MachineFunction::iterator MBBIter = BB;
15523   ++MBBIter;
15524
15525   MF->insert(MBBIter, bumpMBB);
15526   MF->insert(MBBIter, mallocMBB);
15527   MF->insert(MBBIter, continueMBB);
15528
15529   continueMBB->splice(continueMBB->begin(), BB, llvm::next
15530                       (MachineBasicBlock::iterator(MI)), BB->end());
15531   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15532
15533   // Add code to the main basic block to check if the stack limit has been hit,
15534   // and if so, jump to mallocMBB otherwise to bumpMBB.
15535   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15536   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15537     .addReg(tmpSPVReg).addReg(sizeVReg);
15538   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15539     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15540     .addReg(SPLimitVReg);
15541   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15542
15543   // bumpMBB simply decreases the stack pointer, since we know the current
15544   // stacklet has enough space.
15545   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15546     .addReg(SPLimitVReg);
15547   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15548     .addReg(SPLimitVReg);
15549   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15550
15551   // Calls into a routine in libgcc to allocate more space from the heap.
15552   const uint32_t *RegMask =
15553     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15554   if (Is64Bit) {
15555     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15556       .addReg(sizeVReg);
15557     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15558       .addExternalSymbol("__morestack_allocate_stack_space")
15559       .addRegMask(RegMask)
15560       .addReg(X86::RDI, RegState::Implicit)
15561       .addReg(X86::RAX, RegState::ImplicitDefine);
15562   } else {
15563     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15564       .addImm(12);
15565     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15566     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15567       .addExternalSymbol("__morestack_allocate_stack_space")
15568       .addRegMask(RegMask)
15569       .addReg(X86::EAX, RegState::ImplicitDefine);
15570   }
15571
15572   if (!Is64Bit)
15573     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15574       .addImm(16);
15575
15576   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15577     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15578   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15579
15580   // Set up the CFG correctly.
15581   BB->addSuccessor(bumpMBB);
15582   BB->addSuccessor(mallocMBB);
15583   mallocMBB->addSuccessor(continueMBB);
15584   bumpMBB->addSuccessor(continueMBB);
15585
15586   // Take care of the PHI nodes.
15587   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15588           MI->getOperand(0).getReg())
15589     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15590     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15591
15592   // Delete the original pseudo instruction.
15593   MI->eraseFromParent();
15594
15595   // And we're done.
15596   return continueMBB;
15597 }
15598
15599 MachineBasicBlock *
15600 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15601                                           MachineBasicBlock *BB) const {
15602   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15603   DebugLoc DL = MI->getDebugLoc();
15604
15605   assert(!Subtarget->isTargetMacho());
15606
15607   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15608   // non-trivial part is impdef of ESP.
15609
15610   if (Subtarget->isTargetWin64()) {
15611     if (Subtarget->isTargetCygMing()) {
15612       // ___chkstk(Mingw64):
15613       // Clobbers R10, R11, RAX and EFLAGS.
15614       // Updates RSP.
15615       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15616         .addExternalSymbol("___chkstk")
15617         .addReg(X86::RAX, RegState::Implicit)
15618         .addReg(X86::RSP, RegState::Implicit)
15619         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15620         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15621         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15622     } else {
15623       // __chkstk(MSVCRT): does not update stack pointer.
15624       // Clobbers R10, R11 and EFLAGS.
15625       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15626         .addExternalSymbol("__chkstk")
15627         .addReg(X86::RAX, RegState::Implicit)
15628         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15629       // RAX has the offset to be subtracted from RSP.
15630       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15631         .addReg(X86::RSP)
15632         .addReg(X86::RAX);
15633     }
15634   } else {
15635     const char *StackProbeSymbol =
15636       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15637
15638     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15639       .addExternalSymbol(StackProbeSymbol)
15640       .addReg(X86::EAX, RegState::Implicit)
15641       .addReg(X86::ESP, RegState::Implicit)
15642       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15643       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15644       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15645   }
15646
15647   MI->eraseFromParent();   // The pseudo instruction is gone now.
15648   return BB;
15649 }
15650
15651 MachineBasicBlock *
15652 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15653                                       MachineBasicBlock *BB) const {
15654   // This is pretty easy.  We're taking the value that we received from
15655   // our load from the relocation, sticking it in either RDI (x86-64)
15656   // or EAX and doing an indirect call.  The return value will then
15657   // be in the normal return register.
15658   const X86InstrInfo *TII
15659     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15660   DebugLoc DL = MI->getDebugLoc();
15661   MachineFunction *F = BB->getParent();
15662
15663   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15664   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15665
15666   // Get a register mask for the lowered call.
15667   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15668   // proper register mask.
15669   const uint32_t *RegMask =
15670     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15671   if (Subtarget->is64Bit()) {
15672     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15673                                       TII->get(X86::MOV64rm), X86::RDI)
15674     .addReg(X86::RIP)
15675     .addImm(0).addReg(0)
15676     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15677                       MI->getOperand(3).getTargetFlags())
15678     .addReg(0);
15679     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15680     addDirectMem(MIB, X86::RDI);
15681     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15682   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15683     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15684                                       TII->get(X86::MOV32rm), X86::EAX)
15685     .addReg(0)
15686     .addImm(0).addReg(0)
15687     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15688                       MI->getOperand(3).getTargetFlags())
15689     .addReg(0);
15690     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15691     addDirectMem(MIB, X86::EAX);
15692     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15693   } else {
15694     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15695                                       TII->get(X86::MOV32rm), X86::EAX)
15696     .addReg(TII->getGlobalBaseReg(F))
15697     .addImm(0).addReg(0)
15698     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15699                       MI->getOperand(3).getTargetFlags())
15700     .addReg(0);
15701     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15702     addDirectMem(MIB, X86::EAX);
15703     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15704   }
15705
15706   MI->eraseFromParent(); // The pseudo instruction is gone now.
15707   return BB;
15708 }
15709
15710 MachineBasicBlock *
15711 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15712                                     MachineBasicBlock *MBB) const {
15713   DebugLoc DL = MI->getDebugLoc();
15714   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15715
15716   MachineFunction *MF = MBB->getParent();
15717   MachineRegisterInfo &MRI = MF->getRegInfo();
15718
15719   const BasicBlock *BB = MBB->getBasicBlock();
15720   MachineFunction::iterator I = MBB;
15721   ++I;
15722
15723   // Memory Reference
15724   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15725   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15726
15727   unsigned DstReg;
15728   unsigned MemOpndSlot = 0;
15729
15730   unsigned CurOp = 0;
15731
15732   DstReg = MI->getOperand(CurOp++).getReg();
15733   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15734   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15735   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15736   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15737
15738   MemOpndSlot = CurOp;
15739
15740   MVT PVT = getPointerTy();
15741   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15742          "Invalid Pointer Size!");
15743
15744   // For v = setjmp(buf), we generate
15745   //
15746   // thisMBB:
15747   //  buf[LabelOffset] = restoreMBB
15748   //  SjLjSetup restoreMBB
15749   //
15750   // mainMBB:
15751   //  v_main = 0
15752   //
15753   // sinkMBB:
15754   //  v = phi(main, restore)
15755   //
15756   // restoreMBB:
15757   //  v_restore = 1
15758
15759   MachineBasicBlock *thisMBB = MBB;
15760   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15761   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15762   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15763   MF->insert(I, mainMBB);
15764   MF->insert(I, sinkMBB);
15765   MF->push_back(restoreMBB);
15766
15767   MachineInstrBuilder MIB;
15768
15769   // Transfer the remainder of BB and its successor edges to sinkMBB.
15770   sinkMBB->splice(sinkMBB->begin(), MBB,
15771                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15772   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15773
15774   // thisMBB:
15775   unsigned PtrStoreOpc = 0;
15776   unsigned LabelReg = 0;
15777   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15778   Reloc::Model RM = getTargetMachine().getRelocationModel();
15779   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15780                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15781
15782   // Prepare IP either in reg or imm.
15783   if (!UseImmLabel) {
15784     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15785     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15786     LabelReg = MRI.createVirtualRegister(PtrRC);
15787     if (Subtarget->is64Bit()) {
15788       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15789               .addReg(X86::RIP)
15790               .addImm(0)
15791               .addReg(0)
15792               .addMBB(restoreMBB)
15793               .addReg(0);
15794     } else {
15795       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15796       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15797               .addReg(XII->getGlobalBaseReg(MF))
15798               .addImm(0)
15799               .addReg(0)
15800               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15801               .addReg(0);
15802     }
15803   } else
15804     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15805   // Store IP
15806   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15807   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15808     if (i == X86::AddrDisp)
15809       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15810     else
15811       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15812   }
15813   if (!UseImmLabel)
15814     MIB.addReg(LabelReg);
15815   else
15816     MIB.addMBB(restoreMBB);
15817   MIB.setMemRefs(MMOBegin, MMOEnd);
15818   // Setup
15819   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15820           .addMBB(restoreMBB);
15821
15822   const X86RegisterInfo *RegInfo =
15823     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15824   MIB.addRegMask(RegInfo->getNoPreservedMask());
15825   thisMBB->addSuccessor(mainMBB);
15826   thisMBB->addSuccessor(restoreMBB);
15827
15828   // mainMBB:
15829   //  EAX = 0
15830   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15831   mainMBB->addSuccessor(sinkMBB);
15832
15833   // sinkMBB:
15834   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15835           TII->get(X86::PHI), DstReg)
15836     .addReg(mainDstReg).addMBB(mainMBB)
15837     .addReg(restoreDstReg).addMBB(restoreMBB);
15838
15839   // restoreMBB:
15840   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15841   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15842   restoreMBB->addSuccessor(sinkMBB);
15843
15844   MI->eraseFromParent();
15845   return sinkMBB;
15846 }
15847
15848 MachineBasicBlock *
15849 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15850                                      MachineBasicBlock *MBB) const {
15851   DebugLoc DL = MI->getDebugLoc();
15852   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15853
15854   MachineFunction *MF = MBB->getParent();
15855   MachineRegisterInfo &MRI = MF->getRegInfo();
15856
15857   // Memory Reference
15858   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15859   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15860
15861   MVT PVT = getPointerTy();
15862   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15863          "Invalid Pointer Size!");
15864
15865   const TargetRegisterClass *RC =
15866     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15867   unsigned Tmp = MRI.createVirtualRegister(RC);
15868   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15869   const X86RegisterInfo *RegInfo =
15870     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15871   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15872   unsigned SP = RegInfo->getStackRegister();
15873
15874   MachineInstrBuilder MIB;
15875
15876   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15877   const int64_t SPOffset = 2 * PVT.getStoreSize();
15878
15879   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15880   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15881
15882   // Reload FP
15883   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15884   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15885     MIB.addOperand(MI->getOperand(i));
15886   MIB.setMemRefs(MMOBegin, MMOEnd);
15887   // Reload IP
15888   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15889   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15890     if (i == X86::AddrDisp)
15891       MIB.addDisp(MI->getOperand(i), LabelOffset);
15892     else
15893       MIB.addOperand(MI->getOperand(i));
15894   }
15895   MIB.setMemRefs(MMOBegin, MMOEnd);
15896   // Reload SP
15897   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15898   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15899     if (i == X86::AddrDisp)
15900       MIB.addDisp(MI->getOperand(i), SPOffset);
15901     else
15902       MIB.addOperand(MI->getOperand(i));
15903   }
15904   MIB.setMemRefs(MMOBegin, MMOEnd);
15905   // Jump
15906   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15907
15908   MI->eraseFromParent();
15909   return MBB;
15910 }
15911
15912 MachineBasicBlock *
15913 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15914                                                MachineBasicBlock *BB) const {
15915   switch (MI->getOpcode()) {
15916   default: llvm_unreachable("Unexpected instr type to insert");
15917   case X86::TAILJMPd64:
15918   case X86::TAILJMPr64:
15919   case X86::TAILJMPm64:
15920     llvm_unreachable("TAILJMP64 would not be touched here.");
15921   case X86::TCRETURNdi64:
15922   case X86::TCRETURNri64:
15923   case X86::TCRETURNmi64:
15924     return BB;
15925   case X86::WIN_ALLOCA:
15926     return EmitLoweredWinAlloca(MI, BB);
15927   case X86::SEG_ALLOCA_32:
15928     return EmitLoweredSegAlloca(MI, BB, false);
15929   case X86::SEG_ALLOCA_64:
15930     return EmitLoweredSegAlloca(MI, BB, true);
15931   case X86::TLSCall_32:
15932   case X86::TLSCall_64:
15933     return EmitLoweredTLSCall(MI, BB);
15934   case X86::CMOV_GR8:
15935   case X86::CMOV_FR32:
15936   case X86::CMOV_FR64:
15937   case X86::CMOV_V4F32:
15938   case X86::CMOV_V2F64:
15939   case X86::CMOV_V2I64:
15940   case X86::CMOV_V8F32:
15941   case X86::CMOV_V4F64:
15942   case X86::CMOV_V4I64:
15943   case X86::CMOV_V16F32:
15944   case X86::CMOV_V8F64:
15945   case X86::CMOV_V8I64:
15946   case X86::CMOV_GR16:
15947   case X86::CMOV_GR32:
15948   case X86::CMOV_RFP32:
15949   case X86::CMOV_RFP64:
15950   case X86::CMOV_RFP80:
15951     return EmitLoweredSelect(MI, BB);
15952
15953   case X86::FP32_TO_INT16_IN_MEM:
15954   case X86::FP32_TO_INT32_IN_MEM:
15955   case X86::FP32_TO_INT64_IN_MEM:
15956   case X86::FP64_TO_INT16_IN_MEM:
15957   case X86::FP64_TO_INT32_IN_MEM:
15958   case X86::FP64_TO_INT64_IN_MEM:
15959   case X86::FP80_TO_INT16_IN_MEM:
15960   case X86::FP80_TO_INT32_IN_MEM:
15961   case X86::FP80_TO_INT64_IN_MEM: {
15962     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15963     DebugLoc DL = MI->getDebugLoc();
15964
15965     // Change the floating point control register to use "round towards zero"
15966     // mode when truncating to an integer value.
15967     MachineFunction *F = BB->getParent();
15968     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15969     addFrameReference(BuildMI(*BB, MI, DL,
15970                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15971
15972     // Load the old value of the high byte of the control word...
15973     unsigned OldCW =
15974       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15975     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15976                       CWFrameIdx);
15977
15978     // Set the high part to be round to zero...
15979     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15980       .addImm(0xC7F);
15981
15982     // Reload the modified control word now...
15983     addFrameReference(BuildMI(*BB, MI, DL,
15984                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15985
15986     // Restore the memory image of control word to original value
15987     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15988       .addReg(OldCW);
15989
15990     // Get the X86 opcode to use.
15991     unsigned Opc;
15992     switch (MI->getOpcode()) {
15993     default: llvm_unreachable("illegal opcode!");
15994     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15995     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15996     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15997     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15998     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15999     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16000     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16001     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16002     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16003     }
16004
16005     X86AddressMode AM;
16006     MachineOperand &Op = MI->getOperand(0);
16007     if (Op.isReg()) {
16008       AM.BaseType = X86AddressMode::RegBase;
16009       AM.Base.Reg = Op.getReg();
16010     } else {
16011       AM.BaseType = X86AddressMode::FrameIndexBase;
16012       AM.Base.FrameIndex = Op.getIndex();
16013     }
16014     Op = MI->getOperand(1);
16015     if (Op.isImm())
16016       AM.Scale = Op.getImm();
16017     Op = MI->getOperand(2);
16018     if (Op.isImm())
16019       AM.IndexReg = Op.getImm();
16020     Op = MI->getOperand(3);
16021     if (Op.isGlobal()) {
16022       AM.GV = Op.getGlobal();
16023     } else {
16024       AM.Disp = Op.getImm();
16025     }
16026     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16027                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16028
16029     // Reload the original control word now.
16030     addFrameReference(BuildMI(*BB, MI, DL,
16031                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16032
16033     MI->eraseFromParent();   // The pseudo instruction is gone now.
16034     return BB;
16035   }
16036     // String/text processing lowering.
16037   case X86::PCMPISTRM128REG:
16038   case X86::VPCMPISTRM128REG:
16039   case X86::PCMPISTRM128MEM:
16040   case X86::VPCMPISTRM128MEM:
16041   case X86::PCMPESTRM128REG:
16042   case X86::VPCMPESTRM128REG:
16043   case X86::PCMPESTRM128MEM:
16044   case X86::VPCMPESTRM128MEM:
16045     assert(Subtarget->hasSSE42() &&
16046            "Target must have SSE4.2 or AVX features enabled");
16047     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16048
16049   // String/text processing lowering.
16050   case X86::PCMPISTRIREG:
16051   case X86::VPCMPISTRIREG:
16052   case X86::PCMPISTRIMEM:
16053   case X86::VPCMPISTRIMEM:
16054   case X86::PCMPESTRIREG:
16055   case X86::VPCMPESTRIREG:
16056   case X86::PCMPESTRIMEM:
16057   case X86::VPCMPESTRIMEM:
16058     assert(Subtarget->hasSSE42() &&
16059            "Target must have SSE4.2 or AVX features enabled");
16060     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16061
16062   // Thread synchronization.
16063   case X86::MONITOR:
16064     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16065
16066   // xbegin
16067   case X86::XBEGIN:
16068     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16069
16070   // Atomic Lowering.
16071   case X86::ATOMAND8:
16072   case X86::ATOMAND16:
16073   case X86::ATOMAND32:
16074   case X86::ATOMAND64:
16075     // Fall through
16076   case X86::ATOMOR8:
16077   case X86::ATOMOR16:
16078   case X86::ATOMOR32:
16079   case X86::ATOMOR64:
16080     // Fall through
16081   case X86::ATOMXOR16:
16082   case X86::ATOMXOR8:
16083   case X86::ATOMXOR32:
16084   case X86::ATOMXOR64:
16085     // Fall through
16086   case X86::ATOMNAND8:
16087   case X86::ATOMNAND16:
16088   case X86::ATOMNAND32:
16089   case X86::ATOMNAND64:
16090     // Fall through
16091   case X86::ATOMMAX8:
16092   case X86::ATOMMAX16:
16093   case X86::ATOMMAX32:
16094   case X86::ATOMMAX64:
16095     // Fall through
16096   case X86::ATOMMIN8:
16097   case X86::ATOMMIN16:
16098   case X86::ATOMMIN32:
16099   case X86::ATOMMIN64:
16100     // Fall through
16101   case X86::ATOMUMAX8:
16102   case X86::ATOMUMAX16:
16103   case X86::ATOMUMAX32:
16104   case X86::ATOMUMAX64:
16105     // Fall through
16106   case X86::ATOMUMIN8:
16107   case X86::ATOMUMIN16:
16108   case X86::ATOMUMIN32:
16109   case X86::ATOMUMIN64:
16110     return EmitAtomicLoadArith(MI, BB);
16111
16112   // This group does 64-bit operations on a 32-bit host.
16113   case X86::ATOMAND6432:
16114   case X86::ATOMOR6432:
16115   case X86::ATOMXOR6432:
16116   case X86::ATOMNAND6432:
16117   case X86::ATOMADD6432:
16118   case X86::ATOMSUB6432:
16119   case X86::ATOMMAX6432:
16120   case X86::ATOMMIN6432:
16121   case X86::ATOMUMAX6432:
16122   case X86::ATOMUMIN6432:
16123   case X86::ATOMSWAP6432:
16124     return EmitAtomicLoadArith6432(MI, BB);
16125
16126   case X86::VASTART_SAVE_XMM_REGS:
16127     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16128
16129   case X86::VAARG_64:
16130     return EmitVAARG64WithCustomInserter(MI, BB);
16131
16132   case X86::EH_SjLj_SetJmp32:
16133   case X86::EH_SjLj_SetJmp64:
16134     return emitEHSjLjSetJmp(MI, BB);
16135
16136   case X86::EH_SjLj_LongJmp32:
16137   case X86::EH_SjLj_LongJmp64:
16138     return emitEHSjLjLongJmp(MI, BB);
16139
16140   case TargetOpcode::STACKMAP:
16141   case TargetOpcode::PATCHPOINT:
16142     return emitPatchPoint(MI, BB);
16143   }
16144 }
16145
16146 //===----------------------------------------------------------------------===//
16147 //                           X86 Optimization Hooks
16148 //===----------------------------------------------------------------------===//
16149
16150 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16151                                                        APInt &KnownZero,
16152                                                        APInt &KnownOne,
16153                                                        const SelectionDAG &DAG,
16154                                                        unsigned Depth) const {
16155   unsigned BitWidth = KnownZero.getBitWidth();
16156   unsigned Opc = Op.getOpcode();
16157   assert((Opc >= ISD::BUILTIN_OP_END ||
16158           Opc == ISD::INTRINSIC_WO_CHAIN ||
16159           Opc == ISD::INTRINSIC_W_CHAIN ||
16160           Opc == ISD::INTRINSIC_VOID) &&
16161          "Should use MaskedValueIsZero if you don't know whether Op"
16162          " is a target node!");
16163
16164   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16165   switch (Opc) {
16166   default: break;
16167   case X86ISD::ADD:
16168   case X86ISD::SUB:
16169   case X86ISD::ADC:
16170   case X86ISD::SBB:
16171   case X86ISD::SMUL:
16172   case X86ISD::UMUL:
16173   case X86ISD::INC:
16174   case X86ISD::DEC:
16175   case X86ISD::OR:
16176   case X86ISD::XOR:
16177   case X86ISD::AND:
16178     // These nodes' second result is a boolean.
16179     if (Op.getResNo() == 0)
16180       break;
16181     // Fallthrough
16182   case X86ISD::SETCC:
16183     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16184     break;
16185   case ISD::INTRINSIC_WO_CHAIN: {
16186     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16187     unsigned NumLoBits = 0;
16188     switch (IntId) {
16189     default: break;
16190     case Intrinsic::x86_sse_movmsk_ps:
16191     case Intrinsic::x86_avx_movmsk_ps_256:
16192     case Intrinsic::x86_sse2_movmsk_pd:
16193     case Intrinsic::x86_avx_movmsk_pd_256:
16194     case Intrinsic::x86_mmx_pmovmskb:
16195     case Intrinsic::x86_sse2_pmovmskb_128:
16196     case Intrinsic::x86_avx2_pmovmskb: {
16197       // High bits of movmskp{s|d}, pmovmskb are known zero.
16198       switch (IntId) {
16199         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16200         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16201         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16202         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16203         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16204         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16205         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16206         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16207       }
16208       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16209       break;
16210     }
16211     }
16212     break;
16213   }
16214   }
16215 }
16216
16217 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16218                                                          unsigned Depth) const {
16219   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16220   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16221     return Op.getValueType().getScalarType().getSizeInBits();
16222
16223   // Fallback case.
16224   return 1;
16225 }
16226
16227 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16228 /// node is a GlobalAddress + offset.
16229 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16230                                        const GlobalValue* &GA,
16231                                        int64_t &Offset) const {
16232   if (N->getOpcode() == X86ISD::Wrapper) {
16233     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16234       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16235       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16236       return true;
16237     }
16238   }
16239   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16240 }
16241
16242 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16243 /// same as extracting the high 128-bit part of 256-bit vector and then
16244 /// inserting the result into the low part of a new 256-bit vector
16245 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16246   EVT VT = SVOp->getValueType(0);
16247   unsigned NumElems = VT.getVectorNumElements();
16248
16249   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16250   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16251     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16252         SVOp->getMaskElt(j) >= 0)
16253       return false;
16254
16255   return true;
16256 }
16257
16258 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16259 /// same as extracting the low 128-bit part of 256-bit vector and then
16260 /// inserting the result into the high part of a new 256-bit vector
16261 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16262   EVT VT = SVOp->getValueType(0);
16263   unsigned NumElems = VT.getVectorNumElements();
16264
16265   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16266   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16267     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16268         SVOp->getMaskElt(j) >= 0)
16269       return false;
16270
16271   return true;
16272 }
16273
16274 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16275 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16276                                         TargetLowering::DAGCombinerInfo &DCI,
16277                                         const X86Subtarget* Subtarget) {
16278   SDLoc dl(N);
16279   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16280   SDValue V1 = SVOp->getOperand(0);
16281   SDValue V2 = SVOp->getOperand(1);
16282   EVT VT = SVOp->getValueType(0);
16283   unsigned NumElems = VT.getVectorNumElements();
16284
16285   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16286       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16287     //
16288     //                   0,0,0,...
16289     //                      |
16290     //    V      UNDEF    BUILD_VECTOR    UNDEF
16291     //     \      /           \           /
16292     //  CONCAT_VECTOR         CONCAT_VECTOR
16293     //         \                  /
16294     //          \                /
16295     //          RESULT: V + zero extended
16296     //
16297     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16298         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16299         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16300       return SDValue();
16301
16302     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16303       return SDValue();
16304
16305     // To match the shuffle mask, the first half of the mask should
16306     // be exactly the first vector, and all the rest a splat with the
16307     // first element of the second one.
16308     for (unsigned i = 0; i != NumElems/2; ++i)
16309       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16310           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16311         return SDValue();
16312
16313     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16314     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16315       if (Ld->hasNUsesOfValue(1, 0)) {
16316         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16317         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16318         SDValue ResNode =
16319           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16320                                   array_lengthof(Ops),
16321                                   Ld->getMemoryVT(),
16322                                   Ld->getPointerInfo(),
16323                                   Ld->getAlignment(),
16324                                   false/*isVolatile*/, true/*ReadMem*/,
16325                                   false/*WriteMem*/);
16326
16327         // Make sure the newly-created LOAD is in the same position as Ld in
16328         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16329         // and update uses of Ld's output chain to use the TokenFactor.
16330         if (Ld->hasAnyUseOfValue(1)) {
16331           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16332                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16333           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16334           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16335                                  SDValue(ResNode.getNode(), 1));
16336         }
16337
16338         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16339       }
16340     }
16341
16342     // Emit a zeroed vector and insert the desired subvector on its
16343     // first half.
16344     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16345     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16346     return DCI.CombineTo(N, InsV);
16347   }
16348
16349   //===--------------------------------------------------------------------===//
16350   // Combine some shuffles into subvector extracts and inserts:
16351   //
16352
16353   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16354   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16355     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16356     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16357     return DCI.CombineTo(N, InsV);
16358   }
16359
16360   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16361   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16362     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16363     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16364     return DCI.CombineTo(N, InsV);
16365   }
16366
16367   return SDValue();
16368 }
16369
16370 /// PerformShuffleCombine - Performs several different shuffle combines.
16371 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16372                                      TargetLowering::DAGCombinerInfo &DCI,
16373                                      const X86Subtarget *Subtarget) {
16374   SDLoc dl(N);
16375   EVT VT = N->getValueType(0);
16376
16377   // Don't create instructions with illegal types after legalize types has run.
16378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16379   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16380     return SDValue();
16381
16382   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16383   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16384       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16385     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16386
16387   // Only handle 128 wide vector from here on.
16388   if (!VT.is128BitVector())
16389     return SDValue();
16390
16391   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16392   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16393   // consecutive, non-overlapping, and in the right order.
16394   SmallVector<SDValue, 16> Elts;
16395   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16396     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16397
16398   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16399 }
16400
16401 /// PerformTruncateCombine - Converts truncate operation to
16402 /// a sequence of vector shuffle operations.
16403 /// It is possible when we truncate 256-bit vector to 128-bit vector
16404 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16405                                       TargetLowering::DAGCombinerInfo &DCI,
16406                                       const X86Subtarget *Subtarget)  {
16407   return SDValue();
16408 }
16409
16410 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16411 /// specific shuffle of a load can be folded into a single element load.
16412 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16413 /// shuffles have been customed lowered so we need to handle those here.
16414 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16415                                          TargetLowering::DAGCombinerInfo &DCI) {
16416   if (DCI.isBeforeLegalizeOps())
16417     return SDValue();
16418
16419   SDValue InVec = N->getOperand(0);
16420   SDValue EltNo = N->getOperand(1);
16421
16422   if (!isa<ConstantSDNode>(EltNo))
16423     return SDValue();
16424
16425   EVT VT = InVec.getValueType();
16426
16427   bool HasShuffleIntoBitcast = false;
16428   if (InVec.getOpcode() == ISD::BITCAST) {
16429     // Don't duplicate a load with other uses.
16430     if (!InVec.hasOneUse())
16431       return SDValue();
16432     EVT BCVT = InVec.getOperand(0).getValueType();
16433     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16434       return SDValue();
16435     InVec = InVec.getOperand(0);
16436     HasShuffleIntoBitcast = true;
16437   }
16438
16439   if (!isTargetShuffle(InVec.getOpcode()))
16440     return SDValue();
16441
16442   // Don't duplicate a load with other uses.
16443   if (!InVec.hasOneUse())
16444     return SDValue();
16445
16446   SmallVector<int, 16> ShuffleMask;
16447   bool UnaryShuffle;
16448   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16449                             UnaryShuffle))
16450     return SDValue();
16451
16452   // Select the input vector, guarding against out of range extract vector.
16453   unsigned NumElems = VT.getVectorNumElements();
16454   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16455   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16456   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16457                                          : InVec.getOperand(1);
16458
16459   // If inputs to shuffle are the same for both ops, then allow 2 uses
16460   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16461
16462   if (LdNode.getOpcode() == ISD::BITCAST) {
16463     // Don't duplicate a load with other uses.
16464     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16465       return SDValue();
16466
16467     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16468     LdNode = LdNode.getOperand(0);
16469   }
16470
16471   if (!ISD::isNormalLoad(LdNode.getNode()))
16472     return SDValue();
16473
16474   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16475
16476   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16477     return SDValue();
16478
16479   if (HasShuffleIntoBitcast) {
16480     // If there's a bitcast before the shuffle, check if the load type and
16481     // alignment is valid.
16482     unsigned Align = LN0->getAlignment();
16483     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16484     unsigned NewAlign = TLI.getDataLayout()->
16485       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16486
16487     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16488       return SDValue();
16489   }
16490
16491   // All checks match so transform back to vector_shuffle so that DAG combiner
16492   // can finish the job
16493   SDLoc dl(N);
16494
16495   // Create shuffle node taking into account the case that its a unary shuffle
16496   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16497   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16498                                  InVec.getOperand(0), Shuffle,
16499                                  &ShuffleMask[0]);
16500   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16501   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16502                      EltNo);
16503 }
16504
16505 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16506 /// generation and convert it from being a bunch of shuffles and extracts
16507 /// to a simple store and scalar loads to extract the elements.
16508 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16509                                          TargetLowering::DAGCombinerInfo &DCI) {
16510   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16511   if (NewOp.getNode())
16512     return NewOp;
16513
16514   SDValue InputVector = N->getOperand(0);
16515
16516   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16517   // from mmx to v2i32 has a single usage.
16518   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16519       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16520       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16521     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16522                        N->getValueType(0),
16523                        InputVector.getNode()->getOperand(0));
16524
16525   // Only operate on vectors of 4 elements, where the alternative shuffling
16526   // gets to be more expensive.
16527   if (InputVector.getValueType() != MVT::v4i32)
16528     return SDValue();
16529
16530   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16531   // single use which is a sign-extend or zero-extend, and all elements are
16532   // used.
16533   SmallVector<SDNode *, 4> Uses;
16534   unsigned ExtractedElements = 0;
16535   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16536        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16537     if (UI.getUse().getResNo() != InputVector.getResNo())
16538       return SDValue();
16539
16540     SDNode *Extract = *UI;
16541     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16542       return SDValue();
16543
16544     if (Extract->getValueType(0) != MVT::i32)
16545       return SDValue();
16546     if (!Extract->hasOneUse())
16547       return SDValue();
16548     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16549         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16550       return SDValue();
16551     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16552       return SDValue();
16553
16554     // Record which element was extracted.
16555     ExtractedElements |=
16556       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16557
16558     Uses.push_back(Extract);
16559   }
16560
16561   // If not all the elements were used, this may not be worthwhile.
16562   if (ExtractedElements != 15)
16563     return SDValue();
16564
16565   // Ok, we've now decided to do the transformation.
16566   SDLoc dl(InputVector);
16567
16568   // Store the value to a temporary stack slot.
16569   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16570   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16571                             MachinePointerInfo(), false, false, 0);
16572
16573   // Replace each use (extract) with a load of the appropriate element.
16574   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16575        UE = Uses.end(); UI != UE; ++UI) {
16576     SDNode *Extract = *UI;
16577
16578     // cOMpute the element's address.
16579     SDValue Idx = Extract->getOperand(1);
16580     unsigned EltSize =
16581         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16582     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16583     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16584     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16585
16586     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16587                                      StackPtr, OffsetVal);
16588
16589     // Load the scalar.
16590     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16591                                      ScalarAddr, MachinePointerInfo(),
16592                                      false, false, false, 0);
16593
16594     // Replace the exact with the load.
16595     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16596   }
16597
16598   // The replacement was made in place; don't return anything.
16599   return SDValue();
16600 }
16601
16602 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16603 static std::pair<unsigned, bool>
16604 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16605                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16606   if (!VT.isVector())
16607     return std::make_pair(0, false);
16608
16609   bool NeedSplit = false;
16610   switch (VT.getSimpleVT().SimpleTy) {
16611   default: return std::make_pair(0, false);
16612   case MVT::v32i8:
16613   case MVT::v16i16:
16614   case MVT::v8i32:
16615     if (!Subtarget->hasAVX2())
16616       NeedSplit = true;
16617     if (!Subtarget->hasAVX())
16618       return std::make_pair(0, false);
16619     break;
16620   case MVT::v16i8:
16621   case MVT::v8i16:
16622   case MVT::v4i32:
16623     if (!Subtarget->hasSSE2())
16624       return std::make_pair(0, false);
16625   }
16626
16627   // SSE2 has only a small subset of the operations.
16628   bool hasUnsigned = Subtarget->hasSSE41() ||
16629                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16630   bool hasSigned = Subtarget->hasSSE41() ||
16631                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16632
16633   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16634
16635   unsigned Opc = 0;
16636   // Check for x CC y ? x : y.
16637   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16638       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16639     switch (CC) {
16640     default: break;
16641     case ISD::SETULT:
16642     case ISD::SETULE:
16643       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16644     case ISD::SETUGT:
16645     case ISD::SETUGE:
16646       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16647     case ISD::SETLT:
16648     case ISD::SETLE:
16649       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16650     case ISD::SETGT:
16651     case ISD::SETGE:
16652       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16653     }
16654   // Check for x CC y ? y : x -- a min/max with reversed arms.
16655   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16656              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16657     switch (CC) {
16658     default: break;
16659     case ISD::SETULT:
16660     case ISD::SETULE:
16661       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16662     case ISD::SETUGT:
16663     case ISD::SETUGE:
16664       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16665     case ISD::SETLT:
16666     case ISD::SETLE:
16667       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16668     case ISD::SETGT:
16669     case ISD::SETGE:
16670       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16671     }
16672   }
16673
16674   return std::make_pair(Opc, NeedSplit);
16675 }
16676
16677 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16678 /// nodes.
16679 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16680                                     TargetLowering::DAGCombinerInfo &DCI,
16681                                     const X86Subtarget *Subtarget) {
16682   SDLoc DL(N);
16683   SDValue Cond = N->getOperand(0);
16684   // Get the LHS/RHS of the select.
16685   SDValue LHS = N->getOperand(1);
16686   SDValue RHS = N->getOperand(2);
16687   EVT VT = LHS.getValueType();
16688   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16689
16690   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16691   // instructions match the semantics of the common C idiom x<y?x:y but not
16692   // x<=y?x:y, because of how they handle negative zero (which can be
16693   // ignored in unsafe-math mode).
16694   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16695       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
16696       (Subtarget->hasSSE2() ||
16697        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16698     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16699
16700     unsigned Opcode = 0;
16701     // Check for x CC y ? x : y.
16702     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16703         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16704       switch (CC) {
16705       default: break;
16706       case ISD::SETULT:
16707         // Converting this to a min would handle NaNs incorrectly, and swapping
16708         // the operands would cause it to handle comparisons between positive
16709         // and negative zero incorrectly.
16710         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16711           if (!DAG.getTarget().Options.UnsafeFPMath &&
16712               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16713             break;
16714           std::swap(LHS, RHS);
16715         }
16716         Opcode = X86ISD::FMIN;
16717         break;
16718       case ISD::SETOLE:
16719         // Converting this to a min would handle comparisons between positive
16720         // and negative zero incorrectly.
16721         if (!DAG.getTarget().Options.UnsafeFPMath &&
16722             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16723           break;
16724         Opcode = X86ISD::FMIN;
16725         break;
16726       case ISD::SETULE:
16727         // Converting this to a min would handle both negative zeros and NaNs
16728         // incorrectly, but we can swap the operands to fix both.
16729         std::swap(LHS, RHS);
16730       case ISD::SETOLT:
16731       case ISD::SETLT:
16732       case ISD::SETLE:
16733         Opcode = X86ISD::FMIN;
16734         break;
16735
16736       case ISD::SETOGE:
16737         // Converting this to a max would handle comparisons between positive
16738         // and negative zero incorrectly.
16739         if (!DAG.getTarget().Options.UnsafeFPMath &&
16740             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16741           break;
16742         Opcode = X86ISD::FMAX;
16743         break;
16744       case ISD::SETUGT:
16745         // Converting this to a max would handle NaNs incorrectly, and swapping
16746         // the operands would cause it to handle comparisons between positive
16747         // and negative zero incorrectly.
16748         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16749           if (!DAG.getTarget().Options.UnsafeFPMath &&
16750               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16751             break;
16752           std::swap(LHS, RHS);
16753         }
16754         Opcode = X86ISD::FMAX;
16755         break;
16756       case ISD::SETUGE:
16757         // Converting this to a max would handle both negative zeros and NaNs
16758         // incorrectly, but we can swap the operands to fix both.
16759         std::swap(LHS, RHS);
16760       case ISD::SETOGT:
16761       case ISD::SETGT:
16762       case ISD::SETGE:
16763         Opcode = X86ISD::FMAX;
16764         break;
16765       }
16766     // Check for x CC y ? y : x -- a min/max with reversed arms.
16767     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16768                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16769       switch (CC) {
16770       default: break;
16771       case ISD::SETOGE:
16772         // Converting this to a min would handle comparisons between positive
16773         // and negative zero incorrectly, and swapping the operands would
16774         // cause it to handle NaNs incorrectly.
16775         if (!DAG.getTarget().Options.UnsafeFPMath &&
16776             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16777           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16778             break;
16779           std::swap(LHS, RHS);
16780         }
16781         Opcode = X86ISD::FMIN;
16782         break;
16783       case ISD::SETUGT:
16784         // Converting this to a min would handle NaNs incorrectly.
16785         if (!DAG.getTarget().Options.UnsafeFPMath &&
16786             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16787           break;
16788         Opcode = X86ISD::FMIN;
16789         break;
16790       case ISD::SETUGE:
16791         // Converting this to a min would handle both negative zeros and NaNs
16792         // incorrectly, but we can swap the operands to fix both.
16793         std::swap(LHS, RHS);
16794       case ISD::SETOGT:
16795       case ISD::SETGT:
16796       case ISD::SETGE:
16797         Opcode = X86ISD::FMIN;
16798         break;
16799
16800       case ISD::SETULT:
16801         // Converting this to a max would handle NaNs incorrectly.
16802         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16803           break;
16804         Opcode = X86ISD::FMAX;
16805         break;
16806       case ISD::SETOLE:
16807         // Converting this to a max would handle comparisons between positive
16808         // and negative zero incorrectly, and swapping the operands would
16809         // cause it to handle NaNs incorrectly.
16810         if (!DAG.getTarget().Options.UnsafeFPMath &&
16811             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16812           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16813             break;
16814           std::swap(LHS, RHS);
16815         }
16816         Opcode = X86ISD::FMAX;
16817         break;
16818       case ISD::SETULE:
16819         // Converting this to a max would handle both negative zeros and NaNs
16820         // incorrectly, but we can swap the operands to fix both.
16821         std::swap(LHS, RHS);
16822       case ISD::SETOLT:
16823       case ISD::SETLT:
16824       case ISD::SETLE:
16825         Opcode = X86ISD::FMAX;
16826         break;
16827       }
16828     }
16829
16830     if (Opcode)
16831       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16832   }
16833
16834   EVT CondVT = Cond.getValueType();
16835   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
16836       CondVT.getVectorElementType() == MVT::i1) {
16837     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
16838     // lowering on AVX-512. In this case we convert it to
16839     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
16840     // The same situation for all 128 and 256-bit vectors of i8 and i16
16841     EVT OpVT = LHS.getValueType();
16842     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
16843         (OpVT.getVectorElementType() == MVT::i8 ||
16844          OpVT.getVectorElementType() == MVT::i16)) {
16845       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
16846       DCI.AddToWorklist(Cond.getNode());
16847       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
16848     }
16849   }
16850   // If this is a select between two integer constants, try to do some
16851   // optimizations.
16852   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16853     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16854       // Don't do this for crazy integer types.
16855       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16856         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16857         // so that TrueC (the true value) is larger than FalseC.
16858         bool NeedsCondInvert = false;
16859
16860         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16861             // Efficiently invertible.
16862             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16863              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16864               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16865           NeedsCondInvert = true;
16866           std::swap(TrueC, FalseC);
16867         }
16868
16869         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16870         if (FalseC->getAPIntValue() == 0 &&
16871             TrueC->getAPIntValue().isPowerOf2()) {
16872           if (NeedsCondInvert) // Invert the condition if needed.
16873             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16874                                DAG.getConstant(1, Cond.getValueType()));
16875
16876           // Zero extend the condition if needed.
16877           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16878
16879           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16880           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16881                              DAG.getConstant(ShAmt, MVT::i8));
16882         }
16883
16884         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16885         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16886           if (NeedsCondInvert) // Invert the condition if needed.
16887             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16888                                DAG.getConstant(1, Cond.getValueType()));
16889
16890           // Zero extend the condition if needed.
16891           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16892                              FalseC->getValueType(0), Cond);
16893           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16894                              SDValue(FalseC, 0));
16895         }
16896
16897         // Optimize cases that will turn into an LEA instruction.  This requires
16898         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16899         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16900           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16901           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16902
16903           bool isFastMultiplier = false;
16904           if (Diff < 10) {
16905             switch ((unsigned char)Diff) {
16906               default: break;
16907               case 1:  // result = add base, cond
16908               case 2:  // result = lea base(    , cond*2)
16909               case 3:  // result = lea base(cond, cond*2)
16910               case 4:  // result = lea base(    , cond*4)
16911               case 5:  // result = lea base(cond, cond*4)
16912               case 8:  // result = lea base(    , cond*8)
16913               case 9:  // result = lea base(cond, cond*8)
16914                 isFastMultiplier = true;
16915                 break;
16916             }
16917           }
16918
16919           if (isFastMultiplier) {
16920             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16921             if (NeedsCondInvert) // Invert the condition if needed.
16922               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16923                                  DAG.getConstant(1, Cond.getValueType()));
16924
16925             // Zero extend the condition if needed.
16926             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16927                                Cond);
16928             // Scale the condition by the difference.
16929             if (Diff != 1)
16930               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16931                                  DAG.getConstant(Diff, Cond.getValueType()));
16932
16933             // Add the base if non-zero.
16934             if (FalseC->getAPIntValue() != 0)
16935               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16936                                  SDValue(FalseC, 0));
16937             return Cond;
16938           }
16939         }
16940       }
16941   }
16942
16943   // Canonicalize max and min:
16944   // (x > y) ? x : y -> (x >= y) ? x : y
16945   // (x < y) ? x : y -> (x <= y) ? x : y
16946   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16947   // the need for an extra compare
16948   // against zero. e.g.
16949   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16950   // subl   %esi, %edi
16951   // testl  %edi, %edi
16952   // movl   $0, %eax
16953   // cmovgl %edi, %eax
16954   // =>
16955   // xorl   %eax, %eax
16956   // subl   %esi, $edi
16957   // cmovsl %eax, %edi
16958   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16959       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16960       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16961     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16962     switch (CC) {
16963     default: break;
16964     case ISD::SETLT:
16965     case ISD::SETGT: {
16966       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16967       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16968                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16969       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16970     }
16971     }
16972   }
16973
16974   // Early exit check
16975   if (!TLI.isTypeLegal(VT))
16976     return SDValue();
16977
16978   // Match VSELECTs into subs with unsigned saturation.
16979   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16980       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16981       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16982        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16983     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16984
16985     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16986     // left side invert the predicate to simplify logic below.
16987     SDValue Other;
16988     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16989       Other = RHS;
16990       CC = ISD::getSetCCInverse(CC, true);
16991     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16992       Other = LHS;
16993     }
16994
16995     if (Other.getNode() && Other->getNumOperands() == 2 &&
16996         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16997       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16998       SDValue CondRHS = Cond->getOperand(1);
16999
17000       // Look for a general sub with unsigned saturation first.
17001       // x >= y ? x-y : 0 --> subus x, y
17002       // x >  y ? x-y : 0 --> subus x, y
17003       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17004           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17005         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17006
17007       // If the RHS is a constant we have to reverse the const canonicalization.
17008       // x > C-1 ? x+-C : 0 --> subus x, C
17009       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17010           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17011         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17012         if (CondRHS.getConstantOperandVal(0) == -A-1)
17013           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17014                              DAG.getConstant(-A, VT));
17015       }
17016
17017       // Another special case: If C was a sign bit, the sub has been
17018       // canonicalized into a xor.
17019       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17020       //        it's safe to decanonicalize the xor?
17021       // x s< 0 ? x^C : 0 --> subus x, C
17022       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17023           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17024           isSplatVector(OpRHS.getNode())) {
17025         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17026         if (A.isSignBit())
17027           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17028       }
17029     }
17030   }
17031
17032   // Try to match a min/max vector operation.
17033   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17034     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17035     unsigned Opc = ret.first;
17036     bool NeedSplit = ret.second;
17037
17038     if (Opc && NeedSplit) {
17039       unsigned NumElems = VT.getVectorNumElements();
17040       // Extract the LHS vectors
17041       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17042       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17043
17044       // Extract the RHS vectors
17045       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17046       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17047
17048       // Create min/max for each subvector
17049       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17050       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17051
17052       // Merge the result
17053       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17054     } else if (Opc)
17055       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17056   }
17057
17058   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17059   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17060       // Check if SETCC has already been promoted
17061       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17062       // Check that condition value type matches vselect operand type
17063       CondVT == VT) { 
17064
17065     assert(Cond.getValueType().isVector() &&
17066            "vector select expects a vector selector!");
17067
17068     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17069     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17070
17071     if (!TValIsAllOnes && !FValIsAllZeros) {
17072       // Try invert the condition if true value is not all 1s and false value
17073       // is not all 0s.
17074       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17075       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17076
17077       if (TValIsAllZeros || FValIsAllOnes) {
17078         SDValue CC = Cond.getOperand(2);
17079         ISD::CondCode NewCC =
17080           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17081                                Cond.getOperand(0).getValueType().isInteger());
17082         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17083         std::swap(LHS, RHS);
17084         TValIsAllOnes = FValIsAllOnes;
17085         FValIsAllZeros = TValIsAllZeros;
17086       }
17087     }
17088
17089     if (TValIsAllOnes || FValIsAllZeros) {
17090       SDValue Ret;
17091
17092       if (TValIsAllOnes && FValIsAllZeros)
17093         Ret = Cond;
17094       else if (TValIsAllOnes)
17095         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17096                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17097       else if (FValIsAllZeros)
17098         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17099                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17100
17101       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17102     }
17103   }
17104
17105   // If we know that this node is legal then we know that it is going to be
17106   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17107   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17108   // to simplify previous instructions.
17109   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17110       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17111     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17112
17113     // Don't optimize vector selects that map to mask-registers.
17114     if (BitWidth == 1)
17115       return SDValue();
17116
17117     // Check all uses of that condition operand to check whether it will be
17118     // consumed by non-BLEND instructions, which may depend on all bits are set
17119     // properly.
17120     for (SDNode::use_iterator I = Cond->use_begin(),
17121                               E = Cond->use_end(); I != E; ++I)
17122       if (I->getOpcode() != ISD::VSELECT)
17123         // TODO: Add other opcodes eventually lowered into BLEND.
17124         return SDValue();
17125
17126     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17127     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17128
17129     APInt KnownZero, KnownOne;
17130     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17131                                           DCI.isBeforeLegalizeOps());
17132     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17133         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17134       DCI.CommitTargetLoweringOpt(TLO);
17135   }
17136
17137   return SDValue();
17138 }
17139
17140 // Check whether a boolean test is testing a boolean value generated by
17141 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17142 // code.
17143 //
17144 // Simplify the following patterns:
17145 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17146 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17147 // to (Op EFLAGS Cond)
17148 //
17149 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17150 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17151 // to (Op EFLAGS !Cond)
17152 //
17153 // where Op could be BRCOND or CMOV.
17154 //
17155 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17156   // Quit if not CMP and SUB with its value result used.
17157   if (Cmp.getOpcode() != X86ISD::CMP &&
17158       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17159       return SDValue();
17160
17161   // Quit if not used as a boolean value.
17162   if (CC != X86::COND_E && CC != X86::COND_NE)
17163     return SDValue();
17164
17165   // Check CMP operands. One of them should be 0 or 1 and the other should be
17166   // an SetCC or extended from it.
17167   SDValue Op1 = Cmp.getOperand(0);
17168   SDValue Op2 = Cmp.getOperand(1);
17169
17170   SDValue SetCC;
17171   const ConstantSDNode* C = 0;
17172   bool needOppositeCond = (CC == X86::COND_E);
17173   bool checkAgainstTrue = false; // Is it a comparison against 1?
17174
17175   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17176     SetCC = Op2;
17177   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17178     SetCC = Op1;
17179   else // Quit if all operands are not constants.
17180     return SDValue();
17181
17182   if (C->getZExtValue() == 1) {
17183     needOppositeCond = !needOppositeCond;
17184     checkAgainstTrue = true;
17185   } else if (C->getZExtValue() != 0)
17186     // Quit if the constant is neither 0 or 1.
17187     return SDValue();
17188
17189   bool truncatedToBoolWithAnd = false;
17190   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17191   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17192          SetCC.getOpcode() == ISD::TRUNCATE ||
17193          SetCC.getOpcode() == ISD::AND) {
17194     if (SetCC.getOpcode() == ISD::AND) {
17195       int OpIdx = -1;
17196       ConstantSDNode *CS;
17197       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17198           CS->getZExtValue() == 1)
17199         OpIdx = 1;
17200       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17201           CS->getZExtValue() == 1)
17202         OpIdx = 0;
17203       if (OpIdx == -1)
17204         break;
17205       SetCC = SetCC.getOperand(OpIdx);
17206       truncatedToBoolWithAnd = true;
17207     } else
17208       SetCC = SetCC.getOperand(0);
17209   }
17210
17211   switch (SetCC.getOpcode()) {
17212   case X86ISD::SETCC_CARRY:
17213     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17214     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17215     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17216     // truncated to i1 using 'and'.
17217     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17218       break;
17219     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17220            "Invalid use of SETCC_CARRY!");
17221     // FALL THROUGH
17222   case X86ISD::SETCC:
17223     // Set the condition code or opposite one if necessary.
17224     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17225     if (needOppositeCond)
17226       CC = X86::GetOppositeBranchCondition(CC);
17227     return SetCC.getOperand(1);
17228   case X86ISD::CMOV: {
17229     // Check whether false/true value has canonical one, i.e. 0 or 1.
17230     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17231     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17232     // Quit if true value is not a constant.
17233     if (!TVal)
17234       return SDValue();
17235     // Quit if false value is not a constant.
17236     if (!FVal) {
17237       SDValue Op = SetCC.getOperand(0);
17238       // Skip 'zext' or 'trunc' node.
17239       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17240           Op.getOpcode() == ISD::TRUNCATE)
17241         Op = Op.getOperand(0);
17242       // A special case for rdrand/rdseed, where 0 is set if false cond is
17243       // found.
17244       if ((Op.getOpcode() != X86ISD::RDRAND &&
17245            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17246         return SDValue();
17247     }
17248     // Quit if false value is not the constant 0 or 1.
17249     bool FValIsFalse = true;
17250     if (FVal && FVal->getZExtValue() != 0) {
17251       if (FVal->getZExtValue() != 1)
17252         return SDValue();
17253       // If FVal is 1, opposite cond is needed.
17254       needOppositeCond = !needOppositeCond;
17255       FValIsFalse = false;
17256     }
17257     // Quit if TVal is not the constant opposite of FVal.
17258     if (FValIsFalse && TVal->getZExtValue() != 1)
17259       return SDValue();
17260     if (!FValIsFalse && TVal->getZExtValue() != 0)
17261       return SDValue();
17262     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17263     if (needOppositeCond)
17264       CC = X86::GetOppositeBranchCondition(CC);
17265     return SetCC.getOperand(3);
17266   }
17267   }
17268
17269   return SDValue();
17270 }
17271
17272 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17273 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17274                                   TargetLowering::DAGCombinerInfo &DCI,
17275                                   const X86Subtarget *Subtarget) {
17276   SDLoc DL(N);
17277
17278   // If the flag operand isn't dead, don't touch this CMOV.
17279   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17280     return SDValue();
17281
17282   SDValue FalseOp = N->getOperand(0);
17283   SDValue TrueOp = N->getOperand(1);
17284   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17285   SDValue Cond = N->getOperand(3);
17286
17287   if (CC == X86::COND_E || CC == X86::COND_NE) {
17288     switch (Cond.getOpcode()) {
17289     default: break;
17290     case X86ISD::BSR:
17291     case X86ISD::BSF:
17292       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17293       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17294         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17295     }
17296   }
17297
17298   SDValue Flags;
17299
17300   Flags = checkBoolTestSetCCCombine(Cond, CC);
17301   if (Flags.getNode() &&
17302       // Extra check as FCMOV only supports a subset of X86 cond.
17303       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17304     SDValue Ops[] = { FalseOp, TrueOp,
17305                       DAG.getConstant(CC, MVT::i8), Flags };
17306     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17307                        Ops, array_lengthof(Ops));
17308   }
17309
17310   // If this is a select between two integer constants, try to do some
17311   // optimizations.  Note that the operands are ordered the opposite of SELECT
17312   // operands.
17313   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17314     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17315       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17316       // larger than FalseC (the false value).
17317       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17318         CC = X86::GetOppositeBranchCondition(CC);
17319         std::swap(TrueC, FalseC);
17320         std::swap(TrueOp, FalseOp);
17321       }
17322
17323       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17324       // This is efficient for any integer data type (including i8/i16) and
17325       // shift amount.
17326       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17327         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17328                            DAG.getConstant(CC, MVT::i8), Cond);
17329
17330         // Zero extend the condition if needed.
17331         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17332
17333         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17334         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17335                            DAG.getConstant(ShAmt, MVT::i8));
17336         if (N->getNumValues() == 2)  // Dead flag value?
17337           return DCI.CombineTo(N, Cond, SDValue());
17338         return Cond;
17339       }
17340
17341       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17342       // for any integer data type, including i8/i16.
17343       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17344         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17345                            DAG.getConstant(CC, MVT::i8), Cond);
17346
17347         // Zero extend the condition if needed.
17348         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17349                            FalseC->getValueType(0), Cond);
17350         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17351                            SDValue(FalseC, 0));
17352
17353         if (N->getNumValues() == 2)  // Dead flag value?
17354           return DCI.CombineTo(N, Cond, SDValue());
17355         return Cond;
17356       }
17357
17358       // Optimize cases that will turn into an LEA instruction.  This requires
17359       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17360       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17361         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17362         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17363
17364         bool isFastMultiplier = false;
17365         if (Diff < 10) {
17366           switch ((unsigned char)Diff) {
17367           default: break;
17368           case 1:  // result = add base, cond
17369           case 2:  // result = lea base(    , cond*2)
17370           case 3:  // result = lea base(cond, cond*2)
17371           case 4:  // result = lea base(    , cond*4)
17372           case 5:  // result = lea base(cond, cond*4)
17373           case 8:  // result = lea base(    , cond*8)
17374           case 9:  // result = lea base(cond, cond*8)
17375             isFastMultiplier = true;
17376             break;
17377           }
17378         }
17379
17380         if (isFastMultiplier) {
17381           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17382           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17383                              DAG.getConstant(CC, MVT::i8), Cond);
17384           // Zero extend the condition if needed.
17385           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17386                              Cond);
17387           // Scale the condition by the difference.
17388           if (Diff != 1)
17389             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17390                                DAG.getConstant(Diff, Cond.getValueType()));
17391
17392           // Add the base if non-zero.
17393           if (FalseC->getAPIntValue() != 0)
17394             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17395                                SDValue(FalseC, 0));
17396           if (N->getNumValues() == 2)  // Dead flag value?
17397             return DCI.CombineTo(N, Cond, SDValue());
17398           return Cond;
17399         }
17400       }
17401     }
17402   }
17403
17404   // Handle these cases:
17405   //   (select (x != c), e, c) -> select (x != c), e, x),
17406   //   (select (x == c), c, e) -> select (x == c), x, e)
17407   // where the c is an integer constant, and the "select" is the combination
17408   // of CMOV and CMP.
17409   //
17410   // The rationale for this change is that the conditional-move from a constant
17411   // needs two instructions, however, conditional-move from a register needs
17412   // only one instruction.
17413   //
17414   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17415   //  some instruction-combining opportunities. This opt needs to be
17416   //  postponed as late as possible.
17417   //
17418   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17419     // the DCI.xxxx conditions are provided to postpone the optimization as
17420     // late as possible.
17421
17422     ConstantSDNode *CmpAgainst = 0;
17423     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17424         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17425         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17426
17427       if (CC == X86::COND_NE &&
17428           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17429         CC = X86::GetOppositeBranchCondition(CC);
17430         std::swap(TrueOp, FalseOp);
17431       }
17432
17433       if (CC == X86::COND_E &&
17434           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17435         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17436                           DAG.getConstant(CC, MVT::i8), Cond };
17437         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17438                            array_lengthof(Ops));
17439       }
17440     }
17441   }
17442
17443   return SDValue();
17444 }
17445
17446 /// PerformMulCombine - Optimize a single multiply with constant into two
17447 /// in order to implement it with two cheaper instructions, e.g.
17448 /// LEA + SHL, LEA + LEA.
17449 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17450                                  TargetLowering::DAGCombinerInfo &DCI) {
17451   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17452     return SDValue();
17453
17454   EVT VT = N->getValueType(0);
17455   if (VT != MVT::i64)
17456     return SDValue();
17457
17458   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17459   if (!C)
17460     return SDValue();
17461   uint64_t MulAmt = C->getZExtValue();
17462   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17463     return SDValue();
17464
17465   uint64_t MulAmt1 = 0;
17466   uint64_t MulAmt2 = 0;
17467   if ((MulAmt % 9) == 0) {
17468     MulAmt1 = 9;
17469     MulAmt2 = MulAmt / 9;
17470   } else if ((MulAmt % 5) == 0) {
17471     MulAmt1 = 5;
17472     MulAmt2 = MulAmt / 5;
17473   } else if ((MulAmt % 3) == 0) {
17474     MulAmt1 = 3;
17475     MulAmt2 = MulAmt / 3;
17476   }
17477   if (MulAmt2 &&
17478       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17479     SDLoc DL(N);
17480
17481     if (isPowerOf2_64(MulAmt2) &&
17482         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17483       // If second multiplifer is pow2, issue it first. We want the multiply by
17484       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17485       // is an add.
17486       std::swap(MulAmt1, MulAmt2);
17487
17488     SDValue NewMul;
17489     if (isPowerOf2_64(MulAmt1))
17490       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17491                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17492     else
17493       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17494                            DAG.getConstant(MulAmt1, VT));
17495
17496     if (isPowerOf2_64(MulAmt2))
17497       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17498                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17499     else
17500       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17501                            DAG.getConstant(MulAmt2, VT));
17502
17503     // Do not add new nodes to DAG combiner worklist.
17504     DCI.CombineTo(N, NewMul, false);
17505   }
17506   return SDValue();
17507 }
17508
17509 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17510   SDValue N0 = N->getOperand(0);
17511   SDValue N1 = N->getOperand(1);
17512   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17513   EVT VT = N0.getValueType();
17514
17515   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17516   // since the result of setcc_c is all zero's or all ones.
17517   if (VT.isInteger() && !VT.isVector() &&
17518       N1C && N0.getOpcode() == ISD::AND &&
17519       N0.getOperand(1).getOpcode() == ISD::Constant) {
17520     SDValue N00 = N0.getOperand(0);
17521     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17522         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17523           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17524          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17525       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17526       APInt ShAmt = N1C->getAPIntValue();
17527       Mask = Mask.shl(ShAmt);
17528       if (Mask != 0)
17529         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17530                            N00, DAG.getConstant(Mask, VT));
17531     }
17532   }
17533
17534   // Hardware support for vector shifts is sparse which makes us scalarize the
17535   // vector operations in many cases. Also, on sandybridge ADD is faster than
17536   // shl.
17537   // (shl V, 1) -> add V,V
17538   if (isSplatVector(N1.getNode())) {
17539     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17540     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17541     // We shift all of the values by one. In many cases we do not have
17542     // hardware support for this operation. This is better expressed as an ADD
17543     // of two values.
17544     if (N1C && (1 == N1C->getZExtValue())) {
17545       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17546     }
17547   }
17548
17549   return SDValue();
17550 }
17551
17552 /// \brief Returns a vector of 0s if the node in input is a vector logical
17553 /// shift by a constant amount which is known to be bigger than or equal
17554 /// to the vector element size in bits.
17555 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17556                                       const X86Subtarget *Subtarget) {
17557   EVT VT = N->getValueType(0);
17558
17559   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17560       (!Subtarget->hasInt256() ||
17561        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17562     return SDValue();
17563
17564   SDValue Amt = N->getOperand(1);
17565   SDLoc DL(N);
17566   if (isSplatVector(Amt.getNode())) {
17567     SDValue SclrAmt = Amt->getOperand(0);
17568     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17569       APInt ShiftAmt = C->getAPIntValue();
17570       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17571
17572       // SSE2/AVX2 logical shifts always return a vector of 0s
17573       // if the shift amount is bigger than or equal to
17574       // the element size. The constant shift amount will be
17575       // encoded as a 8-bit immediate.
17576       if (ShiftAmt.trunc(8).uge(MaxAmount))
17577         return getZeroVector(VT, Subtarget, DAG, DL);
17578     }
17579   }
17580
17581   return SDValue();
17582 }
17583
17584 /// PerformShiftCombine - Combine shifts.
17585 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17586                                    TargetLowering::DAGCombinerInfo &DCI,
17587                                    const X86Subtarget *Subtarget) {
17588   if (N->getOpcode() == ISD::SHL) {
17589     SDValue V = PerformSHLCombine(N, DAG);
17590     if (V.getNode()) return V;
17591   }
17592
17593   if (N->getOpcode() != ISD::SRA) {
17594     // Try to fold this logical shift into a zero vector.
17595     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17596     if (V.getNode()) return V;
17597   }
17598
17599   return SDValue();
17600 }
17601
17602 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
17603 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17604 // and friends.  Likewise for OR -> CMPNEQSS.
17605 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17606                             TargetLowering::DAGCombinerInfo &DCI,
17607                             const X86Subtarget *Subtarget) {
17608   unsigned opcode;
17609
17610   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17611   // we're requiring SSE2 for both.
17612   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17613     SDValue N0 = N->getOperand(0);
17614     SDValue N1 = N->getOperand(1);
17615     SDValue CMP0 = N0->getOperand(1);
17616     SDValue CMP1 = N1->getOperand(1);
17617     SDLoc DL(N);
17618
17619     // The SETCCs should both refer to the same CMP.
17620     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
17621       return SDValue();
17622
17623     SDValue CMP00 = CMP0->getOperand(0);
17624     SDValue CMP01 = CMP0->getOperand(1);
17625     EVT     VT    = CMP00.getValueType();
17626
17627     if (VT == MVT::f32 || VT == MVT::f64) {
17628       bool ExpectingFlags = false;
17629       // Check for any users that want flags:
17630       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
17631            !ExpectingFlags && UI != UE; ++UI)
17632         switch (UI->getOpcode()) {
17633         default:
17634         case ISD::BR_CC:
17635         case ISD::BRCOND:
17636         case ISD::SELECT:
17637           ExpectingFlags = true;
17638           break;
17639         case ISD::CopyToReg:
17640         case ISD::SIGN_EXTEND:
17641         case ISD::ZERO_EXTEND:
17642         case ISD::ANY_EXTEND:
17643           break;
17644         }
17645
17646       if (!ExpectingFlags) {
17647         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
17648         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
17649
17650         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
17651           X86::CondCode tmp = cc0;
17652           cc0 = cc1;
17653           cc1 = tmp;
17654         }
17655
17656         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
17657             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17658           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17659           // FIXME: need symbolic constants for these magic numbers.
17660           // See X86ATTInstPrinter.cpp:printSSECC().
17661           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17662           if (Subtarget->hasAVX512()) {
17663             // SETCC type in AVX-512 is MVT::i1
17664             assert(N->getValueType(0) == MVT::i1 && "Unexpected AND node type");
17665             return DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00, CMP01,
17666                                DAG.getConstant(x86cc, MVT::i8));
17667           }
17668           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00, CMP01,
17669                                               DAG.getConstant(x86cc, MVT::i8));
17670           MVT IntVT = (is64BitFP ? MVT::i64 : MVT::i32); 
17671           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
17672                                               OnesOrZeroesF);
17673           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
17674                                       DAG.getConstant(1, IntVT));
17675           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17676           return OneBitOfTruth;
17677         }
17678       }
17679     }
17680   }
17681   return SDValue();
17682 }
17683
17684 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17685 /// so it can be folded inside ANDNP.
17686 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17687   EVT VT = N->getValueType(0);
17688
17689   // Match direct AllOnes for 128 and 256-bit vectors
17690   if (ISD::isBuildVectorAllOnes(N))
17691     return true;
17692
17693   // Look through a bit convert.
17694   if (N->getOpcode() == ISD::BITCAST)
17695     N = N->getOperand(0).getNode();
17696
17697   // Sometimes the operand may come from a insert_subvector building a 256-bit
17698   // allones vector
17699   if (VT.is256BitVector() &&
17700       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17701     SDValue V1 = N->getOperand(0);
17702     SDValue V2 = N->getOperand(1);
17703
17704     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17705         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17706         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17707         ISD::isBuildVectorAllOnes(V2.getNode()))
17708       return true;
17709   }
17710
17711   return false;
17712 }
17713
17714 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17715 // register. In most cases we actually compare or select YMM-sized registers
17716 // and mixing the two types creates horrible code. This method optimizes
17717 // some of the transition sequences.
17718 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17719                                  TargetLowering::DAGCombinerInfo &DCI,
17720                                  const X86Subtarget *Subtarget) {
17721   EVT VT = N->getValueType(0);
17722   if (!VT.is256BitVector())
17723     return SDValue();
17724
17725   assert((N->getOpcode() == ISD::ANY_EXTEND ||
17726           N->getOpcode() == ISD::ZERO_EXTEND ||
17727           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17728
17729   SDValue Narrow = N->getOperand(0);
17730   EVT NarrowVT = Narrow->getValueType(0);
17731   if (!NarrowVT.is128BitVector())
17732     return SDValue();
17733
17734   if (Narrow->getOpcode() != ISD::XOR &&
17735       Narrow->getOpcode() != ISD::AND &&
17736       Narrow->getOpcode() != ISD::OR)
17737     return SDValue();
17738
17739   SDValue N0  = Narrow->getOperand(0);
17740   SDValue N1  = Narrow->getOperand(1);
17741   SDLoc DL(Narrow);
17742
17743   // The Left side has to be a trunc.
17744   if (N0.getOpcode() != ISD::TRUNCATE)
17745     return SDValue();
17746
17747   // The type of the truncated inputs.
17748   EVT WideVT = N0->getOperand(0)->getValueType(0);
17749   if (WideVT != VT)
17750     return SDValue();
17751
17752   // The right side has to be a 'trunc' or a constant vector.
17753   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17754   bool RHSConst = (isSplatVector(N1.getNode()) &&
17755                    isa<ConstantSDNode>(N1->getOperand(0)));
17756   if (!RHSTrunc && !RHSConst)
17757     return SDValue();
17758
17759   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17760
17761   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17762     return SDValue();
17763
17764   // Set N0 and N1 to hold the inputs to the new wide operation.
17765   N0 = N0->getOperand(0);
17766   if (RHSConst) {
17767     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17768                      N1->getOperand(0));
17769     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17770     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17771   } else if (RHSTrunc) {
17772     N1 = N1->getOperand(0);
17773   }
17774
17775   // Generate the wide operation.
17776   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17777   unsigned Opcode = N->getOpcode();
17778   switch (Opcode) {
17779   case ISD::ANY_EXTEND:
17780     return Op;
17781   case ISD::ZERO_EXTEND: {
17782     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17783     APInt Mask = APInt::getAllOnesValue(InBits);
17784     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17785     return DAG.getNode(ISD::AND, DL, VT,
17786                        Op, DAG.getConstant(Mask, VT));
17787   }
17788   case ISD::SIGN_EXTEND:
17789     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17790                        Op, DAG.getValueType(NarrowVT));
17791   default:
17792     llvm_unreachable("Unexpected opcode");
17793   }
17794 }
17795
17796 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17797                                  TargetLowering::DAGCombinerInfo &DCI,
17798                                  const X86Subtarget *Subtarget) {
17799   EVT VT = N->getValueType(0);
17800   if (DCI.isBeforeLegalizeOps())
17801     return SDValue();
17802
17803   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17804   if (R.getNode())
17805     return R;
17806
17807   // Create BLSI, BLSR, and BZHI instructions
17808   // BLSI is X & (-X)
17809   // BLSR is X & (X-1)
17810   // BZHI is X & ((1 << Y) - 1)
17811   // BEXTR is ((X >> imm) & (2**size-1))
17812   if (VT == MVT::i32 || VT == MVT::i64) {
17813     SDValue N0 = N->getOperand(0);
17814     SDValue N1 = N->getOperand(1);
17815     SDLoc DL(N);
17816
17817     if (Subtarget->hasBMI()) {
17818       // Check LHS for neg
17819       if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17820           isZero(N0.getOperand(0)))
17821         return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17822
17823       // Check RHS for neg
17824       if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17825           isZero(N1.getOperand(0)))
17826         return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17827
17828       // Check LHS for X-1
17829       if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17830           isAllOnes(N0.getOperand(1)))
17831         return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17832
17833       // Check RHS for X-1
17834       if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17835           isAllOnes(N1.getOperand(1)))
17836         return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17837     }
17838
17839     if (Subtarget->hasBMI2()) {
17840       // Check for (and (add (shl 1, Y), -1), X)
17841       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
17842         SDValue N00 = N0.getOperand(0);
17843         if (N00.getOpcode() == ISD::SHL) {
17844           SDValue N001 = N00.getOperand(1);
17845           assert(N001.getValueType() == MVT::i8 && "unexpected type");
17846           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
17847           if (C && C->getZExtValue() == 1)
17848             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
17849         }
17850       }
17851
17852       // Check for (and X, (add (shl 1, Y), -1))
17853       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
17854         SDValue N10 = N1.getOperand(0);
17855         if (N10.getOpcode() == ISD::SHL) {
17856           SDValue N101 = N10.getOperand(1);
17857           assert(N101.getValueType() == MVT::i8 && "unexpected type");
17858           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
17859           if (C && C->getZExtValue() == 1)
17860             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
17861         }
17862       }
17863     }
17864
17865     // Check for BEXTR.
17866     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
17867         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
17868       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
17869       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17870       if (MaskNode && ShiftNode) {
17871         uint64_t Mask = MaskNode->getZExtValue();
17872         uint64_t Shift = ShiftNode->getZExtValue();
17873         if (isMask_64(Mask)) {
17874           uint64_t MaskSize = CountPopulation_64(Mask);
17875           if (Shift + MaskSize <= VT.getSizeInBits())
17876             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
17877                                DAG.getConstant(Shift | (MaskSize << 8), VT));
17878         }
17879       }
17880     } // BEXTR
17881
17882     return SDValue();
17883   }
17884
17885   // Want to form ANDNP nodes:
17886   // 1) In the hopes of then easily combining them with OR and AND nodes
17887   //    to form PBLEND/PSIGN.
17888   // 2) To match ANDN packed intrinsics
17889   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17890     return SDValue();
17891
17892   SDValue N0 = N->getOperand(0);
17893   SDValue N1 = N->getOperand(1);
17894   SDLoc DL(N);
17895
17896   // Check LHS for vnot
17897   if (N0.getOpcode() == ISD::XOR &&
17898       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17899       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17900     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17901
17902   // Check RHS for vnot
17903   if (N1.getOpcode() == ISD::XOR &&
17904       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17905       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17906     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17907
17908   return SDValue();
17909 }
17910
17911 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17912                                 TargetLowering::DAGCombinerInfo &DCI,
17913                                 const X86Subtarget *Subtarget) {
17914   EVT VT = N->getValueType(0);
17915   if (DCI.isBeforeLegalizeOps())
17916     return SDValue();
17917
17918   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17919   if (R.getNode())
17920     return R;
17921
17922   SDValue N0 = N->getOperand(0);
17923   SDValue N1 = N->getOperand(1);
17924
17925   // look for psign/blend
17926   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17927     if (!Subtarget->hasSSSE3() ||
17928         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17929       return SDValue();
17930
17931     // Canonicalize pandn to RHS
17932     if (N0.getOpcode() == X86ISD::ANDNP)
17933       std::swap(N0, N1);
17934     // or (and (m, y), (pandn m, x))
17935     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17936       SDValue Mask = N1.getOperand(0);
17937       SDValue X    = N1.getOperand(1);
17938       SDValue Y;
17939       if (N0.getOperand(0) == Mask)
17940         Y = N0.getOperand(1);
17941       if (N0.getOperand(1) == Mask)
17942         Y = N0.getOperand(0);
17943
17944       // Check to see if the mask appeared in both the AND and ANDNP and
17945       if (!Y.getNode())
17946         return SDValue();
17947
17948       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17949       // Look through mask bitcast.
17950       if (Mask.getOpcode() == ISD::BITCAST)
17951         Mask = Mask.getOperand(0);
17952       if (X.getOpcode() == ISD::BITCAST)
17953         X = X.getOperand(0);
17954       if (Y.getOpcode() == ISD::BITCAST)
17955         Y = Y.getOperand(0);
17956
17957       EVT MaskVT = Mask.getValueType();
17958
17959       // Validate that the Mask operand is a vector sra node.
17960       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17961       // there is no psrai.b
17962       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17963       unsigned SraAmt = ~0;
17964       if (Mask.getOpcode() == ISD::SRA) {
17965         SDValue Amt = Mask.getOperand(1);
17966         if (isSplatVector(Amt.getNode())) {
17967           SDValue SclrAmt = Amt->getOperand(0);
17968           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17969             SraAmt = C->getZExtValue();
17970         }
17971       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17972         SDValue SraC = Mask.getOperand(1);
17973         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
17974       }
17975       if ((SraAmt + 1) != EltBits)
17976         return SDValue();
17977
17978       SDLoc DL(N);
17979
17980       // Now we know we at least have a plendvb with the mask val.  See if
17981       // we can form a psignb/w/d.
17982       // psign = x.type == y.type == mask.type && y = sub(0, x);
17983       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17984           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17985           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17986         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17987                "Unsupported VT for PSIGN");
17988         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17989         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17990       }
17991       // PBLENDVB only available on SSE 4.1
17992       if (!Subtarget->hasSSE41())
17993         return SDValue();
17994
17995       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17996
17997       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17998       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17999       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18000       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18001       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18002     }
18003   }
18004
18005   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18006     return SDValue();
18007
18008   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18009   MachineFunction &MF = DAG.getMachineFunction();
18010   bool OptForSize = MF.getFunction()->getAttributes().
18011     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18012
18013   // SHLD/SHRD instructions have lower register pressure, but on some
18014   // platforms they have higher latency than the equivalent
18015   // series of shifts/or that would otherwise be generated.
18016   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18017   // have higher latencies and we are not optimizing for size.
18018   if (!OptForSize && Subtarget->isSHLDSlow())
18019     return SDValue();
18020
18021   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18022     std::swap(N0, N1);
18023   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18024     return SDValue();
18025   if (!N0.hasOneUse() || !N1.hasOneUse())
18026     return SDValue();
18027
18028   SDValue ShAmt0 = N0.getOperand(1);
18029   if (ShAmt0.getValueType() != MVT::i8)
18030     return SDValue();
18031   SDValue ShAmt1 = N1.getOperand(1);
18032   if (ShAmt1.getValueType() != MVT::i8)
18033     return SDValue();
18034   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18035     ShAmt0 = ShAmt0.getOperand(0);
18036   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18037     ShAmt1 = ShAmt1.getOperand(0);
18038
18039   SDLoc DL(N);
18040   unsigned Opc = X86ISD::SHLD;
18041   SDValue Op0 = N0.getOperand(0);
18042   SDValue Op1 = N1.getOperand(0);
18043   if (ShAmt0.getOpcode() == ISD::SUB) {
18044     Opc = X86ISD::SHRD;
18045     std::swap(Op0, Op1);
18046     std::swap(ShAmt0, ShAmt1);
18047   }
18048
18049   unsigned Bits = VT.getSizeInBits();
18050   if (ShAmt1.getOpcode() == ISD::SUB) {
18051     SDValue Sum = ShAmt1.getOperand(0);
18052     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18053       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18054       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18055         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18056       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18057         return DAG.getNode(Opc, DL, VT,
18058                            Op0, Op1,
18059                            DAG.getNode(ISD::TRUNCATE, DL,
18060                                        MVT::i8, ShAmt0));
18061     }
18062   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18063     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18064     if (ShAmt0C &&
18065         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18066       return DAG.getNode(Opc, DL, VT,
18067                          N0.getOperand(0), N1.getOperand(0),
18068                          DAG.getNode(ISD::TRUNCATE, DL,
18069                                        MVT::i8, ShAmt0));
18070   }
18071
18072   return SDValue();
18073 }
18074
18075 // Generate NEG and CMOV for integer abs.
18076 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18077   EVT VT = N->getValueType(0);
18078
18079   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18080   // 8-bit integer abs to NEG and CMOV.
18081   if (VT.isInteger() && VT.getSizeInBits() == 8)
18082     return SDValue();
18083
18084   SDValue N0 = N->getOperand(0);
18085   SDValue N1 = N->getOperand(1);
18086   SDLoc DL(N);
18087
18088   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18089   // and change it to SUB and CMOV.
18090   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18091       N0.getOpcode() == ISD::ADD &&
18092       N0.getOperand(1) == N1 &&
18093       N1.getOpcode() == ISD::SRA &&
18094       N1.getOperand(0) == N0.getOperand(0))
18095     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18096       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18097         // Generate SUB & CMOV.
18098         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18099                                   DAG.getConstant(0, VT), N0.getOperand(0));
18100
18101         SDValue Ops[] = { N0.getOperand(0), Neg,
18102                           DAG.getConstant(X86::COND_GE, MVT::i8),
18103                           SDValue(Neg.getNode(), 1) };
18104         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18105                            Ops, array_lengthof(Ops));
18106       }
18107   return SDValue();
18108 }
18109
18110 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18111 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18112                                  TargetLowering::DAGCombinerInfo &DCI,
18113                                  const X86Subtarget *Subtarget) {
18114   EVT VT = N->getValueType(0);
18115   if (DCI.isBeforeLegalizeOps())
18116     return SDValue();
18117
18118   if (Subtarget->hasCMov()) {
18119     SDValue RV = performIntegerAbsCombine(N, DAG);
18120     if (RV.getNode())
18121       return RV;
18122   }
18123
18124   // Try forming BMI if it is available.
18125   if (!Subtarget->hasBMI())
18126     return SDValue();
18127
18128   if (VT != MVT::i32 && VT != MVT::i64)
18129     return SDValue();
18130
18131   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
18132
18133   // Create BLSMSK instructions by finding X ^ (X-1)
18134   SDValue N0 = N->getOperand(0);
18135   SDValue N1 = N->getOperand(1);
18136   SDLoc DL(N);
18137
18138   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
18139       isAllOnes(N0.getOperand(1)))
18140     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
18141
18142   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
18143       isAllOnes(N1.getOperand(1)))
18144     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
18145
18146   return SDValue();
18147 }
18148
18149 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18150 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18151                                   TargetLowering::DAGCombinerInfo &DCI,
18152                                   const X86Subtarget *Subtarget) {
18153   LoadSDNode *Ld = cast<LoadSDNode>(N);
18154   EVT RegVT = Ld->getValueType(0);
18155   EVT MemVT = Ld->getMemoryVT();
18156   SDLoc dl(Ld);
18157   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18158   unsigned RegSz = RegVT.getSizeInBits();
18159
18160   // On Sandybridge unaligned 256bit loads are inefficient.
18161   ISD::LoadExtType Ext = Ld->getExtensionType();
18162   unsigned Alignment = Ld->getAlignment();
18163   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18164   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18165       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18166     unsigned NumElems = RegVT.getVectorNumElements();
18167     if (NumElems < 2)
18168       return SDValue();
18169
18170     SDValue Ptr = Ld->getBasePtr();
18171     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18172
18173     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18174                                   NumElems/2);
18175     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18176                                 Ld->getPointerInfo(), Ld->isVolatile(),
18177                                 Ld->isNonTemporal(), Ld->isInvariant(),
18178                                 Alignment);
18179     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18180     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18181                                 Ld->getPointerInfo(), Ld->isVolatile(),
18182                                 Ld->isNonTemporal(), Ld->isInvariant(),
18183                                 std::min(16U, Alignment));
18184     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18185                              Load1.getValue(1),
18186                              Load2.getValue(1));
18187
18188     SDValue NewVec = DAG.getUNDEF(RegVT);
18189     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18190     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18191     return DCI.CombineTo(N, NewVec, TF, true);
18192   }
18193
18194   // If this is a vector EXT Load then attempt to optimize it using a
18195   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18196   // expansion is still better than scalar code.
18197   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18198   // emit a shuffle and a arithmetic shift.
18199   // TODO: It is possible to support ZExt by zeroing the undef values
18200   // during the shuffle phase or after the shuffle.
18201   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18202       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18203     assert(MemVT != RegVT && "Cannot extend to the same type");
18204     assert(MemVT.isVector() && "Must load a vector from memory");
18205
18206     unsigned NumElems = RegVT.getVectorNumElements();
18207     unsigned MemSz = MemVT.getSizeInBits();
18208     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18209
18210     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18211       return SDValue();
18212
18213     // All sizes must be a power of two.
18214     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18215       return SDValue();
18216
18217     // Attempt to load the original value using scalar loads.
18218     // Find the largest scalar type that divides the total loaded size.
18219     MVT SclrLoadTy = MVT::i8;
18220     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18221          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18222       MVT Tp = (MVT::SimpleValueType)tp;
18223       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18224         SclrLoadTy = Tp;
18225       }
18226     }
18227
18228     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18229     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18230         (64 <= MemSz))
18231       SclrLoadTy = MVT::f64;
18232
18233     // Calculate the number of scalar loads that we need to perform
18234     // in order to load our vector from memory.
18235     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18236     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18237       return SDValue();
18238
18239     unsigned loadRegZize = RegSz;
18240     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18241       loadRegZize /= 2;
18242
18243     // Represent our vector as a sequence of elements which are the
18244     // largest scalar that we can load.
18245     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18246       loadRegZize/SclrLoadTy.getSizeInBits());
18247
18248     // Represent the data using the same element type that is stored in
18249     // memory. In practice, we ''widen'' MemVT.
18250     EVT WideVecVT =
18251           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18252                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18253
18254     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18255       "Invalid vector type");
18256
18257     // We can't shuffle using an illegal type.
18258     if (!TLI.isTypeLegal(WideVecVT))
18259       return SDValue();
18260
18261     SmallVector<SDValue, 8> Chains;
18262     SDValue Ptr = Ld->getBasePtr();
18263     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18264                                         TLI.getPointerTy());
18265     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18266
18267     for (unsigned i = 0; i < NumLoads; ++i) {
18268       // Perform a single load.
18269       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18270                                        Ptr, Ld->getPointerInfo(),
18271                                        Ld->isVolatile(), Ld->isNonTemporal(),
18272                                        Ld->isInvariant(), Ld->getAlignment());
18273       Chains.push_back(ScalarLoad.getValue(1));
18274       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18275       // another round of DAGCombining.
18276       if (i == 0)
18277         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18278       else
18279         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18280                           ScalarLoad, DAG.getIntPtrConstant(i));
18281
18282       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18283     }
18284
18285     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18286                                Chains.size());
18287
18288     // Bitcast the loaded value to a vector of the original element type, in
18289     // the size of the target vector type.
18290     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18291     unsigned SizeRatio = RegSz/MemSz;
18292
18293     if (Ext == ISD::SEXTLOAD) {
18294       // If we have SSE4.1 we can directly emit a VSEXT node.
18295       if (Subtarget->hasSSE41()) {
18296         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18297         return DCI.CombineTo(N, Sext, TF, true);
18298       }
18299
18300       // Otherwise we'll shuffle the small elements in the high bits of the
18301       // larger type and perform an arithmetic shift. If the shift is not legal
18302       // it's better to scalarize.
18303       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18304         return SDValue();
18305
18306       // Redistribute the loaded elements into the different locations.
18307       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18308       for (unsigned i = 0; i != NumElems; ++i)
18309         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18310
18311       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18312                                            DAG.getUNDEF(WideVecVT),
18313                                            &ShuffleVec[0]);
18314
18315       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18316
18317       // Build the arithmetic shift.
18318       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18319                      MemVT.getVectorElementType().getSizeInBits();
18320       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18321                           DAG.getConstant(Amt, RegVT));
18322
18323       return DCI.CombineTo(N, Shuff, TF, true);
18324     }
18325
18326     // Redistribute the loaded elements into the different locations.
18327     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18328     for (unsigned i = 0; i != NumElems; ++i)
18329       ShuffleVec[i*SizeRatio] = i;
18330
18331     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18332                                          DAG.getUNDEF(WideVecVT),
18333                                          &ShuffleVec[0]);
18334
18335     // Bitcast to the requested type.
18336     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18337     // Replace the original load with the new sequence
18338     // and return the new chain.
18339     return DCI.CombineTo(N, Shuff, TF, true);
18340   }
18341
18342   return SDValue();
18343 }
18344
18345 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18346 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18347                                    const X86Subtarget *Subtarget) {
18348   StoreSDNode *St = cast<StoreSDNode>(N);
18349   EVT VT = St->getValue().getValueType();
18350   EVT StVT = St->getMemoryVT();
18351   SDLoc dl(St);
18352   SDValue StoredVal = St->getOperand(1);
18353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18354
18355   // If we are saving a concatenation of two XMM registers, perform two stores.
18356   // On Sandy Bridge, 256-bit memory operations are executed by two
18357   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18358   // memory  operation.
18359   unsigned Alignment = St->getAlignment();
18360   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18361   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18362       StVT == VT && !IsAligned) {
18363     unsigned NumElems = VT.getVectorNumElements();
18364     if (NumElems < 2)
18365       return SDValue();
18366
18367     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18368     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18369
18370     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18371     SDValue Ptr0 = St->getBasePtr();
18372     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18373
18374     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18375                                 St->getPointerInfo(), St->isVolatile(),
18376                                 St->isNonTemporal(), Alignment);
18377     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18378                                 St->getPointerInfo(), St->isVolatile(),
18379                                 St->isNonTemporal(),
18380                                 std::min(16U, Alignment));
18381     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18382   }
18383
18384   // Optimize trunc store (of multiple scalars) to shuffle and store.
18385   // First, pack all of the elements in one place. Next, store to memory
18386   // in fewer chunks.
18387   if (St->isTruncatingStore() && VT.isVector()) {
18388     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18389     unsigned NumElems = VT.getVectorNumElements();
18390     assert(StVT != VT && "Cannot truncate to the same type");
18391     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18392     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18393
18394     // From, To sizes and ElemCount must be pow of two
18395     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18396     // We are going to use the original vector elt for storing.
18397     // Accumulated smaller vector elements must be a multiple of the store size.
18398     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18399
18400     unsigned SizeRatio  = FromSz / ToSz;
18401
18402     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18403
18404     // Create a type on which we perform the shuffle
18405     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18406             StVT.getScalarType(), NumElems*SizeRatio);
18407
18408     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18409
18410     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18411     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18412     for (unsigned i = 0; i != NumElems; ++i)
18413       ShuffleVec[i] = i * SizeRatio;
18414
18415     // Can't shuffle using an illegal type.
18416     if (!TLI.isTypeLegal(WideVecVT))
18417       return SDValue();
18418
18419     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18420                                          DAG.getUNDEF(WideVecVT),
18421                                          &ShuffleVec[0]);
18422     // At this point all of the data is stored at the bottom of the
18423     // register. We now need to save it to mem.
18424
18425     // Find the largest store unit
18426     MVT StoreType = MVT::i8;
18427     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18428          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18429       MVT Tp = (MVT::SimpleValueType)tp;
18430       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18431         StoreType = Tp;
18432     }
18433
18434     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18435     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18436         (64 <= NumElems * ToSz))
18437       StoreType = MVT::f64;
18438
18439     // Bitcast the original vector into a vector of store-size units
18440     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18441             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18442     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18443     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18444     SmallVector<SDValue, 8> Chains;
18445     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18446                                         TLI.getPointerTy());
18447     SDValue Ptr = St->getBasePtr();
18448
18449     // Perform one or more big stores into memory.
18450     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18451       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18452                                    StoreType, ShuffWide,
18453                                    DAG.getIntPtrConstant(i));
18454       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18455                                 St->getPointerInfo(), St->isVolatile(),
18456                                 St->isNonTemporal(), St->getAlignment());
18457       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18458       Chains.push_back(Ch);
18459     }
18460
18461     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18462                                Chains.size());
18463   }
18464
18465   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18466   // the FP state in cases where an emms may be missing.
18467   // A preferable solution to the general problem is to figure out the right
18468   // places to insert EMMS.  This qualifies as a quick hack.
18469
18470   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18471   if (VT.getSizeInBits() != 64)
18472     return SDValue();
18473
18474   const Function *F = DAG.getMachineFunction().getFunction();
18475   bool NoImplicitFloatOps = F->getAttributes().
18476     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18477   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18478                      && Subtarget->hasSSE2();
18479   if ((VT.isVector() ||
18480        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18481       isa<LoadSDNode>(St->getValue()) &&
18482       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18483       St->getChain().hasOneUse() && !St->isVolatile()) {
18484     SDNode* LdVal = St->getValue().getNode();
18485     LoadSDNode *Ld = 0;
18486     int TokenFactorIndex = -1;
18487     SmallVector<SDValue, 8> Ops;
18488     SDNode* ChainVal = St->getChain().getNode();
18489     // Must be a store of a load.  We currently handle two cases:  the load
18490     // is a direct child, and it's under an intervening TokenFactor.  It is
18491     // possible to dig deeper under nested TokenFactors.
18492     if (ChainVal == LdVal)
18493       Ld = cast<LoadSDNode>(St->getChain());
18494     else if (St->getValue().hasOneUse() &&
18495              ChainVal->getOpcode() == ISD::TokenFactor) {
18496       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18497         if (ChainVal->getOperand(i).getNode() == LdVal) {
18498           TokenFactorIndex = i;
18499           Ld = cast<LoadSDNode>(St->getValue());
18500         } else
18501           Ops.push_back(ChainVal->getOperand(i));
18502       }
18503     }
18504
18505     if (!Ld || !ISD::isNormalLoad(Ld))
18506       return SDValue();
18507
18508     // If this is not the MMX case, i.e. we are just turning i64 load/store
18509     // into f64 load/store, avoid the transformation if there are multiple
18510     // uses of the loaded value.
18511     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18512       return SDValue();
18513
18514     SDLoc LdDL(Ld);
18515     SDLoc StDL(N);
18516     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18517     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18518     // pair instead.
18519     if (Subtarget->is64Bit() || F64IsLegal) {
18520       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18521       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18522                                   Ld->getPointerInfo(), Ld->isVolatile(),
18523                                   Ld->isNonTemporal(), Ld->isInvariant(),
18524                                   Ld->getAlignment());
18525       SDValue NewChain = NewLd.getValue(1);
18526       if (TokenFactorIndex != -1) {
18527         Ops.push_back(NewChain);
18528         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18529                                Ops.size());
18530       }
18531       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18532                           St->getPointerInfo(),
18533                           St->isVolatile(), St->isNonTemporal(),
18534                           St->getAlignment());
18535     }
18536
18537     // Otherwise, lower to two pairs of 32-bit loads / stores.
18538     SDValue LoAddr = Ld->getBasePtr();
18539     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18540                                  DAG.getConstant(4, MVT::i32));
18541
18542     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18543                                Ld->getPointerInfo(),
18544                                Ld->isVolatile(), Ld->isNonTemporal(),
18545                                Ld->isInvariant(), Ld->getAlignment());
18546     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18547                                Ld->getPointerInfo().getWithOffset(4),
18548                                Ld->isVolatile(), Ld->isNonTemporal(),
18549                                Ld->isInvariant(),
18550                                MinAlign(Ld->getAlignment(), 4));
18551
18552     SDValue NewChain = LoLd.getValue(1);
18553     if (TokenFactorIndex != -1) {
18554       Ops.push_back(LoLd);
18555       Ops.push_back(HiLd);
18556       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18557                              Ops.size());
18558     }
18559
18560     LoAddr = St->getBasePtr();
18561     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18562                          DAG.getConstant(4, MVT::i32));
18563
18564     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18565                                 St->getPointerInfo(),
18566                                 St->isVolatile(), St->isNonTemporal(),
18567                                 St->getAlignment());
18568     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18569                                 St->getPointerInfo().getWithOffset(4),
18570                                 St->isVolatile(),
18571                                 St->isNonTemporal(),
18572                                 MinAlign(St->getAlignment(), 4));
18573     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18574   }
18575   return SDValue();
18576 }
18577
18578 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18579 /// and return the operands for the horizontal operation in LHS and RHS.  A
18580 /// horizontal operation performs the binary operation on successive elements
18581 /// of its first operand, then on successive elements of its second operand,
18582 /// returning the resulting values in a vector.  For example, if
18583 ///   A = < float a0, float a1, float a2, float a3 >
18584 /// and
18585 ///   B = < float b0, float b1, float b2, float b3 >
18586 /// then the result of doing a horizontal operation on A and B is
18587 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18588 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18589 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18590 /// set to A, RHS to B, and the routine returns 'true'.
18591 /// Note that the binary operation should have the property that if one of the
18592 /// operands is UNDEF then the result is UNDEF.
18593 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18594   // Look for the following pattern: if
18595   //   A = < float a0, float a1, float a2, float a3 >
18596   //   B = < float b0, float b1, float b2, float b3 >
18597   // and
18598   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18599   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18600   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18601   // which is A horizontal-op B.
18602
18603   // At least one of the operands should be a vector shuffle.
18604   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18605       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18606     return false;
18607
18608   MVT VT = LHS.getSimpleValueType();
18609
18610   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18611          "Unsupported vector type for horizontal add/sub");
18612
18613   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18614   // operate independently on 128-bit lanes.
18615   unsigned NumElts = VT.getVectorNumElements();
18616   unsigned NumLanes = VT.getSizeInBits()/128;
18617   unsigned NumLaneElts = NumElts / NumLanes;
18618   assert((NumLaneElts % 2 == 0) &&
18619          "Vector type should have an even number of elements in each lane");
18620   unsigned HalfLaneElts = NumLaneElts/2;
18621
18622   // View LHS in the form
18623   //   LHS = VECTOR_SHUFFLE A, B, LMask
18624   // If LHS is not a shuffle then pretend it is the shuffle
18625   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18626   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18627   // type VT.
18628   SDValue A, B;
18629   SmallVector<int, 16> LMask(NumElts);
18630   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18631     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18632       A = LHS.getOperand(0);
18633     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18634       B = LHS.getOperand(1);
18635     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18636     std::copy(Mask.begin(), Mask.end(), LMask.begin());
18637   } else {
18638     if (LHS.getOpcode() != ISD::UNDEF)
18639       A = LHS;
18640     for (unsigned i = 0; i != NumElts; ++i)
18641       LMask[i] = i;
18642   }
18643
18644   // Likewise, view RHS in the form
18645   //   RHS = VECTOR_SHUFFLE C, D, RMask
18646   SDValue C, D;
18647   SmallVector<int, 16> RMask(NumElts);
18648   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18649     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
18650       C = RHS.getOperand(0);
18651     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
18652       D = RHS.getOperand(1);
18653     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
18654     std::copy(Mask.begin(), Mask.end(), RMask.begin());
18655   } else {
18656     if (RHS.getOpcode() != ISD::UNDEF)
18657       C = RHS;
18658     for (unsigned i = 0; i != NumElts; ++i)
18659       RMask[i] = i;
18660   }
18661
18662   // Check that the shuffles are both shuffling the same vectors.
18663   if (!(A == C && B == D) && !(A == D && B == C))
18664     return false;
18665
18666   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
18667   if (!A.getNode() && !B.getNode())
18668     return false;
18669
18670   // If A and B occur in reverse order in RHS, then "swap" them (which means
18671   // rewriting the mask).
18672   if (A != C)
18673     CommuteVectorShuffleMask(RMask, NumElts);
18674
18675   // At this point LHS and RHS are equivalent to
18676   //   LHS = VECTOR_SHUFFLE A, B, LMask
18677   //   RHS = VECTOR_SHUFFLE A, B, RMask
18678   // Check that the masks correspond to performing a horizontal operation.
18679   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
18680     for (unsigned i = 0; i != NumLaneElts; ++i) {
18681       int LIdx = LMask[i+l], RIdx = RMask[i+l];
18682
18683       // Ignore any UNDEF components.
18684       if (LIdx < 0 || RIdx < 0 ||
18685           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
18686           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
18687         continue;
18688
18689       // Check that successive elements are being operated on.  If not, this is
18690       // not a horizontal operation.
18691       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
18692       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
18693       if (!(LIdx == Index && RIdx == Index + 1) &&
18694           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
18695         return false;
18696     }
18697   }
18698
18699   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
18700   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
18701   return true;
18702 }
18703
18704 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
18705 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
18706                                   const X86Subtarget *Subtarget) {
18707   EVT VT = N->getValueType(0);
18708   SDValue LHS = N->getOperand(0);
18709   SDValue RHS = N->getOperand(1);
18710
18711   // Try to synthesize horizontal adds from adds of shuffles.
18712   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18713        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18714       isHorizontalBinOp(LHS, RHS, true))
18715     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
18716   return SDValue();
18717 }
18718
18719 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
18720 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
18721                                   const X86Subtarget *Subtarget) {
18722   EVT VT = N->getValueType(0);
18723   SDValue LHS = N->getOperand(0);
18724   SDValue RHS = N->getOperand(1);
18725
18726   // Try to synthesize horizontal subs from subs of shuffles.
18727   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18728        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18729       isHorizontalBinOp(LHS, RHS, false))
18730     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18731   return SDValue();
18732 }
18733
18734 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18735 /// X86ISD::FXOR nodes.
18736 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18737   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18738   // F[X]OR(0.0, x) -> x
18739   // F[X]OR(x, 0.0) -> x
18740   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18741     if (C->getValueAPF().isPosZero())
18742       return N->getOperand(1);
18743   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18744     if (C->getValueAPF().isPosZero())
18745       return N->getOperand(0);
18746   return SDValue();
18747 }
18748
18749 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18750 /// X86ISD::FMAX nodes.
18751 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18752   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18753
18754   // Only perform optimizations if UnsafeMath is used.
18755   if (!DAG.getTarget().Options.UnsafeFPMath)
18756     return SDValue();
18757
18758   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18759   // into FMINC and FMAXC, which are Commutative operations.
18760   unsigned NewOp = 0;
18761   switch (N->getOpcode()) {
18762     default: llvm_unreachable("unknown opcode");
18763     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
18764     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
18765   }
18766
18767   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18768                      N->getOperand(0), N->getOperand(1));
18769 }
18770
18771 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18772 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18773   // FAND(0.0, x) -> 0.0
18774   // FAND(x, 0.0) -> 0.0
18775   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18776     if (C->getValueAPF().isPosZero())
18777       return N->getOperand(0);
18778   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18779     if (C->getValueAPF().isPosZero())
18780       return N->getOperand(1);
18781   return SDValue();
18782 }
18783
18784 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18785 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18786   // FANDN(x, 0.0) -> 0.0
18787   // FANDN(0.0, x) -> x
18788   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18789     if (C->getValueAPF().isPosZero())
18790       return N->getOperand(1);
18791   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18792     if (C->getValueAPF().isPosZero())
18793       return N->getOperand(1);
18794   return SDValue();
18795 }
18796
18797 static SDValue PerformBTCombine(SDNode *N,
18798                                 SelectionDAG &DAG,
18799                                 TargetLowering::DAGCombinerInfo &DCI) {
18800   // BT ignores high bits in the bit index operand.
18801   SDValue Op1 = N->getOperand(1);
18802   if (Op1.hasOneUse()) {
18803     unsigned BitWidth = Op1.getValueSizeInBits();
18804     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18805     APInt KnownZero, KnownOne;
18806     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18807                                           !DCI.isBeforeLegalizeOps());
18808     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18809     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18810         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18811       DCI.CommitTargetLoweringOpt(TLO);
18812   }
18813   return SDValue();
18814 }
18815
18816 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18817   SDValue Op = N->getOperand(0);
18818   if (Op.getOpcode() == ISD::BITCAST)
18819     Op = Op.getOperand(0);
18820   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18821   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18822       VT.getVectorElementType().getSizeInBits() ==
18823       OpVT.getVectorElementType().getSizeInBits()) {
18824     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18825   }
18826   return SDValue();
18827 }
18828
18829 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18830                                                const X86Subtarget *Subtarget) {
18831   EVT VT = N->getValueType(0);
18832   if (!VT.isVector())
18833     return SDValue();
18834
18835   SDValue N0 = N->getOperand(0);
18836   SDValue N1 = N->getOperand(1);
18837   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18838   SDLoc dl(N);
18839
18840   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18841   // both SSE and AVX2 since there is no sign-extended shift right
18842   // operation on a vector with 64-bit elements.
18843   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18844   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18845   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18846       N0.getOpcode() == ISD::SIGN_EXTEND)) {
18847     SDValue N00 = N0.getOperand(0);
18848
18849     // EXTLOAD has a better solution on AVX2,
18850     // it may be replaced with X86ISD::VSEXT node.
18851     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18852       if (!ISD::isNormalLoad(N00.getNode()))
18853         return SDValue();
18854
18855     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18856         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18857                                   N00, N1);
18858       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18859     }
18860   }
18861   return SDValue();
18862 }
18863
18864 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18865                                   TargetLowering::DAGCombinerInfo &DCI,
18866                                   const X86Subtarget *Subtarget) {
18867   if (!DCI.isBeforeLegalizeOps())
18868     return SDValue();
18869
18870   if (!Subtarget->hasFp256())
18871     return SDValue();
18872
18873   EVT VT = N->getValueType(0);
18874   if (VT.isVector() && VT.getSizeInBits() == 256) {
18875     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18876     if (R.getNode())
18877       return R;
18878   }
18879
18880   return SDValue();
18881 }
18882
18883 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18884                                  const X86Subtarget* Subtarget) {
18885   SDLoc dl(N);
18886   EVT VT = N->getValueType(0);
18887
18888   // Let legalize expand this if it isn't a legal type yet.
18889   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18890     return SDValue();
18891
18892   EVT ScalarVT = VT.getScalarType();
18893   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18894       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18895     return SDValue();
18896
18897   SDValue A = N->getOperand(0);
18898   SDValue B = N->getOperand(1);
18899   SDValue C = N->getOperand(2);
18900
18901   bool NegA = (A.getOpcode() == ISD::FNEG);
18902   bool NegB = (B.getOpcode() == ISD::FNEG);
18903   bool NegC = (C.getOpcode() == ISD::FNEG);
18904
18905   // Negative multiplication when NegA xor NegB
18906   bool NegMul = (NegA != NegB);
18907   if (NegA)
18908     A = A.getOperand(0);
18909   if (NegB)
18910     B = B.getOperand(0);
18911   if (NegC)
18912     C = C.getOperand(0);
18913
18914   unsigned Opcode;
18915   if (!NegMul)
18916     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18917   else
18918     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18919
18920   return DAG.getNode(Opcode, dl, VT, A, B, C);
18921 }
18922
18923 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18924                                   TargetLowering::DAGCombinerInfo &DCI,
18925                                   const X86Subtarget *Subtarget) {
18926   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18927   //           (and (i32 x86isd::setcc_carry), 1)
18928   // This eliminates the zext. This transformation is necessary because
18929   // ISD::SETCC is always legalized to i8.
18930   SDLoc dl(N);
18931   SDValue N0 = N->getOperand(0);
18932   EVT VT = N->getValueType(0);
18933
18934   if (N0.getOpcode() == ISD::AND &&
18935       N0.hasOneUse() &&
18936       N0.getOperand(0).hasOneUse()) {
18937     SDValue N00 = N0.getOperand(0);
18938     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18939       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18940       if (!C || C->getZExtValue() != 1)
18941         return SDValue();
18942       return DAG.getNode(ISD::AND, dl, VT,
18943                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18944                                      N00.getOperand(0), N00.getOperand(1)),
18945                          DAG.getConstant(1, VT));
18946     }
18947   }
18948
18949   if (VT.is256BitVector()) {
18950     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18951     if (R.getNode())
18952       return R;
18953   }
18954
18955   return SDValue();
18956 }
18957
18958 // Optimize x == -y --> x+y == 0
18959 //          x != -y --> x+y != 0
18960 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18961   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18962   SDValue LHS = N->getOperand(0);
18963   SDValue RHS = N->getOperand(1);
18964
18965   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18966     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18967       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18968         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18969                                    LHS.getValueType(), RHS, LHS.getOperand(1));
18970         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18971                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18972       }
18973   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18974     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18975       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18976         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18977                                    RHS.getValueType(), LHS, RHS.getOperand(1));
18978         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18979                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18980       }
18981   return SDValue();
18982 }
18983
18984 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18985 // as "sbb reg,reg", since it can be extended without zext and produces
18986 // an all-ones bit which is more useful than 0/1 in some cases.
18987 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18988   return DAG.getNode(ISD::AND, DL, MVT::i8,
18989                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18990                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18991                      DAG.getConstant(1, MVT::i8));
18992 }
18993
18994 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18995 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18996                                    TargetLowering::DAGCombinerInfo &DCI,
18997                                    const X86Subtarget *Subtarget) {
18998   SDLoc DL(N);
18999   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19000   SDValue EFLAGS = N->getOperand(1);
19001
19002   if (CC == X86::COND_A) {
19003     // Try to convert COND_A into COND_B in an attempt to facilitate
19004     // materializing "setb reg".
19005     //
19006     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19007     // cannot take an immediate as its first operand.
19008     //
19009     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19010         EFLAGS.getValueType().isInteger() &&
19011         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19012       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19013                                    EFLAGS.getNode()->getVTList(),
19014                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19015       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19016       return MaterializeSETB(DL, NewEFLAGS, DAG);
19017     }
19018   }
19019
19020   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19021   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19022   // cases.
19023   if (CC == X86::COND_B)
19024     return MaterializeSETB(DL, EFLAGS, DAG);
19025
19026   SDValue Flags;
19027
19028   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19029   if (Flags.getNode()) {
19030     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19031     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19032   }
19033
19034   return SDValue();
19035 }
19036
19037 // Optimize branch condition evaluation.
19038 //
19039 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19040                                     TargetLowering::DAGCombinerInfo &DCI,
19041                                     const X86Subtarget *Subtarget) {
19042   SDLoc DL(N);
19043   SDValue Chain = N->getOperand(0);
19044   SDValue Dest = N->getOperand(1);
19045   SDValue EFLAGS = N->getOperand(3);
19046   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19047
19048   SDValue Flags;
19049
19050   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19051   if (Flags.getNode()) {
19052     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19053     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19054                        Flags);
19055   }
19056
19057   return SDValue();
19058 }
19059
19060 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19061                                         const X86TargetLowering *XTLI) {
19062   SDValue Op0 = N->getOperand(0);
19063   EVT InVT = Op0->getValueType(0);
19064
19065   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19066   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19067     SDLoc dl(N);
19068     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19069     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19070     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19071   }
19072
19073   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19074   // a 32-bit target where SSE doesn't support i64->FP operations.
19075   if (Op0.getOpcode() == ISD::LOAD) {
19076     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19077     EVT VT = Ld->getValueType(0);
19078     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19079         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19080         !XTLI->getSubtarget()->is64Bit() &&
19081         VT == MVT::i64) {
19082       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19083                                           Ld->getChain(), Op0, DAG);
19084       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19085       return FILDChain;
19086     }
19087   }
19088   return SDValue();
19089 }
19090
19091 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19092 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19093                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19094   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19095   // the result is either zero or one (depending on the input carry bit).
19096   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19097   if (X86::isZeroNode(N->getOperand(0)) &&
19098       X86::isZeroNode(N->getOperand(1)) &&
19099       // We don't have a good way to replace an EFLAGS use, so only do this when
19100       // dead right now.
19101       SDValue(N, 1).use_empty()) {
19102     SDLoc DL(N);
19103     EVT VT = N->getValueType(0);
19104     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19105     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19106                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19107                                            DAG.getConstant(X86::COND_B,MVT::i8),
19108                                            N->getOperand(2)),
19109                                DAG.getConstant(1, VT));
19110     return DCI.CombineTo(N, Res1, CarryOut);
19111   }
19112
19113   return SDValue();
19114 }
19115
19116 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19117 //      (add Y, (setne X, 0)) -> sbb -1, Y
19118 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19119 //      (sub (setne X, 0), Y) -> adc -1, Y
19120 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19121   SDLoc DL(N);
19122
19123   // Look through ZExts.
19124   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19125   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19126     return SDValue();
19127
19128   SDValue SetCC = Ext.getOperand(0);
19129   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19130     return SDValue();
19131
19132   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19133   if (CC != X86::COND_E && CC != X86::COND_NE)
19134     return SDValue();
19135
19136   SDValue Cmp = SetCC.getOperand(1);
19137   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19138       !X86::isZeroNode(Cmp.getOperand(1)) ||
19139       !Cmp.getOperand(0).getValueType().isInteger())
19140     return SDValue();
19141
19142   SDValue CmpOp0 = Cmp.getOperand(0);
19143   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19144                                DAG.getConstant(1, CmpOp0.getValueType()));
19145
19146   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19147   if (CC == X86::COND_NE)
19148     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19149                        DL, OtherVal.getValueType(), OtherVal,
19150                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19151   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19152                      DL, OtherVal.getValueType(), OtherVal,
19153                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19154 }
19155
19156 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19157 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19158                                  const X86Subtarget *Subtarget) {
19159   EVT VT = N->getValueType(0);
19160   SDValue Op0 = N->getOperand(0);
19161   SDValue Op1 = N->getOperand(1);
19162
19163   // Try to synthesize horizontal adds from adds of shuffles.
19164   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19165        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19166       isHorizontalBinOp(Op0, Op1, true))
19167     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19168
19169   return OptimizeConditionalInDecrement(N, DAG);
19170 }
19171
19172 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19173                                  const X86Subtarget *Subtarget) {
19174   SDValue Op0 = N->getOperand(0);
19175   SDValue Op1 = N->getOperand(1);
19176
19177   // X86 can't encode an immediate LHS of a sub. See if we can push the
19178   // negation into a preceding instruction.
19179   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19180     // If the RHS of the sub is a XOR with one use and a constant, invert the
19181     // immediate. Then add one to the LHS of the sub so we can turn
19182     // X-Y -> X+~Y+1, saving one register.
19183     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19184         isa<ConstantSDNode>(Op1.getOperand(1))) {
19185       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19186       EVT VT = Op0.getValueType();
19187       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19188                                    Op1.getOperand(0),
19189                                    DAG.getConstant(~XorC, VT));
19190       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19191                          DAG.getConstant(C->getAPIntValue()+1, VT));
19192     }
19193   }
19194
19195   // Try to synthesize horizontal adds from adds of shuffles.
19196   EVT VT = N->getValueType(0);
19197   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19198        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19199       isHorizontalBinOp(Op0, Op1, true))
19200     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19201
19202   return OptimizeConditionalInDecrement(N, DAG);
19203 }
19204
19205 /// performVZEXTCombine - Performs build vector combines
19206 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19207                                         TargetLowering::DAGCombinerInfo &DCI,
19208                                         const X86Subtarget *Subtarget) {
19209   // (vzext (bitcast (vzext (x)) -> (vzext x)
19210   SDValue In = N->getOperand(0);
19211   while (In.getOpcode() == ISD::BITCAST)
19212     In = In.getOperand(0);
19213
19214   if (In.getOpcode() != X86ISD::VZEXT)
19215     return SDValue();
19216
19217   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19218                      In.getOperand(0));
19219 }
19220
19221 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19222                                              DAGCombinerInfo &DCI) const {
19223   SelectionDAG &DAG = DCI.DAG;
19224   switch (N->getOpcode()) {
19225   default: break;
19226   case ISD::EXTRACT_VECTOR_ELT:
19227     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19228   case ISD::VSELECT:
19229   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19230   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19231   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19232   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19233   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19234   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19235   case ISD::SHL:
19236   case ISD::SRA:
19237   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19238   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19239   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19240   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19241   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19242   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19243   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19244   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19245   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19246   case X86ISD::FXOR:
19247   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19248   case X86ISD::FMIN:
19249   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19250   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19251   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19252   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19253   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19254   case ISD::ANY_EXTEND:
19255   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19256   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19257   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19258   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19259   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
19260   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19261   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19262   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19263   case X86ISD::SHUFP:       // Handle all target specific shuffles
19264   case X86ISD::PALIGNR:
19265   case X86ISD::UNPCKH:
19266   case X86ISD::UNPCKL:
19267   case X86ISD::MOVHLPS:
19268   case X86ISD::MOVLHPS:
19269   case X86ISD::PSHUFD:
19270   case X86ISD::PSHUFHW:
19271   case X86ISD::PSHUFLW:
19272   case X86ISD::MOVSS:
19273   case X86ISD::MOVSD:
19274   case X86ISD::VPERMILP:
19275   case X86ISD::VPERM2X128:
19276   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19277   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19278   }
19279
19280   return SDValue();
19281 }
19282
19283 /// isTypeDesirableForOp - Return true if the target has native support for
19284 /// the specified value type and it is 'desirable' to use the type for the
19285 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19286 /// instruction encodings are longer and some i16 instructions are slow.
19287 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19288   if (!isTypeLegal(VT))
19289     return false;
19290   if (VT != MVT::i16)
19291     return true;
19292
19293   switch (Opc) {
19294   default:
19295     return true;
19296   case ISD::LOAD:
19297   case ISD::SIGN_EXTEND:
19298   case ISD::ZERO_EXTEND:
19299   case ISD::ANY_EXTEND:
19300   case ISD::SHL:
19301   case ISD::SRL:
19302   case ISD::SUB:
19303   case ISD::ADD:
19304   case ISD::MUL:
19305   case ISD::AND:
19306   case ISD::OR:
19307   case ISD::XOR:
19308     return false;
19309   }
19310 }
19311
19312 /// IsDesirableToPromoteOp - This method query the target whether it is
19313 /// beneficial for dag combiner to promote the specified node. If true, it
19314 /// should return the desired promotion type by reference.
19315 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19316   EVT VT = Op.getValueType();
19317   if (VT != MVT::i16)
19318     return false;
19319
19320   bool Promote = false;
19321   bool Commute = false;
19322   switch (Op.getOpcode()) {
19323   default: break;
19324   case ISD::LOAD: {
19325     LoadSDNode *LD = cast<LoadSDNode>(Op);
19326     // If the non-extending load has a single use and it's not live out, then it
19327     // might be folded.
19328     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19329                                                      Op.hasOneUse()*/) {
19330       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19331              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19332         // The only case where we'd want to promote LOAD (rather then it being
19333         // promoted as an operand is when it's only use is liveout.
19334         if (UI->getOpcode() != ISD::CopyToReg)
19335           return false;
19336       }
19337     }
19338     Promote = true;
19339     break;
19340   }
19341   case ISD::SIGN_EXTEND:
19342   case ISD::ZERO_EXTEND:
19343   case ISD::ANY_EXTEND:
19344     Promote = true;
19345     break;
19346   case ISD::SHL:
19347   case ISD::SRL: {
19348     SDValue N0 = Op.getOperand(0);
19349     // Look out for (store (shl (load), x)).
19350     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19351       return false;
19352     Promote = true;
19353     break;
19354   }
19355   case ISD::ADD:
19356   case ISD::MUL:
19357   case ISD::AND:
19358   case ISD::OR:
19359   case ISD::XOR:
19360     Commute = true;
19361     // fallthrough
19362   case ISD::SUB: {
19363     SDValue N0 = Op.getOperand(0);
19364     SDValue N1 = Op.getOperand(1);
19365     if (!Commute && MayFoldLoad(N1))
19366       return false;
19367     // Avoid disabling potential load folding opportunities.
19368     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19369       return false;
19370     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19371       return false;
19372     Promote = true;
19373   }
19374   }
19375
19376   PVT = MVT::i32;
19377   return Promote;
19378 }
19379
19380 //===----------------------------------------------------------------------===//
19381 //                           X86 Inline Assembly Support
19382 //===----------------------------------------------------------------------===//
19383
19384 namespace {
19385   // Helper to match a string separated by whitespace.
19386   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19387     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19388
19389     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19390       StringRef piece(*args[i]);
19391       if (!s.startswith(piece)) // Check if the piece matches.
19392         return false;
19393
19394       s = s.substr(piece.size());
19395       StringRef::size_type pos = s.find_first_not_of(" \t");
19396       if (pos == 0) // We matched a prefix.
19397         return false;
19398
19399       s = s.substr(pos);
19400     }
19401
19402     return s.empty();
19403   }
19404   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19405 }
19406
19407 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19408
19409   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19410     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19411         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19412         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19413
19414       if (AsmPieces.size() == 3)
19415         return true;
19416       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19417         return true;
19418     }
19419   }
19420   return false;
19421 }
19422
19423 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19424   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19425
19426   std::string AsmStr = IA->getAsmString();
19427
19428   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19429   if (!Ty || Ty->getBitWidth() % 16 != 0)
19430     return false;
19431
19432   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19433   SmallVector<StringRef, 4> AsmPieces;
19434   SplitString(AsmStr, AsmPieces, ";\n");
19435
19436   switch (AsmPieces.size()) {
19437   default: return false;
19438   case 1:
19439     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19440     // we will turn this bswap into something that will be lowered to logical
19441     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19442     // lower so don't worry about this.
19443     // bswap $0
19444     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19445         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19446         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19447         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19448         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19449         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19450       // No need to check constraints, nothing other than the equivalent of
19451       // "=r,0" would be valid here.
19452       return IntrinsicLowering::LowerToByteSwap(CI);
19453     }
19454
19455     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19456     if (CI->getType()->isIntegerTy(16) &&
19457         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19458         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19459          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19460       AsmPieces.clear();
19461       const std::string &ConstraintsStr = IA->getConstraintString();
19462       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19463       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19464       if (clobbersFlagRegisters(AsmPieces))
19465         return IntrinsicLowering::LowerToByteSwap(CI);
19466     }
19467     break;
19468   case 3:
19469     if (CI->getType()->isIntegerTy(32) &&
19470         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19471         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19472         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19473         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19474       AsmPieces.clear();
19475       const std::string &ConstraintsStr = IA->getConstraintString();
19476       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19477       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19478       if (clobbersFlagRegisters(AsmPieces))
19479         return IntrinsicLowering::LowerToByteSwap(CI);
19480     }
19481
19482     if (CI->getType()->isIntegerTy(64)) {
19483       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19484       if (Constraints.size() >= 2 &&
19485           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19486           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19487         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19488         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19489             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19490             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19491           return IntrinsicLowering::LowerToByteSwap(CI);
19492       }
19493     }
19494     break;
19495   }
19496   return false;
19497 }
19498
19499 /// getConstraintType - Given a constraint letter, return the type of
19500 /// constraint it is for this target.
19501 X86TargetLowering::ConstraintType
19502 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19503   if (Constraint.size() == 1) {
19504     switch (Constraint[0]) {
19505     case 'R':
19506     case 'q':
19507     case 'Q':
19508     case 'f':
19509     case 't':
19510     case 'u':
19511     case 'y':
19512     case 'x':
19513     case 'Y':
19514     case 'l':
19515       return C_RegisterClass;
19516     case 'a':
19517     case 'b':
19518     case 'c':
19519     case 'd':
19520     case 'S':
19521     case 'D':
19522     case 'A':
19523       return C_Register;
19524     case 'I':
19525     case 'J':
19526     case 'K':
19527     case 'L':
19528     case 'M':
19529     case 'N':
19530     case 'G':
19531     case 'C':
19532     case 'e':
19533     case 'Z':
19534       return C_Other;
19535     default:
19536       break;
19537     }
19538   }
19539   return TargetLowering::getConstraintType(Constraint);
19540 }
19541
19542 /// Examine constraint type and operand type and determine a weight value.
19543 /// This object must already have been set up with the operand type
19544 /// and the current alternative constraint selected.
19545 TargetLowering::ConstraintWeight
19546   X86TargetLowering::getSingleConstraintMatchWeight(
19547     AsmOperandInfo &info, const char *constraint) const {
19548   ConstraintWeight weight = CW_Invalid;
19549   Value *CallOperandVal = info.CallOperandVal;
19550     // If we don't have a value, we can't do a match,
19551     // but allow it at the lowest weight.
19552   if (CallOperandVal == NULL)
19553     return CW_Default;
19554   Type *type = CallOperandVal->getType();
19555   // Look at the constraint type.
19556   switch (*constraint) {
19557   default:
19558     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19559   case 'R':
19560   case 'q':
19561   case 'Q':
19562   case 'a':
19563   case 'b':
19564   case 'c':
19565   case 'd':
19566   case 'S':
19567   case 'D':
19568   case 'A':
19569     if (CallOperandVal->getType()->isIntegerTy())
19570       weight = CW_SpecificReg;
19571     break;
19572   case 'f':
19573   case 't':
19574   case 'u':
19575     if (type->isFloatingPointTy())
19576       weight = CW_SpecificReg;
19577     break;
19578   case 'y':
19579     if (type->isX86_MMXTy() && Subtarget->hasMMX())
19580       weight = CW_SpecificReg;
19581     break;
19582   case 'x':
19583   case 'Y':
19584     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19585         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19586       weight = CW_Register;
19587     break;
19588   case 'I':
19589     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19590       if (C->getZExtValue() <= 31)
19591         weight = CW_Constant;
19592     }
19593     break;
19594   case 'J':
19595     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19596       if (C->getZExtValue() <= 63)
19597         weight = CW_Constant;
19598     }
19599     break;
19600   case 'K':
19601     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19602       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
19603         weight = CW_Constant;
19604     }
19605     break;
19606   case 'L':
19607     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19608       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
19609         weight = CW_Constant;
19610     }
19611     break;
19612   case 'M':
19613     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19614       if (C->getZExtValue() <= 3)
19615         weight = CW_Constant;
19616     }
19617     break;
19618   case 'N':
19619     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19620       if (C->getZExtValue() <= 0xff)
19621         weight = CW_Constant;
19622     }
19623     break;
19624   case 'G':
19625   case 'C':
19626     if (dyn_cast<ConstantFP>(CallOperandVal)) {
19627       weight = CW_Constant;
19628     }
19629     break;
19630   case 'e':
19631     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19632       if ((C->getSExtValue() >= -0x80000000LL) &&
19633           (C->getSExtValue() <= 0x7fffffffLL))
19634         weight = CW_Constant;
19635     }
19636     break;
19637   case 'Z':
19638     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19639       if (C->getZExtValue() <= 0xffffffff)
19640         weight = CW_Constant;
19641     }
19642     break;
19643   }
19644   return weight;
19645 }
19646
19647 /// LowerXConstraint - try to replace an X constraint, which matches anything,
19648 /// with another that has more specific requirements based on the type of the
19649 /// corresponding operand.
19650 const char *X86TargetLowering::
19651 LowerXConstraint(EVT ConstraintVT) const {
19652   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
19653   // 'f' like normal targets.
19654   if (ConstraintVT.isFloatingPoint()) {
19655     if (Subtarget->hasSSE2())
19656       return "Y";
19657     if (Subtarget->hasSSE1())
19658       return "x";
19659   }
19660
19661   return TargetLowering::LowerXConstraint(ConstraintVT);
19662 }
19663
19664 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19665 /// vector.  If it is invalid, don't add anything to Ops.
19666 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19667                                                      std::string &Constraint,
19668                                                      std::vector<SDValue>&Ops,
19669                                                      SelectionDAG &DAG) const {
19670   SDValue Result(0, 0);
19671
19672   // Only support length 1 constraints for now.
19673   if (Constraint.length() > 1) return;
19674
19675   char ConstraintLetter = Constraint[0];
19676   switch (ConstraintLetter) {
19677   default: break;
19678   case 'I':
19679     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19680       if (C->getZExtValue() <= 31) {
19681         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19682         break;
19683       }
19684     }
19685     return;
19686   case 'J':
19687     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19688       if (C->getZExtValue() <= 63) {
19689         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19690         break;
19691       }
19692     }
19693     return;
19694   case 'K':
19695     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19696       if (isInt<8>(C->getSExtValue())) {
19697         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19698         break;
19699       }
19700     }
19701     return;
19702   case 'N':
19703     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19704       if (C->getZExtValue() <= 255) {
19705         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19706         break;
19707       }
19708     }
19709     return;
19710   case 'e': {
19711     // 32-bit signed value
19712     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19713       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19714                                            C->getSExtValue())) {
19715         // Widen to 64 bits here to get it sign extended.
19716         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
19717         break;
19718       }
19719     // FIXME gcc accepts some relocatable values here too, but only in certain
19720     // memory models; it's complicated.
19721     }
19722     return;
19723   }
19724   case 'Z': {
19725     // 32-bit unsigned value
19726     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19727       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19728                                            C->getZExtValue())) {
19729         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19730         break;
19731       }
19732     }
19733     // FIXME gcc accepts some relocatable values here too, but only in certain
19734     // memory models; it's complicated.
19735     return;
19736   }
19737   case 'i': {
19738     // Literal immediates are always ok.
19739     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19740       // Widen to 64 bits here to get it sign extended.
19741       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19742       break;
19743     }
19744
19745     // In any sort of PIC mode addresses need to be computed at runtime by
19746     // adding in a register or some sort of table lookup.  These can't
19747     // be used as immediates.
19748     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19749       return;
19750
19751     // If we are in non-pic codegen mode, we allow the address of a global (with
19752     // an optional displacement) to be used with 'i'.
19753     GlobalAddressSDNode *GA = 0;
19754     int64_t Offset = 0;
19755
19756     // Match either (GA), (GA+C), (GA+C1+C2), etc.
19757     while (1) {
19758       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19759         Offset += GA->getOffset();
19760         break;
19761       } else if (Op.getOpcode() == ISD::ADD) {
19762         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19763           Offset += C->getZExtValue();
19764           Op = Op.getOperand(0);
19765           continue;
19766         }
19767       } else if (Op.getOpcode() == ISD::SUB) {
19768         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19769           Offset += -C->getZExtValue();
19770           Op = Op.getOperand(0);
19771           continue;
19772         }
19773       }
19774
19775       // Otherwise, this isn't something we can handle, reject it.
19776       return;
19777     }
19778
19779     const GlobalValue *GV = GA->getGlobal();
19780     // If we require an extra load to get this address, as in PIC mode, we
19781     // can't accept it.
19782     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19783                                                         getTargetMachine())))
19784       return;
19785
19786     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19787                                         GA->getValueType(0), Offset);
19788     break;
19789   }
19790   }
19791
19792   if (Result.getNode()) {
19793     Ops.push_back(Result);
19794     return;
19795   }
19796   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19797 }
19798
19799 std::pair<unsigned, const TargetRegisterClass*>
19800 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19801                                                 MVT VT) const {
19802   // First, see if this is a constraint that directly corresponds to an LLVM
19803   // register class.
19804   if (Constraint.size() == 1) {
19805     // GCC Constraint Letters
19806     switch (Constraint[0]) {
19807     default: break;
19808       // TODO: Slight differences here in allocation order and leaving
19809       // RIP in the class. Do they matter any more here than they do
19810       // in the normal allocation?
19811     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19812       if (Subtarget->is64Bit()) {
19813         if (VT == MVT::i32 || VT == MVT::f32)
19814           return std::make_pair(0U, &X86::GR32RegClass);
19815         if (VT == MVT::i16)
19816           return std::make_pair(0U, &X86::GR16RegClass);
19817         if (VT == MVT::i8 || VT == MVT::i1)
19818           return std::make_pair(0U, &X86::GR8RegClass);
19819         if (VT == MVT::i64 || VT == MVT::f64)
19820           return std::make_pair(0U, &X86::GR64RegClass);
19821         break;
19822       }
19823       // 32-bit fallthrough
19824     case 'Q':   // Q_REGS
19825       if (VT == MVT::i32 || VT == MVT::f32)
19826         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19827       if (VT == MVT::i16)
19828         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19829       if (VT == MVT::i8 || VT == MVT::i1)
19830         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19831       if (VT == MVT::i64)
19832         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19833       break;
19834     case 'r':   // GENERAL_REGS
19835     case 'l':   // INDEX_REGS
19836       if (VT == MVT::i8 || VT == MVT::i1)
19837         return std::make_pair(0U, &X86::GR8RegClass);
19838       if (VT == MVT::i16)
19839         return std::make_pair(0U, &X86::GR16RegClass);
19840       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19841         return std::make_pair(0U, &X86::GR32RegClass);
19842       return std::make_pair(0U, &X86::GR64RegClass);
19843     case 'R':   // LEGACY_REGS
19844       if (VT == MVT::i8 || VT == MVT::i1)
19845         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19846       if (VT == MVT::i16)
19847         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19848       if (VT == MVT::i32 || !Subtarget->is64Bit())
19849         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19850       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19851     case 'f':  // FP Stack registers.
19852       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19853       // value to the correct fpstack register class.
19854       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19855         return std::make_pair(0U, &X86::RFP32RegClass);
19856       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19857         return std::make_pair(0U, &X86::RFP64RegClass);
19858       return std::make_pair(0U, &X86::RFP80RegClass);
19859     case 'y':   // MMX_REGS if MMX allowed.
19860       if (!Subtarget->hasMMX()) break;
19861       return std::make_pair(0U, &X86::VR64RegClass);
19862     case 'Y':   // SSE_REGS if SSE2 allowed
19863       if (!Subtarget->hasSSE2()) break;
19864       // FALL THROUGH.
19865     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19866       if (!Subtarget->hasSSE1()) break;
19867
19868       switch (VT.SimpleTy) {
19869       default: break;
19870       // Scalar SSE types.
19871       case MVT::f32:
19872       case MVT::i32:
19873         return std::make_pair(0U, &X86::FR32RegClass);
19874       case MVT::f64:
19875       case MVT::i64:
19876         return std::make_pair(0U, &X86::FR64RegClass);
19877       // Vector types.
19878       case MVT::v16i8:
19879       case MVT::v8i16:
19880       case MVT::v4i32:
19881       case MVT::v2i64:
19882       case MVT::v4f32:
19883       case MVT::v2f64:
19884         return std::make_pair(0U, &X86::VR128RegClass);
19885       // AVX types.
19886       case MVT::v32i8:
19887       case MVT::v16i16:
19888       case MVT::v8i32:
19889       case MVT::v4i64:
19890       case MVT::v8f32:
19891       case MVT::v4f64:
19892         return std::make_pair(0U, &X86::VR256RegClass);
19893       case MVT::v8f64:
19894       case MVT::v16f32:
19895       case MVT::v16i32:
19896       case MVT::v8i64:
19897         return std::make_pair(0U, &X86::VR512RegClass);
19898       }
19899       break;
19900     }
19901   }
19902
19903   // Use the default implementation in TargetLowering to convert the register
19904   // constraint into a member of a register class.
19905   std::pair<unsigned, const TargetRegisterClass*> Res;
19906   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19907
19908   // Not found as a standard register?
19909   if (Res.second == 0) {
19910     // Map st(0) -> st(7) -> ST0
19911     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19912         tolower(Constraint[1]) == 's' &&
19913         tolower(Constraint[2]) == 't' &&
19914         Constraint[3] == '(' &&
19915         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19916         Constraint[5] == ')' &&
19917         Constraint[6] == '}') {
19918
19919       Res.first = X86::ST0+Constraint[4]-'0';
19920       Res.second = &X86::RFP80RegClass;
19921       return Res;
19922     }
19923
19924     // GCC allows "st(0)" to be called just plain "st".
19925     if (StringRef("{st}").equals_lower(Constraint)) {
19926       Res.first = X86::ST0;
19927       Res.second = &X86::RFP80RegClass;
19928       return Res;
19929     }
19930
19931     // flags -> EFLAGS
19932     if (StringRef("{flags}").equals_lower(Constraint)) {
19933       Res.first = X86::EFLAGS;
19934       Res.second = &X86::CCRRegClass;
19935       return Res;
19936     }
19937
19938     // 'A' means EAX + EDX.
19939     if (Constraint == "A") {
19940       Res.first = X86::EAX;
19941       Res.second = &X86::GR32_ADRegClass;
19942       return Res;
19943     }
19944     return Res;
19945   }
19946
19947   // Otherwise, check to see if this is a register class of the wrong value
19948   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19949   // turn into {ax},{dx}.
19950   if (Res.second->hasType(VT))
19951     return Res;   // Correct type already, nothing to do.
19952
19953   // All of the single-register GCC register classes map their values onto
19954   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
19955   // really want an 8-bit or 32-bit register, map to the appropriate register
19956   // class and return the appropriate register.
19957   if (Res.second == &X86::GR16RegClass) {
19958     if (VT == MVT::i8 || VT == MVT::i1) {
19959       unsigned DestReg = 0;
19960       switch (Res.first) {
19961       default: break;
19962       case X86::AX: DestReg = X86::AL; break;
19963       case X86::DX: DestReg = X86::DL; break;
19964       case X86::CX: DestReg = X86::CL; break;
19965       case X86::BX: DestReg = X86::BL; break;
19966       }
19967       if (DestReg) {
19968         Res.first = DestReg;
19969         Res.second = &X86::GR8RegClass;
19970       }
19971     } else if (VT == MVT::i32 || VT == MVT::f32) {
19972       unsigned DestReg = 0;
19973       switch (Res.first) {
19974       default: break;
19975       case X86::AX: DestReg = X86::EAX; break;
19976       case X86::DX: DestReg = X86::EDX; break;
19977       case X86::CX: DestReg = X86::ECX; break;
19978       case X86::BX: DestReg = X86::EBX; break;
19979       case X86::SI: DestReg = X86::ESI; break;
19980       case X86::DI: DestReg = X86::EDI; break;
19981       case X86::BP: DestReg = X86::EBP; break;
19982       case X86::SP: DestReg = X86::ESP; break;
19983       }
19984       if (DestReg) {
19985         Res.first = DestReg;
19986         Res.second = &X86::GR32RegClass;
19987       }
19988     } else if (VT == MVT::i64 || VT == MVT::f64) {
19989       unsigned DestReg = 0;
19990       switch (Res.first) {
19991       default: break;
19992       case X86::AX: DestReg = X86::RAX; break;
19993       case X86::DX: DestReg = X86::RDX; break;
19994       case X86::CX: DestReg = X86::RCX; break;
19995       case X86::BX: DestReg = X86::RBX; break;
19996       case X86::SI: DestReg = X86::RSI; break;
19997       case X86::DI: DestReg = X86::RDI; break;
19998       case X86::BP: DestReg = X86::RBP; break;
19999       case X86::SP: DestReg = X86::RSP; break;
20000       }
20001       if (DestReg) {
20002         Res.first = DestReg;
20003         Res.second = &X86::GR64RegClass;
20004       }
20005     }
20006   } else if (Res.second == &X86::FR32RegClass ||
20007              Res.second == &X86::FR64RegClass ||
20008              Res.second == &X86::VR128RegClass ||
20009              Res.second == &X86::VR256RegClass ||
20010              Res.second == &X86::FR32XRegClass ||
20011              Res.second == &X86::FR64XRegClass ||
20012              Res.second == &X86::VR128XRegClass ||
20013              Res.second == &X86::VR256XRegClass ||
20014              Res.second == &X86::VR512RegClass) {
20015     // Handle references to XMM physical registers that got mapped into the
20016     // wrong class.  This can happen with constraints like {xmm0} where the
20017     // target independent register mapper will just pick the first match it can
20018     // find, ignoring the required type.
20019
20020     if (VT == MVT::f32 || VT == MVT::i32)
20021       Res.second = &X86::FR32RegClass;
20022     else if (VT == MVT::f64 || VT == MVT::i64)
20023       Res.second = &X86::FR64RegClass;
20024     else if (X86::VR128RegClass.hasType(VT))
20025       Res.second = &X86::VR128RegClass;
20026     else if (X86::VR256RegClass.hasType(VT))
20027       Res.second = &X86::VR256RegClass;
20028     else if (X86::VR512RegClass.hasType(VT))
20029       Res.second = &X86::VR512RegClass;
20030   }
20031
20032   return Res;
20033 }