AVX-512: Added VPERM* instructons and MOV* zmm-to-zmm instructions.
[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 "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62                                 SelectionDAG &DAG, SDLoc dl,
63                                 unsigned vectorWidth) {
64   assert((vectorWidth == 128 || vectorWidth == 256) &&
65          "Unsupported vector width");
66   EVT VT = Vec.getValueType();
67   EVT ElVT = VT.getVectorElementType();
68   unsigned Factor = VT.getSizeInBits()/vectorWidth;
69   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70                                   VT.getVectorNumElements()/Factor);
71
72   // Extract from UNDEF is UNDEF.
73   if (Vec.getOpcode() == ISD::UNDEF)
74     return DAG.getUNDEF(ResultVT);
75
76   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
77   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
78
79   // This is the index of the first element of the vectorWidth-bit chunk
80   // we want.
81   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
82                                * ElemsPerChunk);
83
84   // If the input is a buildvector just emit a smaller one.
85   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
88
89   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
91                                VecIdx);
92
93   return Result;
94   
95 }
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103                                    SelectionDAG &DAG, SDLoc dl) {
104   assert((Vec.getValueType().is256BitVector() ||
105           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
107 }
108
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111                                    SelectionDAG &DAG, SDLoc dl) {
112   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
114 }
115
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117                                unsigned IdxVal, SelectionDAG &DAG,
118                                SDLoc dl, unsigned vectorWidth) {
119   assert((vectorWidth == 128 || vectorWidth == 256) &&
120          "Unsupported vector width");
121   // Inserting UNDEF is Result
122   if (Vec.getOpcode() == ISD::UNDEF)
123     return Result;
124   EVT VT = Vec.getValueType();
125   EVT ElVT = VT.getVectorElementType();
126   EVT ResultVT = Result.getValueType();
127
128   // Insert the relevant vectorWidth bits.
129   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
130
131   // This is the index of the first element of the vectorWidth-bit chunk
132   // we want.
133   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
134                                * ElemsPerChunk);
135
136   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
138                      VecIdx);
139 }
140 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference.  Idx is an index in the 128 bits
144 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147                                   unsigned IdxVal, SelectionDAG &DAG,
148                                   SDLoc dl) {
149   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
151 }
152
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154                                   unsigned IdxVal, SelectionDAG &DAG,
155                                   SDLoc dl) {
156   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
158 }
159
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165                                    unsigned NumElems, SelectionDAG &DAG,
166                                    SDLoc dl) {
167   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
169 }
170
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172                                    unsigned NumElems, SelectionDAG &DAG,
173                                    SDLoc dl) {
174   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
176 }
177
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180   bool is64Bit = Subtarget->is64Bit();
181
182   if (Subtarget->isTargetEnvMacho()) {
183     if (is64Bit)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (Subtarget->isTargetLinux())
189     return new X86LinuxTargetObjectFile();
190   if (Subtarget->isTargetELF())
191     return new TargetLoweringObjectFileELF();
192   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
193     return new TargetLoweringObjectFileCOFF();
194   llvm_unreachable("unknown subtarget type");
195 }
196
197 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
198   : TargetLowering(TM, createTLOF(TM)) {
199   Subtarget = &TM.getSubtarget<X86Subtarget>();
200   X86ScalarSSEf64 = Subtarget->hasSSE2();
201   X86ScalarSSEf32 = Subtarget->hasSSE1();
202   TD = getDataLayout();
203
204   resetOperationActions();
205 }
206
207 void X86TargetLowering::resetOperationActions() {
208   const TargetMachine &TM = getTargetMachine();
209   static bool FirstTimeThrough = true;
210
211   // If none of the target options have changed, then we don't need to reset the
212   // operation actions.
213   if (!FirstTimeThrough && TO == TM.Options) return;
214
215   if (!FirstTimeThrough) {
216     // Reinitialize the actions.
217     initActions();
218     FirstTimeThrough = false;
219   }
220
221   TO = TM.Options;
222
223   // Set up the TargetLowering object.
224   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
225
226   // X86 is weird, it always uses i8 for shift amounts and setcc results.
227   setBooleanContents(ZeroOrOneBooleanContent);
228   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
229   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
230
231   // For 64-bit since we have so many registers use the ILP scheduler, for
232   // 32-bit code use the register pressure specific scheduling.
233   // For Atom, always use ILP scheduling.
234   if (Subtarget->isAtom())
235     setSchedulingPreference(Sched::ILP);
236   else if (Subtarget->is64Bit())
237     setSchedulingPreference(Sched::ILP);
238   else
239     setSchedulingPreference(Sched::RegPressure);
240   const X86RegisterInfo *RegInfo =
241     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
242   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
243
244   // Bypass expensive divides on Atom when compiling with O2
245   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
246     addBypassSlowDiv(32, 8);
247     if (Subtarget->is64Bit())
248       addBypassSlowDiv(64, 16);
249   }
250
251   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
252     // Setup Windows compiler runtime calls.
253     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
254     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
255     setLibcallName(RTLIB::SREM_I64, "_allrem");
256     setLibcallName(RTLIB::UREM_I64, "_aullrem");
257     setLibcallName(RTLIB::MUL_I64, "_allmul");
258     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
259     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
260     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
263
264     // The _ftol2 runtime function has an unusual calling conv, which
265     // is modeled by a special pseudo-instruction.
266     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
267     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
268     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
269     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
270   }
271
272   if (Subtarget->isTargetDarwin()) {
273     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
274     setUseUnderscoreSetJmp(false);
275     setUseUnderscoreLongJmp(false);
276   } else if (Subtarget->isTargetMingw()) {
277     // MS runtime is weird: it exports _setjmp, but longjmp!
278     setUseUnderscoreSetJmp(true);
279     setUseUnderscoreLongJmp(false);
280   } else {
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(true);
283   }
284
285   // Set up the register classes.
286   addRegisterClass(MVT::i8, &X86::GR8RegClass);
287   addRegisterClass(MVT::i16, &X86::GR16RegClass);
288   addRegisterClass(MVT::i32, &X86::GR32RegClass);
289   if (Subtarget->is64Bit())
290     addRegisterClass(MVT::i64, &X86::GR64RegClass);
291
292   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
293
294   // We don't accept any truncstore of integer registers.
295   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
296   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
297   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
298   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
301
302   // SETOEQ and SETUNE require checking two conditions.
303   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
304   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
305   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
306   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
307   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
309
310   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
311   // operation.
312   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
313   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
315
316   if (Subtarget->is64Bit()) {
317     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
318     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
319   } else if (!TM.Options.UseSoftFloat) {
320     // We have an algorithm for SSE2->double, and we turn this into a
321     // 64-bit FILD followed by conditional FADD for other targets.
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
323     // We have an algorithm for SSE2, and we turn this into a 64-bit
324     // FILD for other targets.
325     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
326   }
327
328   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
329   // this operation.
330   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
331   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
332
333   if (!TM.Options.UseSoftFloat) {
334     // SSE has no i16 to fp conversion, only i32
335     if (X86ScalarSSEf32) {
336       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
337       // f32 and f64 cases are Legal, f80 case is not
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
339     } else {
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
342     }
343   } else {
344     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
345     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
346   }
347
348   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
349   // are Legal, f80 is custom lowered.
350   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
351   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
352
353   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
354   // this operation.
355   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
356   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
357
358   if (X86ScalarSSEf32) {
359     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
360     // f32 and f64 cases are Legal, f80 case is not
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
362   } else {
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
365   }
366
367   // Handle FP_TO_UINT by promoting the destination to a larger signed
368   // conversion.
369   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
370   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
372
373   if (Subtarget->is64Bit()) {
374     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
375     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
376   } else if (!TM.Options.UseSoftFloat) {
377     // Since AVX is a superset of SSE3, only check for SSE here.
378     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
379       // Expand FP_TO_UINT into a select.
380       // FIXME: We would like to use a Custom expander here eventually to do
381       // the optimal thing for SSE vs. the default expansion in the legalizer.
382       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
383     else
384       // With SSE3 we can use fisttpll to convert to a signed i64; without
385       // SSE, we're stuck with a fistpll.
386       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
387   }
388
389   if (isTargetFTOL()) {
390     // Use the _ftol2 runtime function, which has a pseudo-instruction
391     // to handle its weird calling convention.
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
393   }
394
395   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
396   if (!X86ScalarSSEf64) {
397     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
398     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
399     if (Subtarget->is64Bit()) {
400       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
401       // Without SSE, i64->f64 goes through memory.
402       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
403     }
404   }
405
406   // Scalar integer divide and remainder are lowered to use operations that
407   // produce two results, to match the available instructions. This exposes
408   // the two-result form to trivial CSE, which is able to combine x/y and x%y
409   // into a single instruction.
410   //
411   // Scalar integer multiply-high is also lowered to use two-result
412   // operations, to match the available instructions. However, plain multiply
413   // (low) operations are left as Legal, as there are single-result
414   // instructions for this in x86. Using the two-result multiply instructions
415   // when both high and low results are needed must be arranged by dagcombine.
416   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
417     MVT VT = IntVTs[i];
418     setOperationAction(ISD::MULHS, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::SDIV, VT, Expand);
421     setOperationAction(ISD::UDIV, VT, Expand);
422     setOperationAction(ISD::SREM, VT, Expand);
423     setOperationAction(ISD::UREM, VT, Expand);
424
425     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
426     setOperationAction(ISD::ADDC, VT, Custom);
427     setOperationAction(ISD::ADDE, VT, Custom);
428     setOperationAction(ISD::SUBC, VT, Custom);
429     setOperationAction(ISD::SUBE, VT, Custom);
430   }
431
432   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
433   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
434   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
435   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
436   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
438   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
441   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
442   if (Subtarget->is64Bit())
443     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
444   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
445   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
447   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
448   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
449   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
451   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
452
453   // Promote the i8 variants and force them on up to i32 which has a shorter
454   // encoding.
455   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
456   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
457   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
459   if (Subtarget->hasBMI()) {
460     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
461     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
462     if (Subtarget->is64Bit())
463       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
464   } else {
465     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
466     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
467     if (Subtarget->is64Bit())
468       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
469   }
470
471   if (Subtarget->hasLZCNT()) {
472     // When promoting the i8 variants, force them to i32 for a shorter
473     // encoding.
474     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
475     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
476     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
480     if (Subtarget->is64Bit())
481       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
482   } else {
483     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
484     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
485     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
486     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
489     if (Subtarget->is64Bit()) {
490       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
491       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
492     }
493   }
494
495   if (Subtarget->hasPOPCNT()) {
496     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
497   } else {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
499     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
500     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
501     if (Subtarget->is64Bit())
502       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
503   }
504
505   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
506   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
507
508   // These should be promoted to a larger select which is supported.
509   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
510   // X86 wants to expand cmov itself.
511   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
512   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
513   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
514   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
515   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
516   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
517   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
518   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
519   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
520   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
523   if (Subtarget->is64Bit()) {
524     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
525     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
526   }
527   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
528   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
529   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
530   // support continuation, user-level threading, and etc.. As a result, no
531   // other SjLj exception interfaces are implemented and please don't build
532   // your own exception handling based on them.
533   // LLVM/Clang supports zero-cost DWARF exception handling.
534   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
535   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
536
537   // Darwin ABI issue.
538   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
539   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
540   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
541   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
542   if (Subtarget->is64Bit())
543     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
544   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
545   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
546   if (Subtarget->is64Bit()) {
547     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
548     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
549     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
550     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
551     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
552   }
553   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
554   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
555   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
556   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
557   if (Subtarget->is64Bit()) {
558     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
559     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
560     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
561   }
562
563   if (Subtarget->hasSSE1())
564     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
565
566   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
567
568   // Expand certain atomics
569   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
570     MVT VT = IntVTs[i];
571     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
572     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
573     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
574   }
575
576   if (!Subtarget->is64Bit()) {
577     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
578     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
589   }
590
591   if (Subtarget->hasCmpxchg16b()) {
592     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
593   }
594
595   // FIXME - use subtarget debug flags
596   if (!Subtarget->isTargetDarwin() &&
597       !Subtarget->isTargetELF() &&
598       !Subtarget->isTargetCygMing()) {
599     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
600   }
601
602   if (Subtarget->is64Bit()) {
603     setExceptionPointerRegister(X86::RAX);
604     setExceptionSelectorRegister(X86::RDX);
605   } else {
606     setExceptionPointerRegister(X86::EAX);
607     setExceptionSelectorRegister(X86::EDX);
608   }
609   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
610   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
611
612   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
613   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
614
615   setOperationAction(ISD::TRAP, MVT::Other, Legal);
616   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
617
618   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
619   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
620   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
621   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
622     // TargetInfo::X86_64ABIBuiltinVaList
623     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
624     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
625   } else {
626     // TargetInfo::CharPtrBuiltinVaList
627     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
628     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
629   }
630
631   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
632   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
633
634   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
635     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
636                        MVT::i64 : MVT::i32, Custom);
637   else if (TM.Options.EnableSegmentedStacks)
638     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639                        MVT::i64 : MVT::i32, Custom);
640   else
641     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642                        MVT::i64 : MVT::i32, Expand);
643
644   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645     // f32 and f64 use SSE.
646     // Set up the FP register classes.
647     addRegisterClass(MVT::f32, &X86::FR32RegClass);
648     addRegisterClass(MVT::f64, &X86::FR64RegClass);
649
650     // Use ANDPD to simulate FABS.
651     setOperationAction(ISD::FABS , MVT::f64, Custom);
652     setOperationAction(ISD::FABS , MVT::f32, Custom);
653
654     // Use XORP to simulate FNEG.
655     setOperationAction(ISD::FNEG , MVT::f64, Custom);
656     setOperationAction(ISD::FNEG , MVT::f32, Custom);
657
658     // Use ANDPD and ORPD to simulate FCOPYSIGN.
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661
662     // Lower this to FGETSIGNx86 plus an AND.
663     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
665
666     // We don't support sin/cos/fmod
667     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674     // Expand FP immediates into loads from the stack, except for the special
675     // cases we handle.
676     addLegalFPImmediate(APFloat(+0.0)); // xorpd
677     addLegalFPImmediate(APFloat(+0.0f)); // xorps
678   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679     // Use SSE for f32, x87 for f64.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f32, &X86::FR32RegClass);
682     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683
684     // Use ANDPS to simulate FABS.
685     setOperationAction(ISD::FABS , MVT::f32, Custom);
686
687     // Use XORP to simulate FNEG.
688     setOperationAction(ISD::FNEG , MVT::f32, Custom);
689
690     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
691
692     // Use ANDPS and ORPS to simulate FCOPYSIGN.
693     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
695
696     // We don't support sin/cos/fmod
697     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
698     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
699     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
700
701     // Special cases we handle for FP constants.
702     addLegalFPImmediate(APFloat(+0.0f)); // xorps
703     addLegalFPImmediate(APFloat(+0.0)); // FLD0
704     addLegalFPImmediate(APFloat(+1.0)); // FLD1
705     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
707
708     if (!TM.Options.UnsafeFPMath) {
709       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
710       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
711       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
712     }
713   } else if (!TM.Options.UseSoftFloat) {
714     // f32 and f64 in x87.
715     // Set up the FP register classes.
716     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
718
719     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
720     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
721     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
723
724     if (!TM.Options.UnsafeFPMath) {
725       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
726       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
727       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
728       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
729       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
731     }
732     addLegalFPImmediate(APFloat(+0.0)); // FLD0
733     addLegalFPImmediate(APFloat(+1.0)); // FLD1
734     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740   }
741
742   // We don't support FMA.
743   setOperationAction(ISD::FMA, MVT::f64, Expand);
744   setOperationAction(ISD::FMA, MVT::f32, Expand);
745
746   // Long double always uses X87.
747   if (!TM.Options.UseSoftFloat) {
748     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
750     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
751     {
752       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753       addLegalFPImmediate(TmpFlt);  // FLD0
754       TmpFlt.changeSign();
755       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
756
757       bool ignored;
758       APFloat TmpFlt2(+1.0);
759       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
760                       &ignored);
761       addLegalFPImmediate(TmpFlt2);  // FLD1
762       TmpFlt2.changeSign();
763       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
764     }
765
766     if (!TM.Options.UnsafeFPMath) {
767       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
768       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
769       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770     }
771
772     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
774     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
776     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777     setOperationAction(ISD::FMA, MVT::f80, Expand);
778   }
779
780   // Always use a library call for pow.
781   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
782   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
783   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
784
785   setOperationAction(ISD::FLOG, MVT::f80, Expand);
786   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788   setOperationAction(ISD::FEXP, MVT::f80, Expand);
789   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
790
791   // First set operation action for all vector types to either promote
792   // (for widening) or expand (for scalarization). Then we will selectively
793   // turn on ones that can be effectively codegen'd.
794   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796     MVT VT = (MVT::SimpleValueType)i;
797     setOperationAction(ISD::ADD , VT, Expand);
798     setOperationAction(ISD::SUB , VT, Expand);
799     setOperationAction(ISD::FADD, VT, Expand);
800     setOperationAction(ISD::FNEG, VT, Expand);
801     setOperationAction(ISD::FSUB, VT, Expand);
802     setOperationAction(ISD::MUL , VT, Expand);
803     setOperationAction(ISD::FMUL, VT, Expand);
804     setOperationAction(ISD::SDIV, VT, Expand);
805     setOperationAction(ISD::UDIV, VT, Expand);
806     setOperationAction(ISD::FDIV, VT, Expand);
807     setOperationAction(ISD::SREM, VT, Expand);
808     setOperationAction(ISD::UREM, VT, Expand);
809     setOperationAction(ISD::LOAD, VT, Expand);
810     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815     setOperationAction(ISD::FABS, VT, Expand);
816     setOperationAction(ISD::FSIN, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FCOS, VT, Expand);
819     setOperationAction(ISD::FSINCOS, VT, Expand);
820     setOperationAction(ISD::FREM, VT, Expand);
821     setOperationAction(ISD::FMA,  VT, Expand);
822     setOperationAction(ISD::FPOWI, VT, Expand);
823     setOperationAction(ISD::FSQRT, VT, Expand);
824     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825     setOperationAction(ISD::FFLOOR, VT, Expand);
826     setOperationAction(ISD::FCEIL, VT, Expand);
827     setOperationAction(ISD::FTRUNC, VT, Expand);
828     setOperationAction(ISD::FRINT, VT, Expand);
829     setOperationAction(ISD::FNEARBYINT, VT, Expand);
830     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
832     setOperationAction(ISD::SDIVREM, VT, Expand);
833     setOperationAction(ISD::UDIVREM, VT, Expand);
834     setOperationAction(ISD::FPOW, VT, Expand);
835     setOperationAction(ISD::CTPOP, VT, Expand);
836     setOperationAction(ISD::CTTZ, VT, Expand);
837     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::CTLZ, VT, Expand);
839     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::SHL, VT, Expand);
841     setOperationAction(ISD::SRA, VT, Expand);
842     setOperationAction(ISD::SRL, VT, Expand);
843     setOperationAction(ISD::ROTL, VT, Expand);
844     setOperationAction(ISD::ROTR, VT, Expand);
845     setOperationAction(ISD::BSWAP, VT, Expand);
846     setOperationAction(ISD::SETCC, VT, Expand);
847     setOperationAction(ISD::FLOG, VT, Expand);
848     setOperationAction(ISD::FLOG2, VT, Expand);
849     setOperationAction(ISD::FLOG10, VT, Expand);
850     setOperationAction(ISD::FEXP, VT, Expand);
851     setOperationAction(ISD::FEXP2, VT, Expand);
852     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857     setOperationAction(ISD::TRUNCATE, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861     setOperationAction(ISD::VSELECT, VT, Expand);
862     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864       setTruncStoreAction(VT,
865                           (MVT::SimpleValueType)InnerVT, Expand);
866     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869   }
870
871   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872   // with -msoft-float, disable use of MMX as well.
873   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875     // No operations on x86mmx supported, everything uses intrinsics.
876   }
877
878   // MMX-sized vectors (other than x86mmx) are expected to be expanded
879   // into smaller operations.
880   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
881   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
883   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
884   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
885   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
886   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
887   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
888   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
889   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
890   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
891   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
892   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
893   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
894   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
895   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
900   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
902   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
904   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
909
910   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
912
913     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
918     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
919     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
920     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
921     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
922     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
923     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
925   }
926
927   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
929
930     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931     // registers cannot be used even for integer operations.
932     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
936
937     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
938     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
939     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
940     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
941     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
942     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
943     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
944     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
945     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
946     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
947     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
948     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
953     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
954     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
955
956     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
960
961     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
962     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
966
967     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
968     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
969       MVT VT = (MVT::SimpleValueType)i;
970       // Do not attempt to custom lower non-power-of-2 vectors
971       if (!isPowerOf2_32(VT.getVectorNumElements()))
972         continue;
973       // Do not attempt to custom lower non-128-bit vectors
974       if (!VT.is128BitVector())
975         continue;
976       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
977       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
978       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
979     }
980
981     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
982     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
983     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
984     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
987
988     if (Subtarget->is64Bit()) {
989       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
991     }
992
993     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
994     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
995       MVT VT = (MVT::SimpleValueType)i;
996
997       // Do not attempt to promote non-128-bit vectors
998       if (!VT.is128BitVector())
999         continue;
1000
1001       setOperationAction(ISD::AND,    VT, Promote);
1002       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1003       setOperationAction(ISD::OR,     VT, Promote);
1004       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1005       setOperationAction(ISD::XOR,    VT, Promote);
1006       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1007       setOperationAction(ISD::LOAD,   VT, Promote);
1008       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1009       setOperationAction(ISD::SELECT, VT, Promote);
1010       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1011     }
1012
1013     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1014
1015     // Custom lower v2i64 and v2f64 selects.
1016     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1017     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1018     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1019     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1020
1021     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1022     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1023
1024     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1025     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1026     // As there is no 64-bit GPR available, we need build a special custom
1027     // sequence to convert from v2i32 to v2f32.
1028     if (!Subtarget->is64Bit())
1029       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1030
1031     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1032     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1033
1034     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1035   }
1036
1037   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1038     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1039     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1040     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1041     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1042     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1043     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1044     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1045     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1046     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1047     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1048
1049     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1050     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1051     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1052     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1053     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1054     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1055     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1056     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1057     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1058     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1059
1060     // FIXME: Do we need to handle scalar-to-vector here?
1061     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1062
1063     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1064     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1068
1069     // i8 and i16 vectors are custom , because the source register and source
1070     // source memory operand types are not the same width.  f32 vectors are
1071     // custom since the immediate controlling the insert encodes additional
1072     // information.
1073     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1077
1078     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1082
1083     // FIXME: these should be Legal but thats only for the case where
1084     // the index is constant.  For now custom expand to deal with that.
1085     if (Subtarget->is64Bit()) {
1086       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1087       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1088     }
1089   }
1090
1091   if (Subtarget->hasSSE2()) {
1092     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1093     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1094
1095     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1096     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1097
1098     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1099     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1100
1101     // In the customized shift lowering, the legal cases in AVX2 will be
1102     // recognized.
1103     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1104     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1105
1106     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1107     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1108
1109     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1110
1111     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1112     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1113   }
1114
1115   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1116     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1117     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1118     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1120     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1122
1123     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1124     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1125     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1126
1127     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1132     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1133     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1135     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1136     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1137     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1138     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1139
1140     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1145     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1146     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1148     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1149     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1150     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1151     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1152
1153     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1154     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1155
1156     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1157
1158     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1159     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1160     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1161     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1162
1163     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1164     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1165     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1166
1167     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1168
1169     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1179
1180     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1182     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1183     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1184
1185     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1186     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1187     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1188
1189     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1191     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1192     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1193
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1200
1201     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1202       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1203       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1204       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1205       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1206       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1208     }
1209
1210     if (Subtarget->hasInt256()) {
1211       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1212       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1213       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1214       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1215
1216       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1217       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1218       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1219       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1220
1221       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1222       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1223       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1224       // Don't lower v32i8 because there is no 128-bit byte mul
1225
1226       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1227
1228       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1229     } else {
1230       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1231       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1232       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1233       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1234
1235       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1236       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1237       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1238       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1239
1240       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1241       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1242       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1243       // Don't lower v32i8 because there is no 128-bit byte mul
1244     }
1245
1246     // In the customized shift lowering, the legal cases in AVX2 will be
1247     // recognized.
1248     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1249     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1250
1251     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1253
1254     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1255
1256     // Custom lower several nodes for 256-bit types.
1257     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1258              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1259       MVT VT = (MVT::SimpleValueType)i;
1260
1261       // Extract subvector is special because the value type
1262       // (result) is 128-bit but the source is 256-bit wide.
1263       if (VT.is128BitVector())
1264         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1265
1266       // Do not attempt to custom lower other non-256-bit vectors
1267       if (!VT.is256BitVector())
1268         continue;
1269
1270       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1271       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1272       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1273       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1275       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1276       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1277     }
1278
1279     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1280     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1281       MVT VT = (MVT::SimpleValueType)i;
1282
1283       // Do not attempt to promote non-256-bit vectors
1284       if (!VT.is256BitVector())
1285         continue;
1286
1287       setOperationAction(ISD::AND,    VT, Promote);
1288       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1289       setOperationAction(ISD::OR,     VT, Promote);
1290       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1291       setOperationAction(ISD::XOR,    VT, Promote);
1292       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1293       setOperationAction(ISD::LOAD,   VT, Promote);
1294       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1295       setOperationAction(ISD::SELECT, VT, Promote);
1296       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1297     }
1298   }
1299
1300   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1301     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1302     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1303     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1304     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1305
1306     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1307     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1308
1309     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1310     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1312     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1313     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1314     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1315
1316     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1317     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1321     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1322
1323     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1324     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1327     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1328     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1329     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1330     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1331     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1332
1333
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1338     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1340     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1341     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1342
1343     setOperationAction(ISD::TRUNCATE,           MVT::i1, Legal);
1344     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1345     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1346     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1347     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1348     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1349     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1350     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1351     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1352     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1353     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1354     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1355
1356     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1357     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1358     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1359     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1360     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1361
1362     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1363     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1364
1365     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1366
1367     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1368     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1370     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1371     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1372
1373     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1374     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1375
1376     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1377     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1378
1379     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1380
1381     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1382     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1383
1384     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1385     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1386
1387     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1388     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1389
1390     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1391     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1392     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1393
1394     // Custom lower several nodes.
1395     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1396              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1397       MVT VT = (MVT::SimpleValueType)i;
1398
1399       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1400       // Extract subvector is special because the value type
1401       // (result) is 256/128-bit but the source is 512-bit wide.
1402       if (VT.is128BitVector() || VT.is256BitVector())
1403         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1404
1405       if (VT.getVectorElementType() == MVT::i1)
1406         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1407
1408       // Do not attempt to custom lower other non-512-bit vectors
1409       if (!VT.is512BitVector())
1410         continue;
1411
1412       if (VT != MVT::v8i64) {
1413         setOperationAction(ISD::XOR,   VT, Promote);
1414         AddPromotedToType (ISD::XOR,   VT, MVT::v8i64);
1415         setOperationAction(ISD::OR,    VT, Promote);
1416         AddPromotedToType (ISD::OR,    VT, MVT::v8i64);
1417         setOperationAction(ISD::AND,   VT, Promote);
1418         AddPromotedToType (ISD::AND,   VT, MVT::v8i64);
1419       }
1420       if ( EltSize >= 32) {
1421         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1422         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1423         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1424         setOperationAction(ISD::VSELECT,             VT, Legal);
1425         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1426         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1427         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1428       }
1429     }
1430     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1431       MVT VT = (MVT::SimpleValueType)i;
1432
1433       // Do not attempt to promote non-256-bit vectors
1434       if (!VT.is512BitVector())
1435         continue;
1436
1437       setOperationAction(ISD::LOAD,   VT, Promote);
1438       AddPromotedToType (ISD::LOAD,   VT, MVT::v8i64);
1439       setOperationAction(ISD::SELECT, VT, Promote);
1440       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1441     }
1442   }// has  AVX-512
1443
1444   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1445   // of this type with custom code.
1446   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1447            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1448     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1449                        Custom);
1450   }
1451
1452   // We want to custom lower some of our intrinsics.
1453   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1454   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1455
1456   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1457   // handle type legalization for these operations here.
1458   //
1459   // FIXME: We really should do custom legalization for addition and
1460   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1461   // than generic legalization for 64-bit multiplication-with-overflow, though.
1462   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1463     // Add/Sub/Mul with overflow operations are custom lowered.
1464     MVT VT = IntVTs[i];
1465     setOperationAction(ISD::SADDO, VT, Custom);
1466     setOperationAction(ISD::UADDO, VT, Custom);
1467     setOperationAction(ISD::SSUBO, VT, Custom);
1468     setOperationAction(ISD::USUBO, VT, Custom);
1469     setOperationAction(ISD::SMULO, VT, Custom);
1470     setOperationAction(ISD::UMULO, VT, Custom);
1471   }
1472
1473   // There are no 8-bit 3-address imul/mul instructions
1474   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1475   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1476
1477   if (!Subtarget->is64Bit()) {
1478     // These libcalls are not available in 32-bit.
1479     setLibcallName(RTLIB::SHL_I128, 0);
1480     setLibcallName(RTLIB::SRL_I128, 0);
1481     setLibcallName(RTLIB::SRA_I128, 0);
1482   }
1483
1484   // Combine sin / cos into one node or libcall if possible.
1485   if (Subtarget->hasSinCos()) {
1486     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1487     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1488     if (Subtarget->isTargetDarwin()) {
1489       // For MacOSX, we don't want to the normal expansion of a libcall to
1490       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1491       // traffic.
1492       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1493       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1494     }
1495   }
1496
1497   // We have target-specific dag combine patterns for the following nodes:
1498   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1499   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1500   setTargetDAGCombine(ISD::VSELECT);
1501   setTargetDAGCombine(ISD::SELECT);
1502   setTargetDAGCombine(ISD::SHL);
1503   setTargetDAGCombine(ISD::SRA);
1504   setTargetDAGCombine(ISD::SRL);
1505   setTargetDAGCombine(ISD::OR);
1506   setTargetDAGCombine(ISD::AND);
1507   setTargetDAGCombine(ISD::ADD);
1508   setTargetDAGCombine(ISD::FADD);
1509   setTargetDAGCombine(ISD::FSUB);
1510   setTargetDAGCombine(ISD::FMA);
1511   setTargetDAGCombine(ISD::SUB);
1512   setTargetDAGCombine(ISD::LOAD);
1513   setTargetDAGCombine(ISD::STORE);
1514   setTargetDAGCombine(ISD::ZERO_EXTEND);
1515   setTargetDAGCombine(ISD::ANY_EXTEND);
1516   setTargetDAGCombine(ISD::SIGN_EXTEND);
1517   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1518   setTargetDAGCombine(ISD::TRUNCATE);
1519   setTargetDAGCombine(ISD::SINT_TO_FP);
1520   setTargetDAGCombine(ISD::SETCC);
1521   if (Subtarget->is64Bit())
1522     setTargetDAGCombine(ISD::MUL);
1523   setTargetDAGCombine(ISD::XOR);
1524
1525   computeRegisterProperties();
1526
1527   // On Darwin, -Os means optimize for size without hurting performance,
1528   // do not reduce the limit.
1529   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1530   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1531   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1532   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1533   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1534   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1535   setPrefLoopAlignment(4); // 2^4 bytes.
1536
1537   // Predictable cmov don't hurt on atom because it's in-order.
1538   PredictableSelectIsExpensive = !Subtarget->isAtom();
1539
1540   setPrefFunctionAlignment(4); // 2^4 bytes.
1541 }
1542
1543 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1544   if (!VT.isVector()) return MVT::i8;
1545   return VT.changeVectorElementTypeToInteger();
1546 }
1547
1548 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1549 /// the desired ByVal argument alignment.
1550 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1551   if (MaxAlign == 16)
1552     return;
1553   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1554     if (VTy->getBitWidth() == 128)
1555       MaxAlign = 16;
1556   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1557     unsigned EltAlign = 0;
1558     getMaxByValAlign(ATy->getElementType(), EltAlign);
1559     if (EltAlign > MaxAlign)
1560       MaxAlign = EltAlign;
1561   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1562     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1563       unsigned EltAlign = 0;
1564       getMaxByValAlign(STy->getElementType(i), EltAlign);
1565       if (EltAlign > MaxAlign)
1566         MaxAlign = EltAlign;
1567       if (MaxAlign == 16)
1568         break;
1569     }
1570   }
1571 }
1572
1573 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1574 /// function arguments in the caller parameter area. For X86, aggregates
1575 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1576 /// are at 4-byte boundaries.
1577 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1578   if (Subtarget->is64Bit()) {
1579     // Max of 8 and alignment of type.
1580     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1581     if (TyAlign > 8)
1582       return TyAlign;
1583     return 8;
1584   }
1585
1586   unsigned Align = 4;
1587   if (Subtarget->hasSSE1())
1588     getMaxByValAlign(Ty, Align);
1589   return Align;
1590 }
1591
1592 /// getOptimalMemOpType - Returns the target specific optimal type for load
1593 /// and store operations as a result of memset, memcpy, and memmove
1594 /// lowering. If DstAlign is zero that means it's safe to destination
1595 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1596 /// means there isn't a need to check it against alignment requirement,
1597 /// probably because the source does not need to be loaded. If 'IsMemset' is
1598 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1599 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1600 /// source is constant so it does not need to be loaded.
1601 /// It returns EVT::Other if the type should be determined using generic
1602 /// target-independent logic.
1603 EVT
1604 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1605                                        unsigned DstAlign, unsigned SrcAlign,
1606                                        bool IsMemset, bool ZeroMemset,
1607                                        bool MemcpyStrSrc,
1608                                        MachineFunction &MF) const {
1609   const Function *F = MF.getFunction();
1610   if ((!IsMemset || ZeroMemset) &&
1611       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1612                                        Attribute::NoImplicitFloat)) {
1613     if (Size >= 16 &&
1614         (Subtarget->isUnalignedMemAccessFast() ||
1615          ((DstAlign == 0 || DstAlign >= 16) &&
1616           (SrcAlign == 0 || SrcAlign >= 16)))) {
1617       if (Size >= 32) {
1618         if (Subtarget->hasInt256())
1619           return MVT::v8i32;
1620         if (Subtarget->hasFp256())
1621           return MVT::v8f32;
1622       }
1623       if (Subtarget->hasSSE2())
1624         return MVT::v4i32;
1625       if (Subtarget->hasSSE1())
1626         return MVT::v4f32;
1627     } else if (!MemcpyStrSrc && Size >= 8 &&
1628                !Subtarget->is64Bit() &&
1629                Subtarget->hasSSE2()) {
1630       // Do not use f64 to lower memcpy if source is string constant. It's
1631       // better to use i32 to avoid the loads.
1632       return MVT::f64;
1633     }
1634   }
1635   if (Subtarget->is64Bit() && Size >= 8)
1636     return MVT::i64;
1637   return MVT::i32;
1638 }
1639
1640 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1641   if (VT == MVT::f32)
1642     return X86ScalarSSEf32;
1643   else if (VT == MVT::f64)
1644     return X86ScalarSSEf64;
1645   return true;
1646 }
1647
1648 bool
1649 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1650   if (Fast)
1651     *Fast = Subtarget->isUnalignedMemAccessFast();
1652   return true;
1653 }
1654
1655 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1656 /// current function.  The returned value is a member of the
1657 /// MachineJumpTableInfo::JTEntryKind enum.
1658 unsigned X86TargetLowering::getJumpTableEncoding() const {
1659   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1660   // symbol.
1661   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1662       Subtarget->isPICStyleGOT())
1663     return MachineJumpTableInfo::EK_Custom32;
1664
1665   // Otherwise, use the normal jump table encoding heuristics.
1666   return TargetLowering::getJumpTableEncoding();
1667 }
1668
1669 const MCExpr *
1670 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1671                                              const MachineBasicBlock *MBB,
1672                                              unsigned uid,MCContext &Ctx) const{
1673   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1674          Subtarget->isPICStyleGOT());
1675   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1676   // entries.
1677   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1678                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1679 }
1680
1681 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1682 /// jumptable.
1683 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1684                                                     SelectionDAG &DAG) const {
1685   if (!Subtarget->is64Bit())
1686     // This doesn't have SDLoc associated with it, but is not really the
1687     // same as a Register.
1688     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1689   return Table;
1690 }
1691
1692 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1693 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1694 /// MCExpr.
1695 const MCExpr *X86TargetLowering::
1696 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1697                              MCContext &Ctx) const {
1698   // X86-64 uses RIP relative addressing based on the jump table label.
1699   if (Subtarget->isPICStyleRIPRel())
1700     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1701
1702   // Otherwise, the reference is relative to the PIC base.
1703   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1704 }
1705
1706 // FIXME: Why this routine is here? Move to RegInfo!
1707 std::pair<const TargetRegisterClass*, uint8_t>
1708 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1709   const TargetRegisterClass *RRC = 0;
1710   uint8_t Cost = 1;
1711   switch (VT.SimpleTy) {
1712   default:
1713     return TargetLowering::findRepresentativeClass(VT);
1714   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1715     RRC = Subtarget->is64Bit() ?
1716       (const TargetRegisterClass*)&X86::GR64RegClass :
1717       (const TargetRegisterClass*)&X86::GR32RegClass;
1718     break;
1719   case MVT::x86mmx:
1720     RRC = &X86::VR64RegClass;
1721     break;
1722   case MVT::f32: case MVT::f64:
1723   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1724   case MVT::v4f32: case MVT::v2f64:
1725   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1726   case MVT::v4f64:
1727     RRC = &X86::VR128RegClass;
1728     break;
1729   }
1730   return std::make_pair(RRC, Cost);
1731 }
1732
1733 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1734                                                unsigned &Offset) const {
1735   if (!Subtarget->isTargetLinux())
1736     return false;
1737
1738   if (Subtarget->is64Bit()) {
1739     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1740     Offset = 0x28;
1741     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1742       AddressSpace = 256;
1743     else
1744       AddressSpace = 257;
1745   } else {
1746     // %gs:0x14 on i386
1747     Offset = 0x14;
1748     AddressSpace = 256;
1749   }
1750   return true;
1751 }
1752
1753 //===----------------------------------------------------------------------===//
1754 //               Return Value Calling Convention Implementation
1755 //===----------------------------------------------------------------------===//
1756
1757 #include "X86GenCallingConv.inc"
1758
1759 bool
1760 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1761                                   MachineFunction &MF, bool isVarArg,
1762                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1763                         LLVMContext &Context) const {
1764   SmallVector<CCValAssign, 16> RVLocs;
1765   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1766                  RVLocs, Context);
1767   return CCInfo.CheckReturn(Outs, RetCC_X86);
1768 }
1769
1770 SDValue
1771 X86TargetLowering::LowerReturn(SDValue Chain,
1772                                CallingConv::ID CallConv, bool isVarArg,
1773                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1774                                const SmallVectorImpl<SDValue> &OutVals,
1775                                SDLoc dl, SelectionDAG &DAG) const {
1776   MachineFunction &MF = DAG.getMachineFunction();
1777   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1778
1779   SmallVector<CCValAssign, 16> RVLocs;
1780   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1781                  RVLocs, *DAG.getContext());
1782   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1783
1784   SDValue Flag;
1785   SmallVector<SDValue, 6> RetOps;
1786   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1787   // Operand #1 = Bytes To Pop
1788   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1789                    MVT::i16));
1790
1791   // Copy the result values into the output registers.
1792   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1793     CCValAssign &VA = RVLocs[i];
1794     assert(VA.isRegLoc() && "Can only return in registers!");
1795     SDValue ValToCopy = OutVals[i];
1796     EVT ValVT = ValToCopy.getValueType();
1797
1798     // Promote values to the appropriate types
1799     if (VA.getLocInfo() == CCValAssign::SExt)
1800       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1801     else if (VA.getLocInfo() == CCValAssign::ZExt)
1802       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1803     else if (VA.getLocInfo() == CCValAssign::AExt)
1804       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1805     else if (VA.getLocInfo() == CCValAssign::BCvt)
1806       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1807
1808     // If this is x86-64, and we disabled SSE, we can't return FP values,
1809     // or SSE or MMX vectors.
1810     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1811          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1812           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1813       report_fatal_error("SSE register return with SSE disabled");
1814     }
1815     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1816     // llvm-gcc has never done it right and no one has noticed, so this
1817     // should be OK for now.
1818     if (ValVT == MVT::f64 &&
1819         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1820       report_fatal_error("SSE2 register return with SSE2 disabled");
1821
1822     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1823     // the RET instruction and handled by the FP Stackifier.
1824     if (VA.getLocReg() == X86::ST0 ||
1825         VA.getLocReg() == X86::ST1) {
1826       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1827       // change the value to the FP stack register class.
1828       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1829         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1830       RetOps.push_back(ValToCopy);
1831       // Don't emit a copytoreg.
1832       continue;
1833     }
1834
1835     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1836     // which is returned in RAX / RDX.
1837     if (Subtarget->is64Bit()) {
1838       if (ValVT == MVT::x86mmx) {
1839         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1840           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1841           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1842                                   ValToCopy);
1843           // If we don't have SSE2 available, convert to v4f32 so the generated
1844           // register is legal.
1845           if (!Subtarget->hasSSE2())
1846             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1847         }
1848       }
1849     }
1850
1851     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1852     Flag = Chain.getValue(1);
1853     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1854   }
1855
1856   // The x86-64 ABIs require that for returning structs by value we copy
1857   // the sret argument into %rax/%eax (depending on ABI) for the return.
1858   // Win32 requires us to put the sret argument to %eax as well.
1859   // We saved the argument into a virtual register in the entry block,
1860   // so now we copy the value out and into %rax/%eax.
1861   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1862       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1863     MachineFunction &MF = DAG.getMachineFunction();
1864     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865     unsigned Reg = FuncInfo->getSRetReturnReg();
1866     assert(Reg &&
1867            "SRetReturnReg should have been set in LowerFormalArguments().");
1868     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1869
1870     unsigned RetValReg
1871         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1872           X86::RAX : X86::EAX;
1873     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1874     Flag = Chain.getValue(1);
1875
1876     // RAX/EAX now acts like a return value.
1877     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1878   }
1879
1880   RetOps[0] = Chain;  // Update chain.
1881
1882   // Add the flag if we have it.
1883   if (Flag.getNode())
1884     RetOps.push_back(Flag);
1885
1886   return DAG.getNode(X86ISD::RET_FLAG, dl,
1887                      MVT::Other, &RetOps[0], RetOps.size());
1888 }
1889
1890 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1891   if (N->getNumValues() != 1)
1892     return false;
1893   if (!N->hasNUsesOfValue(1, 0))
1894     return false;
1895
1896   SDValue TCChain = Chain;
1897   SDNode *Copy = *N->use_begin();
1898   if (Copy->getOpcode() == ISD::CopyToReg) {
1899     // If the copy has a glue operand, we conservatively assume it isn't safe to
1900     // perform a tail call.
1901     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1902       return false;
1903     TCChain = Copy->getOperand(0);
1904   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1905     return false;
1906
1907   bool HasRet = false;
1908   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1909        UI != UE; ++UI) {
1910     if (UI->getOpcode() != X86ISD::RET_FLAG)
1911       return false;
1912     HasRet = true;
1913   }
1914
1915   if (!HasRet)
1916     return false;
1917
1918   Chain = TCChain;
1919   return true;
1920 }
1921
1922 MVT
1923 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1924                                             ISD::NodeType ExtendKind) const {
1925   MVT ReturnMVT;
1926   // TODO: Is this also valid on 32-bit?
1927   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1928     ReturnMVT = MVT::i8;
1929   else
1930     ReturnMVT = MVT::i32;
1931
1932   MVT MinVT = getRegisterType(ReturnMVT);
1933   return VT.bitsLT(MinVT) ? MinVT : VT;
1934 }
1935
1936 /// LowerCallResult - Lower the result values of a call into the
1937 /// appropriate copies out of appropriate physical registers.
1938 ///
1939 SDValue
1940 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1941                                    CallingConv::ID CallConv, bool isVarArg,
1942                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1943                                    SDLoc dl, SelectionDAG &DAG,
1944                                    SmallVectorImpl<SDValue> &InVals) const {
1945
1946   // Assign locations to each value returned by this call.
1947   SmallVector<CCValAssign, 16> RVLocs;
1948   bool Is64Bit = Subtarget->is64Bit();
1949   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1950                  getTargetMachine(), RVLocs, *DAG.getContext());
1951   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1952
1953   // Copy all of the result registers out of their specified physreg.
1954   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1955     CCValAssign &VA = RVLocs[i];
1956     EVT CopyVT = VA.getValVT();
1957
1958     // If this is x86-64, and we disabled SSE, we can't return FP values
1959     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1960         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1961       report_fatal_error("SSE register return with SSE disabled");
1962     }
1963
1964     SDValue Val;
1965
1966     // If this is a call to a function that returns an fp value on the floating
1967     // point stack, we must guarantee the value is popped from the stack, so
1968     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1969     // if the return value is not used. We use the FpPOP_RETVAL instruction
1970     // instead.
1971     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1972       // If we prefer to use the value in xmm registers, copy it out as f80 and
1973       // use a truncate to move it from fp stack reg to xmm reg.
1974       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1975       SDValue Ops[] = { Chain, InFlag };
1976       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1977                                          MVT::Other, MVT::Glue, Ops), 1);
1978       Val = Chain.getValue(0);
1979
1980       // Round the f80 to the right size, which also moves it to the appropriate
1981       // xmm register.
1982       if (CopyVT != VA.getValVT())
1983         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1984                           // This truncation won't change the value.
1985                           DAG.getIntPtrConstant(1));
1986     } else {
1987       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1988                                  CopyVT, InFlag).getValue(1);
1989       Val = Chain.getValue(0);
1990     }
1991     InFlag = Chain.getValue(2);
1992     InVals.push_back(Val);
1993   }
1994
1995   return Chain;
1996 }
1997
1998 //===----------------------------------------------------------------------===//
1999 //                C & StdCall & Fast Calling Convention implementation
2000 //===----------------------------------------------------------------------===//
2001 //  StdCall calling convention seems to be standard for many Windows' API
2002 //  routines and around. It differs from C calling convention just a little:
2003 //  callee should clean up the stack, not caller. Symbols should be also
2004 //  decorated in some fancy way :) It doesn't support any vector arguments.
2005 //  For info on fast calling convention see Fast Calling Convention (tail call)
2006 //  implementation LowerX86_32FastCCCallTo.
2007
2008 /// CallIsStructReturn - Determines whether a call uses struct return
2009 /// semantics.
2010 enum StructReturnType {
2011   NotStructReturn,
2012   RegStructReturn,
2013   StackStructReturn
2014 };
2015 static StructReturnType
2016 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2017   if (Outs.empty())
2018     return NotStructReturn;
2019
2020   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2021   if (!Flags.isSRet())
2022     return NotStructReturn;
2023   if (Flags.isInReg())
2024     return RegStructReturn;
2025   return StackStructReturn;
2026 }
2027
2028 /// ArgsAreStructReturn - Determines whether a function uses struct
2029 /// return semantics.
2030 static StructReturnType
2031 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2032   if (Ins.empty())
2033     return NotStructReturn;
2034
2035   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2036   if (!Flags.isSRet())
2037     return NotStructReturn;
2038   if (Flags.isInReg())
2039     return RegStructReturn;
2040   return StackStructReturn;
2041 }
2042
2043 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2044 /// by "Src" to address "Dst" with size and alignment information specified by
2045 /// the specific parameter attribute. The copy will be passed as a byval
2046 /// function parameter.
2047 static SDValue
2048 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2049                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2050                           SDLoc dl) {
2051   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2052
2053   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2054                        /*isVolatile*/false, /*AlwaysInline=*/true,
2055                        MachinePointerInfo(), MachinePointerInfo());
2056 }
2057
2058 /// IsTailCallConvention - Return true if the calling convention is one that
2059 /// supports tail call optimization.
2060 static bool IsTailCallConvention(CallingConv::ID CC) {
2061   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2062           CC == CallingConv::HiPE);
2063 }
2064
2065 /// \brief Return true if the calling convention is a C calling convention.
2066 static bool IsCCallConvention(CallingConv::ID CC) {
2067   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2068           CC == CallingConv::X86_64_SysV);
2069 }
2070
2071 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2072   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2073     return false;
2074
2075   CallSite CS(CI);
2076   CallingConv::ID CalleeCC = CS.getCallingConv();
2077   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2078     return false;
2079
2080   return true;
2081 }
2082
2083 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2084 /// a tailcall target by changing its ABI.
2085 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2086                                    bool GuaranteedTailCallOpt) {
2087   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2088 }
2089
2090 SDValue
2091 X86TargetLowering::LowerMemArgument(SDValue Chain,
2092                                     CallingConv::ID CallConv,
2093                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2094                                     SDLoc dl, SelectionDAG &DAG,
2095                                     const CCValAssign &VA,
2096                                     MachineFrameInfo *MFI,
2097                                     unsigned i) const {
2098   // Create the nodes corresponding to a load from this parameter slot.
2099   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2100   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2101                               getTargetMachine().Options.GuaranteedTailCallOpt);
2102   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2103   EVT ValVT;
2104
2105   // If value is passed by pointer we have address passed instead of the value
2106   // itself.
2107   if (VA.getLocInfo() == CCValAssign::Indirect)
2108     ValVT = VA.getLocVT();
2109   else
2110     ValVT = VA.getValVT();
2111
2112   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2113   // changed with more analysis.
2114   // In case of tail call optimization mark all arguments mutable. Since they
2115   // could be overwritten by lowering of arguments in case of a tail call.
2116   if (Flags.isByVal()) {
2117     unsigned Bytes = Flags.getByValSize();
2118     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2119     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2120     return DAG.getFrameIndex(FI, getPointerTy());
2121   } else {
2122     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2123                                     VA.getLocMemOffset(), isImmutable);
2124     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2125     return DAG.getLoad(ValVT, dl, Chain, FIN,
2126                        MachinePointerInfo::getFixedStack(FI),
2127                        false, false, false, 0);
2128   }
2129 }
2130
2131 SDValue
2132 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2133                                         CallingConv::ID CallConv,
2134                                         bool isVarArg,
2135                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2136                                         SDLoc dl,
2137                                         SelectionDAG &DAG,
2138                                         SmallVectorImpl<SDValue> &InVals)
2139                                           const {
2140   MachineFunction &MF = DAG.getMachineFunction();
2141   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2142
2143   const Function* Fn = MF.getFunction();
2144   if (Fn->hasExternalLinkage() &&
2145       Subtarget->isTargetCygMing() &&
2146       Fn->getName() == "main")
2147     FuncInfo->setForceFramePointer(true);
2148
2149   MachineFrameInfo *MFI = MF.getFrameInfo();
2150   bool Is64Bit = Subtarget->is64Bit();
2151   bool IsWindows = Subtarget->isTargetWindows();
2152   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2153
2154   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2155          "Var args not supported with calling convention fastcc, ghc or hipe");
2156
2157   // Assign locations to all of the incoming arguments.
2158   SmallVector<CCValAssign, 16> ArgLocs;
2159   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2160                  ArgLocs, *DAG.getContext());
2161
2162   // Allocate shadow area for Win64
2163   if (IsWin64)
2164     CCInfo.AllocateStack(32, 8);
2165
2166   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2167
2168   unsigned LastVal = ~0U;
2169   SDValue ArgValue;
2170   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2171     CCValAssign &VA = ArgLocs[i];
2172     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2173     // places.
2174     assert(VA.getValNo() != LastVal &&
2175            "Don't support value assigned to multiple locs yet");
2176     (void)LastVal;
2177     LastVal = VA.getValNo();
2178
2179     if (VA.isRegLoc()) {
2180       EVT RegVT = VA.getLocVT();
2181       const TargetRegisterClass *RC;
2182       if (RegVT == MVT::i32)
2183         RC = &X86::GR32RegClass;
2184       else if (Is64Bit && RegVT == MVT::i64)
2185         RC = &X86::GR64RegClass;
2186       else if (RegVT == MVT::f32)
2187         RC = &X86::FR32RegClass;
2188       else if (RegVT == MVT::f64)
2189         RC = &X86::FR64RegClass;
2190       else if (RegVT.is512BitVector())
2191         RC = &X86::VR512RegClass;
2192       else if (RegVT.is256BitVector())
2193         RC = &X86::VR256RegClass;
2194       else if (RegVT.is128BitVector())
2195         RC = &X86::VR128RegClass;
2196       else if (RegVT == MVT::x86mmx)
2197         RC = &X86::VR64RegClass;
2198       else if (RegVT == MVT::v8i1)
2199         RC = &X86::VK8RegClass;
2200       else if (RegVT == MVT::v16i1)
2201         RC = &X86::VK16RegClass;
2202       else
2203         llvm_unreachable("Unknown argument type!");
2204
2205       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2206       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2207
2208       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2209       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2210       // right size.
2211       if (VA.getLocInfo() == CCValAssign::SExt)
2212         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2213                                DAG.getValueType(VA.getValVT()));
2214       else if (VA.getLocInfo() == CCValAssign::ZExt)
2215         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2216                                DAG.getValueType(VA.getValVT()));
2217       else if (VA.getLocInfo() == CCValAssign::BCvt)
2218         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2219
2220       if (VA.isExtInLoc()) {
2221         // Handle MMX values passed in XMM regs.
2222         if (RegVT.isVector())
2223           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2224         else
2225           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2226       }
2227     } else {
2228       assert(VA.isMemLoc());
2229       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2230     }
2231
2232     // If value is passed via pointer - do a load.
2233     if (VA.getLocInfo() == CCValAssign::Indirect)
2234       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2235                              MachinePointerInfo(), false, false, false, 0);
2236
2237     InVals.push_back(ArgValue);
2238   }
2239
2240   // The x86-64 ABIs require that for returning structs by value we copy
2241   // the sret argument into %rax/%eax (depending on ABI) for the return.
2242   // Win32 requires us to put the sret argument to %eax as well.
2243   // Save the argument into a virtual register so that we can access it
2244   // from the return points.
2245   if (MF.getFunction()->hasStructRetAttr() &&
2246       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2247     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2248     unsigned Reg = FuncInfo->getSRetReturnReg();
2249     if (!Reg) {
2250       MVT PtrTy = getPointerTy();
2251       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2252       FuncInfo->setSRetReturnReg(Reg);
2253     }
2254     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2255     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2256   }
2257
2258   unsigned StackSize = CCInfo.getNextStackOffset();
2259   // Align stack specially for tail calls.
2260   if (FuncIsMadeTailCallSafe(CallConv,
2261                              MF.getTarget().Options.GuaranteedTailCallOpt))
2262     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2263
2264   // If the function takes variable number of arguments, make a frame index for
2265   // the start of the first vararg value... for expansion of llvm.va_start.
2266   if (isVarArg) {
2267     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2268                     CallConv != CallingConv::X86_ThisCall)) {
2269       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2270     }
2271     if (Is64Bit) {
2272       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2273
2274       // FIXME: We should really autogenerate these arrays
2275       static const uint16_t GPR64ArgRegsWin64[] = {
2276         X86::RCX, X86::RDX, X86::R8,  X86::R9
2277       };
2278       static const uint16_t GPR64ArgRegs64Bit[] = {
2279         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2280       };
2281       static const uint16_t XMMArgRegs64Bit[] = {
2282         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2283         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2284       };
2285       const uint16_t *GPR64ArgRegs;
2286       unsigned NumXMMRegs = 0;
2287
2288       if (IsWin64) {
2289         // The XMM registers which might contain var arg parameters are shadowed
2290         // in their paired GPR.  So we only need to save the GPR to their home
2291         // slots.
2292         TotalNumIntRegs = 4;
2293         GPR64ArgRegs = GPR64ArgRegsWin64;
2294       } else {
2295         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2296         GPR64ArgRegs = GPR64ArgRegs64Bit;
2297
2298         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2299                                                 TotalNumXMMRegs);
2300       }
2301       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2302                                                        TotalNumIntRegs);
2303
2304       bool NoImplicitFloatOps = Fn->getAttributes().
2305         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2306       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2307              "SSE register cannot be used when SSE is disabled!");
2308       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2309                NoImplicitFloatOps) &&
2310              "SSE register cannot be used when SSE is disabled!");
2311       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2312           !Subtarget->hasSSE1())
2313         // Kernel mode asks for SSE to be disabled, so don't push them
2314         // on the stack.
2315         TotalNumXMMRegs = 0;
2316
2317       if (IsWin64) {
2318         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2319         // Get to the caller-allocated home save location.  Add 8 to account
2320         // for the return address.
2321         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2322         FuncInfo->setRegSaveFrameIndex(
2323           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2324         // Fixup to set vararg frame on shadow area (4 x i64).
2325         if (NumIntRegs < 4)
2326           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2327       } else {
2328         // For X86-64, if there are vararg parameters that are passed via
2329         // registers, then we must store them to their spots on the stack so
2330         // they may be loaded by deferencing the result of va_next.
2331         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2332         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2333         FuncInfo->setRegSaveFrameIndex(
2334           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2335                                false));
2336       }
2337
2338       // Store the integer parameter registers.
2339       SmallVector<SDValue, 8> MemOps;
2340       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2341                                         getPointerTy());
2342       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2343       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2344         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2345                                   DAG.getIntPtrConstant(Offset));
2346         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2347                                      &X86::GR64RegClass);
2348         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2349         SDValue Store =
2350           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2351                        MachinePointerInfo::getFixedStack(
2352                          FuncInfo->getRegSaveFrameIndex(), Offset),
2353                        false, false, 0);
2354         MemOps.push_back(Store);
2355         Offset += 8;
2356       }
2357
2358       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2359         // Now store the XMM (fp + vector) parameter registers.
2360         SmallVector<SDValue, 11> SaveXMMOps;
2361         SaveXMMOps.push_back(Chain);
2362
2363         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2364         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2365         SaveXMMOps.push_back(ALVal);
2366
2367         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2368                                FuncInfo->getRegSaveFrameIndex()));
2369         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2370                                FuncInfo->getVarArgsFPOffset()));
2371
2372         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2373           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2374                                        &X86::VR128RegClass);
2375           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2376           SaveXMMOps.push_back(Val);
2377         }
2378         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2379                                      MVT::Other,
2380                                      &SaveXMMOps[0], SaveXMMOps.size()));
2381       }
2382
2383       if (!MemOps.empty())
2384         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2385                             &MemOps[0], MemOps.size());
2386     }
2387   }
2388
2389   // Some CCs need callee pop.
2390   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2391                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2392     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2393   } else {
2394     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2395     // If this is an sret function, the return should pop the hidden pointer.
2396     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2397         argsAreStructReturn(Ins) == StackStructReturn)
2398       FuncInfo->setBytesToPopOnReturn(4);
2399   }
2400
2401   if (!Is64Bit) {
2402     // RegSaveFrameIndex is X86-64 only.
2403     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2404     if (CallConv == CallingConv::X86_FastCall ||
2405         CallConv == CallingConv::X86_ThisCall)
2406       // fastcc functions can't have varargs.
2407       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2408   }
2409
2410   FuncInfo->setArgumentStackSize(StackSize);
2411
2412   return Chain;
2413 }
2414
2415 SDValue
2416 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2417                                     SDValue StackPtr, SDValue Arg,
2418                                     SDLoc dl, SelectionDAG &DAG,
2419                                     const CCValAssign &VA,
2420                                     ISD::ArgFlagsTy Flags) const {
2421   unsigned LocMemOffset = VA.getLocMemOffset();
2422   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2423   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2424   if (Flags.isByVal())
2425     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2426
2427   return DAG.getStore(Chain, dl, Arg, PtrOff,
2428                       MachinePointerInfo::getStack(LocMemOffset),
2429                       false, false, 0);
2430 }
2431
2432 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2433 /// optimization is performed and it is required.
2434 SDValue
2435 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2436                                            SDValue &OutRetAddr, SDValue Chain,
2437                                            bool IsTailCall, bool Is64Bit,
2438                                            int FPDiff, SDLoc dl) const {
2439   // Adjust the Return address stack slot.
2440   EVT VT = getPointerTy();
2441   OutRetAddr = getReturnAddressFrameIndex(DAG);
2442
2443   // Load the "old" Return address.
2444   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2445                            false, false, false, 0);
2446   return SDValue(OutRetAddr.getNode(), 1);
2447 }
2448
2449 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2450 /// optimization is performed and it is required (FPDiff!=0).
2451 static SDValue
2452 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2453                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2454                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2455   // Store the return address to the appropriate stack slot.
2456   if (!FPDiff) return Chain;
2457   // Calculate the new stack slot for the return address.
2458   int NewReturnAddrFI =
2459     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2460                                          false);
2461   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2462   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2463                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2464                        false, false, 0);
2465   return Chain;
2466 }
2467
2468 SDValue
2469 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2470                              SmallVectorImpl<SDValue> &InVals) const {
2471   SelectionDAG &DAG                     = CLI.DAG;
2472   SDLoc &dl                             = CLI.DL;
2473   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2474   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2475   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2476   SDValue Chain                         = CLI.Chain;
2477   SDValue Callee                        = CLI.Callee;
2478   CallingConv::ID CallConv              = CLI.CallConv;
2479   bool &isTailCall                      = CLI.IsTailCall;
2480   bool isVarArg                         = CLI.IsVarArg;
2481
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   bool Is64Bit        = Subtarget->is64Bit();
2484   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2485   bool IsWindows      = Subtarget->isTargetWindows();
2486   StructReturnType SR = callIsStructReturn(Outs);
2487   bool IsSibcall      = false;
2488
2489   if (MF.getTarget().Options.DisableTailCalls)
2490     isTailCall = false;
2491
2492   if (isTailCall) {
2493     // Check if it's really possible to do a tail call.
2494     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2495                     isVarArg, SR != NotStructReturn,
2496                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2497                     Outs, OutVals, Ins, DAG);
2498
2499     // Sibcalls are automatically detected tailcalls which do not require
2500     // ABI changes.
2501     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2502       IsSibcall = true;
2503
2504     if (isTailCall)
2505       ++NumTailCalls;
2506   }
2507
2508   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2509          "Var args not supported with calling convention fastcc, ghc or hipe");
2510
2511   // Analyze operands of the call, assigning locations to each operand.
2512   SmallVector<CCValAssign, 16> ArgLocs;
2513   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2514                  ArgLocs, *DAG.getContext());
2515
2516   // Allocate shadow area for Win64
2517   if (IsWin64)
2518     CCInfo.AllocateStack(32, 8);
2519
2520   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2521
2522   // Get a count of how many bytes are to be pushed on the stack.
2523   unsigned NumBytes = CCInfo.getNextStackOffset();
2524   if (IsSibcall)
2525     // This is a sibcall. The memory operands are available in caller's
2526     // own caller's stack.
2527     NumBytes = 0;
2528   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2529            IsTailCallConvention(CallConv))
2530     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2531
2532   int FPDiff = 0;
2533   if (isTailCall && !IsSibcall) {
2534     // Lower arguments at fp - stackoffset + fpdiff.
2535     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2536     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2537
2538     FPDiff = NumBytesCallerPushed - NumBytes;
2539
2540     // Set the delta of movement of the returnaddr stackslot.
2541     // But only set if delta is greater than previous delta.
2542     if (FPDiff < X86Info->getTCReturnAddrDelta())
2543       X86Info->setTCReturnAddrDelta(FPDiff);
2544   }
2545
2546   if (!IsSibcall)
2547     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2548                                  dl);
2549
2550   SDValue RetAddrFrIdx;
2551   // Load return address for tail calls.
2552   if (isTailCall && FPDiff)
2553     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2554                                     Is64Bit, FPDiff, dl);
2555
2556   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2557   SmallVector<SDValue, 8> MemOpChains;
2558   SDValue StackPtr;
2559
2560   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2561   // of tail call optimization arguments are handle later.
2562   const X86RegisterInfo *RegInfo =
2563     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2564   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2565     CCValAssign &VA = ArgLocs[i];
2566     EVT RegVT = VA.getLocVT();
2567     SDValue Arg = OutVals[i];
2568     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2569     bool isByVal = Flags.isByVal();
2570
2571     // Promote the value if needed.
2572     switch (VA.getLocInfo()) {
2573     default: llvm_unreachable("Unknown loc info!");
2574     case CCValAssign::Full: break;
2575     case CCValAssign::SExt:
2576       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2577       break;
2578     case CCValAssign::ZExt:
2579       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2580       break;
2581     case CCValAssign::AExt:
2582       if (RegVT.is128BitVector()) {
2583         // Special case: passing MMX values in XMM registers.
2584         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2585         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2586         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2587       } else
2588         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2589       break;
2590     case CCValAssign::BCvt:
2591       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2592       break;
2593     case CCValAssign::Indirect: {
2594       // Store the argument.
2595       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2596       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2597       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2598                            MachinePointerInfo::getFixedStack(FI),
2599                            false, false, 0);
2600       Arg = SpillSlot;
2601       break;
2602     }
2603     }
2604
2605     if (VA.isRegLoc()) {
2606       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2607       if (isVarArg && IsWin64) {
2608         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2609         // shadow reg if callee is a varargs function.
2610         unsigned ShadowReg = 0;
2611         switch (VA.getLocReg()) {
2612         case X86::XMM0: ShadowReg = X86::RCX; break;
2613         case X86::XMM1: ShadowReg = X86::RDX; break;
2614         case X86::XMM2: ShadowReg = X86::R8; break;
2615         case X86::XMM3: ShadowReg = X86::R9; break;
2616         }
2617         if (ShadowReg)
2618           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2619       }
2620     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2621       assert(VA.isMemLoc());
2622       if (StackPtr.getNode() == 0)
2623         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2624                                       getPointerTy());
2625       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2626                                              dl, DAG, VA, Flags));
2627     }
2628   }
2629
2630   if (!MemOpChains.empty())
2631     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2632                         &MemOpChains[0], MemOpChains.size());
2633
2634   if (Subtarget->isPICStyleGOT()) {
2635     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2636     // GOT pointer.
2637     if (!isTailCall) {
2638       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2639                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2640     } else {
2641       // If we are tail calling and generating PIC/GOT style code load the
2642       // address of the callee into ECX. The value in ecx is used as target of
2643       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2644       // for tail calls on PIC/GOT architectures. Normally we would just put the
2645       // address of GOT into ebx and then call target@PLT. But for tail calls
2646       // ebx would be restored (since ebx is callee saved) before jumping to the
2647       // target@PLT.
2648
2649       // Note: The actual moving to ECX is done further down.
2650       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2651       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2652           !G->getGlobal()->hasProtectedVisibility())
2653         Callee = LowerGlobalAddress(Callee, DAG);
2654       else if (isa<ExternalSymbolSDNode>(Callee))
2655         Callee = LowerExternalSymbol(Callee, DAG);
2656     }
2657   }
2658
2659   if (Is64Bit && isVarArg && !IsWin64) {
2660     // From AMD64 ABI document:
2661     // For calls that may call functions that use varargs or stdargs
2662     // (prototype-less calls or calls to functions containing ellipsis (...) in
2663     // the declaration) %al is used as hidden argument to specify the number
2664     // of SSE registers used. The contents of %al do not need to match exactly
2665     // the number of registers, but must be an ubound on the number of SSE
2666     // registers used and is in the range 0 - 8 inclusive.
2667
2668     // Count the number of XMM registers allocated.
2669     static const uint16_t XMMArgRegs[] = {
2670       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2671       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2672     };
2673     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2674     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2675            && "SSE registers cannot be used when SSE is disabled");
2676
2677     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2678                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2679   }
2680
2681   // For tail calls lower the arguments to the 'real' stack slot.
2682   if (isTailCall) {
2683     // Force all the incoming stack arguments to be loaded from the stack
2684     // before any new outgoing arguments are stored to the stack, because the
2685     // outgoing stack slots may alias the incoming argument stack slots, and
2686     // the alias isn't otherwise explicit. This is slightly more conservative
2687     // than necessary, because it means that each store effectively depends
2688     // on every argument instead of just those arguments it would clobber.
2689     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2690
2691     SmallVector<SDValue, 8> MemOpChains2;
2692     SDValue FIN;
2693     int FI = 0;
2694     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2695       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696         CCValAssign &VA = ArgLocs[i];
2697         if (VA.isRegLoc())
2698           continue;
2699         assert(VA.isMemLoc());
2700         SDValue Arg = OutVals[i];
2701         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2702         // Create frame index.
2703         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2704         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2705         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2706         FIN = DAG.getFrameIndex(FI, getPointerTy());
2707
2708         if (Flags.isByVal()) {
2709           // Copy relative to framepointer.
2710           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2711           if (StackPtr.getNode() == 0)
2712             StackPtr = DAG.getCopyFromReg(Chain, dl,
2713                                           RegInfo->getStackRegister(),
2714                                           getPointerTy());
2715           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2716
2717           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2718                                                            ArgChain,
2719                                                            Flags, DAG, dl));
2720         } else {
2721           // Store relative to framepointer.
2722           MemOpChains2.push_back(
2723             DAG.getStore(ArgChain, dl, Arg, FIN,
2724                          MachinePointerInfo::getFixedStack(FI),
2725                          false, false, 0));
2726         }
2727       }
2728     }
2729
2730     if (!MemOpChains2.empty())
2731       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2732                           &MemOpChains2[0], MemOpChains2.size());
2733
2734     // Store the return address to the appropriate stack slot.
2735     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2736                                      getPointerTy(), RegInfo->getSlotSize(),
2737                                      FPDiff, dl);
2738   }
2739
2740   // Build a sequence of copy-to-reg nodes chained together with token chain
2741   // and flag operands which copy the outgoing args into registers.
2742   SDValue InFlag;
2743   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2744     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2745                              RegsToPass[i].second, InFlag);
2746     InFlag = Chain.getValue(1);
2747   }
2748
2749   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2750     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2751     // In the 64-bit large code model, we have to make all calls
2752     // through a register, since the call instruction's 32-bit
2753     // pc-relative offset may not be large enough to hold the whole
2754     // address.
2755   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2756     // If the callee is a GlobalAddress node (quite common, every direct call
2757     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2758     // it.
2759
2760     // We should use extra load for direct calls to dllimported functions in
2761     // non-JIT mode.
2762     const GlobalValue *GV = G->getGlobal();
2763     if (!GV->hasDLLImportLinkage()) {
2764       unsigned char OpFlags = 0;
2765       bool ExtraLoad = false;
2766       unsigned WrapperKind = ISD::DELETED_NODE;
2767
2768       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2769       // external symbols most go through the PLT in PIC mode.  If the symbol
2770       // has hidden or protected visibility, or if it is static or local, then
2771       // we don't need to use the PLT - we can directly call it.
2772       if (Subtarget->isTargetELF() &&
2773           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2774           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2775         OpFlags = X86II::MO_PLT;
2776       } else if (Subtarget->isPICStyleStubAny() &&
2777                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2778                  (!Subtarget->getTargetTriple().isMacOSX() ||
2779                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2780         // PC-relative references to external symbols should go through $stub,
2781         // unless we're building with the leopard linker or later, which
2782         // automatically synthesizes these stubs.
2783         OpFlags = X86II::MO_DARWIN_STUB;
2784       } else if (Subtarget->isPICStyleRIPRel() &&
2785                  isa<Function>(GV) &&
2786                  cast<Function>(GV)->getAttributes().
2787                    hasAttribute(AttributeSet::FunctionIndex,
2788                                 Attribute::NonLazyBind)) {
2789         // If the function is marked as non-lazy, generate an indirect call
2790         // which loads from the GOT directly. This avoids runtime overhead
2791         // at the cost of eager binding (and one extra byte of encoding).
2792         OpFlags = X86II::MO_GOTPCREL;
2793         WrapperKind = X86ISD::WrapperRIP;
2794         ExtraLoad = true;
2795       }
2796
2797       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2798                                           G->getOffset(), OpFlags);
2799
2800       // Add a wrapper if needed.
2801       if (WrapperKind != ISD::DELETED_NODE)
2802         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2803       // Add extra indirection if needed.
2804       if (ExtraLoad)
2805         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2806                              MachinePointerInfo::getGOT(),
2807                              false, false, false, 0);
2808     }
2809   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2810     unsigned char OpFlags = 0;
2811
2812     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2813     // external symbols should go through the PLT.
2814     if (Subtarget->isTargetELF() &&
2815         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2816       OpFlags = X86II::MO_PLT;
2817     } else if (Subtarget->isPICStyleStubAny() &&
2818                (!Subtarget->getTargetTriple().isMacOSX() ||
2819                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2820       // PC-relative references to external symbols should go through $stub,
2821       // unless we're building with the leopard linker or later, which
2822       // automatically synthesizes these stubs.
2823       OpFlags = X86II::MO_DARWIN_STUB;
2824     }
2825
2826     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2827                                          OpFlags);
2828   }
2829
2830   // Returns a chain & a flag for retval copy to use.
2831   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2832   SmallVector<SDValue, 8> Ops;
2833
2834   if (!IsSibcall && isTailCall) {
2835     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2836                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2837     InFlag = Chain.getValue(1);
2838   }
2839
2840   Ops.push_back(Chain);
2841   Ops.push_back(Callee);
2842
2843   if (isTailCall)
2844     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2845
2846   // Add argument registers to the end of the list so that they are known live
2847   // into the call.
2848   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2849     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2850                                   RegsToPass[i].second.getValueType()));
2851
2852   // Add a register mask operand representing the call-preserved registers.
2853   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2854   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2855   assert(Mask && "Missing call preserved mask for calling convention");
2856   Ops.push_back(DAG.getRegisterMask(Mask));
2857
2858   if (InFlag.getNode())
2859     Ops.push_back(InFlag);
2860
2861   if (isTailCall) {
2862     // We used to do:
2863     //// If this is the first return lowered for this function, add the regs
2864     //// to the liveout set for the function.
2865     // This isn't right, although it's probably harmless on x86; liveouts
2866     // should be computed from returns not tail calls.  Consider a void
2867     // function making a tail call to a function returning int.
2868     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2869   }
2870
2871   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2872   InFlag = Chain.getValue(1);
2873
2874   // Create the CALLSEQ_END node.
2875   unsigned NumBytesForCalleeToPush;
2876   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2877                        getTargetMachine().Options.GuaranteedTailCallOpt))
2878     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2879   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2880            SR == StackStructReturn)
2881     // If this is a call to a struct-return function, the callee
2882     // pops the hidden struct pointer, so we have to push it back.
2883     // This is common for Darwin/X86, Linux & Mingw32 targets.
2884     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2885     NumBytesForCalleeToPush = 4;
2886   else
2887     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2888
2889   // Returns a flag for retval copy to use.
2890   if (!IsSibcall) {
2891     Chain = DAG.getCALLSEQ_END(Chain,
2892                                DAG.getIntPtrConstant(NumBytes, true),
2893                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2894                                                      true),
2895                                InFlag, dl);
2896     InFlag = Chain.getValue(1);
2897   }
2898
2899   // Handle result values, copying them out of physregs into vregs that we
2900   // return.
2901   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2902                          Ins, dl, DAG, InVals);
2903 }
2904
2905 //===----------------------------------------------------------------------===//
2906 //                Fast Calling Convention (tail call) implementation
2907 //===----------------------------------------------------------------------===//
2908
2909 //  Like std call, callee cleans arguments, convention except that ECX is
2910 //  reserved for storing the tail called function address. Only 2 registers are
2911 //  free for argument passing (inreg). Tail call optimization is performed
2912 //  provided:
2913 //                * tailcallopt is enabled
2914 //                * caller/callee are fastcc
2915 //  On X86_64 architecture with GOT-style position independent code only local
2916 //  (within module) calls are supported at the moment.
2917 //  To keep the stack aligned according to platform abi the function
2918 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2919 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2920 //  If a tail called function callee has more arguments than the caller the
2921 //  caller needs to make sure that there is room to move the RETADDR to. This is
2922 //  achieved by reserving an area the size of the argument delta right after the
2923 //  original REtADDR, but before the saved framepointer or the spilled registers
2924 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2925 //  stack layout:
2926 //    arg1
2927 //    arg2
2928 //    RETADDR
2929 //    [ new RETADDR
2930 //      move area ]
2931 //    (possible EBP)
2932 //    ESI
2933 //    EDI
2934 //    local1 ..
2935
2936 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2937 /// for a 16 byte align requirement.
2938 unsigned
2939 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2940                                                SelectionDAG& DAG) const {
2941   MachineFunction &MF = DAG.getMachineFunction();
2942   const TargetMachine &TM = MF.getTarget();
2943   const X86RegisterInfo *RegInfo =
2944     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2945   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2946   unsigned StackAlignment = TFI.getStackAlignment();
2947   uint64_t AlignMask = StackAlignment - 1;
2948   int64_t Offset = StackSize;
2949   unsigned SlotSize = RegInfo->getSlotSize();
2950   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2951     // Number smaller than 12 so just add the difference.
2952     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2953   } else {
2954     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2955     Offset = ((~AlignMask) & Offset) + StackAlignment +
2956       (StackAlignment-SlotSize);
2957   }
2958   return Offset;
2959 }
2960
2961 /// MatchingStackOffset - Return true if the given stack call argument is
2962 /// already available in the same position (relatively) of the caller's
2963 /// incoming argument stack.
2964 static
2965 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2966                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2967                          const X86InstrInfo *TII) {
2968   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2969   int FI = INT_MAX;
2970   if (Arg.getOpcode() == ISD::CopyFromReg) {
2971     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2972     if (!TargetRegisterInfo::isVirtualRegister(VR))
2973       return false;
2974     MachineInstr *Def = MRI->getVRegDef(VR);
2975     if (!Def)
2976       return false;
2977     if (!Flags.isByVal()) {
2978       if (!TII->isLoadFromStackSlot(Def, FI))
2979         return false;
2980     } else {
2981       unsigned Opcode = Def->getOpcode();
2982       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2983           Def->getOperand(1).isFI()) {
2984         FI = Def->getOperand(1).getIndex();
2985         Bytes = Flags.getByValSize();
2986       } else
2987         return false;
2988     }
2989   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2990     if (Flags.isByVal())
2991       // ByVal argument is passed in as a pointer but it's now being
2992       // dereferenced. e.g.
2993       // define @foo(%struct.X* %A) {
2994       //   tail call @bar(%struct.X* byval %A)
2995       // }
2996       return false;
2997     SDValue Ptr = Ld->getBasePtr();
2998     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2999     if (!FINode)
3000       return false;
3001     FI = FINode->getIndex();
3002   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3003     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3004     FI = FINode->getIndex();
3005     Bytes = Flags.getByValSize();
3006   } else
3007     return false;
3008
3009   assert(FI != INT_MAX);
3010   if (!MFI->isFixedObjectIndex(FI))
3011     return false;
3012   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3013 }
3014
3015 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3016 /// for tail call optimization. Targets which want to do tail call
3017 /// optimization should implement this function.
3018 bool
3019 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3020                                                      CallingConv::ID CalleeCC,
3021                                                      bool isVarArg,
3022                                                      bool isCalleeStructRet,
3023                                                      bool isCallerStructRet,
3024                                                      Type *RetTy,
3025                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3026                                     const SmallVectorImpl<SDValue> &OutVals,
3027                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3028                                                      SelectionDAG &DAG) const {
3029   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3030     return false;
3031
3032   // If -tailcallopt is specified, make fastcc functions tail-callable.
3033   const MachineFunction &MF = DAG.getMachineFunction();
3034   const Function *CallerF = MF.getFunction();
3035
3036   // If the function return type is x86_fp80 and the callee return type is not,
3037   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3038   // perform a tailcall optimization here.
3039   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3040     return false;
3041
3042   CallingConv::ID CallerCC = CallerF->getCallingConv();
3043   bool CCMatch = CallerCC == CalleeCC;
3044   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3045   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3046
3047   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3048     if (IsTailCallConvention(CalleeCC) && CCMatch)
3049       return true;
3050     return false;
3051   }
3052
3053   // Look for obvious safe cases to perform tail call optimization that do not
3054   // require ABI changes. This is what gcc calls sibcall.
3055
3056   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3057   // emit a special epilogue.
3058   const X86RegisterInfo *RegInfo =
3059     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3060   if (RegInfo->needsStackRealignment(MF))
3061     return false;
3062
3063   // Also avoid sibcall optimization if either caller or callee uses struct
3064   // return semantics.
3065   if (isCalleeStructRet || isCallerStructRet)
3066     return false;
3067
3068   // An stdcall caller is expected to clean up its arguments; the callee
3069   // isn't going to do that.
3070   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3071     return false;
3072
3073   // Do not sibcall optimize vararg calls unless all arguments are passed via
3074   // registers.
3075   if (isVarArg && !Outs.empty()) {
3076
3077     // Optimizing for varargs on Win64 is unlikely to be safe without
3078     // additional testing.
3079     if (IsCalleeWin64 || IsCallerWin64)
3080       return false;
3081
3082     SmallVector<CCValAssign, 16> ArgLocs;
3083     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3084                    getTargetMachine(), ArgLocs, *DAG.getContext());
3085
3086     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3087     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3088       if (!ArgLocs[i].isRegLoc())
3089         return false;
3090   }
3091
3092   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3093   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3094   // this into a sibcall.
3095   bool Unused = false;
3096   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3097     if (!Ins[i].Used) {
3098       Unused = true;
3099       break;
3100     }
3101   }
3102   if (Unused) {
3103     SmallVector<CCValAssign, 16> RVLocs;
3104     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3105                    getTargetMachine(), RVLocs, *DAG.getContext());
3106     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3107     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3108       CCValAssign &VA = RVLocs[i];
3109       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3110         return false;
3111     }
3112   }
3113
3114   // If the calling conventions do not match, then we'd better make sure the
3115   // results are returned in the same way as what the caller expects.
3116   if (!CCMatch) {
3117     SmallVector<CCValAssign, 16> RVLocs1;
3118     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3119                     getTargetMachine(), RVLocs1, *DAG.getContext());
3120     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3121
3122     SmallVector<CCValAssign, 16> RVLocs2;
3123     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3124                     getTargetMachine(), RVLocs2, *DAG.getContext());
3125     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3126
3127     if (RVLocs1.size() != RVLocs2.size())
3128       return false;
3129     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3130       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3131         return false;
3132       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3133         return false;
3134       if (RVLocs1[i].isRegLoc()) {
3135         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3136           return false;
3137       } else {
3138         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3139           return false;
3140       }
3141     }
3142   }
3143
3144   // If the callee takes no arguments then go on to check the results of the
3145   // call.
3146   if (!Outs.empty()) {
3147     // Check if stack adjustment is needed. For now, do not do this if any
3148     // argument is passed on the stack.
3149     SmallVector<CCValAssign, 16> ArgLocs;
3150     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3151                    getTargetMachine(), ArgLocs, *DAG.getContext());
3152
3153     // Allocate shadow area for Win64
3154     if (IsCalleeWin64)
3155       CCInfo.AllocateStack(32, 8);
3156
3157     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3158     if (CCInfo.getNextStackOffset()) {
3159       MachineFunction &MF = DAG.getMachineFunction();
3160       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3161         return false;
3162
3163       // Check if the arguments are already laid out in the right way as
3164       // the caller's fixed stack objects.
3165       MachineFrameInfo *MFI = MF.getFrameInfo();
3166       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3167       const X86InstrInfo *TII =
3168         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3169       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3170         CCValAssign &VA = ArgLocs[i];
3171         SDValue Arg = OutVals[i];
3172         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3173         if (VA.getLocInfo() == CCValAssign::Indirect)
3174           return false;
3175         if (!VA.isRegLoc()) {
3176           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3177                                    MFI, MRI, TII))
3178             return false;
3179         }
3180       }
3181     }
3182
3183     // If the tailcall address may be in a register, then make sure it's
3184     // possible to register allocate for it. In 32-bit, the call address can
3185     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3186     // callee-saved registers are restored. These happen to be the same
3187     // registers used to pass 'inreg' arguments so watch out for those.
3188     if (!Subtarget->is64Bit() &&
3189         ((!isa<GlobalAddressSDNode>(Callee) &&
3190           !isa<ExternalSymbolSDNode>(Callee)) ||
3191          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3192       unsigned NumInRegs = 0;
3193       // In PIC we need an extra register to formulate the address computation
3194       // for the callee.
3195       unsigned MaxInRegs =
3196           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3197
3198       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199         CCValAssign &VA = ArgLocs[i];
3200         if (!VA.isRegLoc())
3201           continue;
3202         unsigned Reg = VA.getLocReg();
3203         switch (Reg) {
3204         default: break;
3205         case X86::EAX: case X86::EDX: case X86::ECX:
3206           if (++NumInRegs == MaxInRegs)
3207             return false;
3208           break;
3209         }
3210       }
3211     }
3212   }
3213
3214   return true;
3215 }
3216
3217 FastISel *
3218 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3219                                   const TargetLibraryInfo *libInfo) const {
3220   return X86::createFastISel(funcInfo, libInfo);
3221 }
3222
3223 //===----------------------------------------------------------------------===//
3224 //                           Other Lowering Hooks
3225 //===----------------------------------------------------------------------===//
3226
3227 static bool MayFoldLoad(SDValue Op) {
3228   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3229 }
3230
3231 static bool MayFoldIntoStore(SDValue Op) {
3232   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3233 }
3234
3235 static bool isTargetShuffle(unsigned Opcode) {
3236   switch(Opcode) {
3237   default: return false;
3238   case X86ISD::PSHUFD:
3239   case X86ISD::PSHUFHW:
3240   case X86ISD::PSHUFLW:
3241   case X86ISD::SHUFP:
3242   case X86ISD::PALIGNR:
3243   case X86ISD::MOVLHPS:
3244   case X86ISD::MOVLHPD:
3245   case X86ISD::MOVHLPS:
3246   case X86ISD::MOVLPS:
3247   case X86ISD::MOVLPD:
3248   case X86ISD::MOVSHDUP:
3249   case X86ISD::MOVSLDUP:
3250   case X86ISD::MOVDDUP:
3251   case X86ISD::MOVSS:
3252   case X86ISD::MOVSD:
3253   case X86ISD::UNPCKL:
3254   case X86ISD::UNPCKH:
3255   case X86ISD::VPERMILP:
3256   case X86ISD::VPERM2X128:
3257   case X86ISD::VPERMI:
3258     return true;
3259   }
3260 }
3261
3262 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3263                                     SDValue V1, SelectionDAG &DAG) {
3264   switch(Opc) {
3265   default: llvm_unreachable("Unknown x86 shuffle node");
3266   case X86ISD::MOVSHDUP:
3267   case X86ISD::MOVSLDUP:
3268   case X86ISD::MOVDDUP:
3269     return DAG.getNode(Opc, dl, VT, V1);
3270   }
3271 }
3272
3273 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3274                                     SDValue V1, unsigned TargetMask,
3275                                     SelectionDAG &DAG) {
3276   switch(Opc) {
3277   default: llvm_unreachable("Unknown x86 shuffle node");
3278   case X86ISD::PSHUFD:
3279   case X86ISD::PSHUFHW:
3280   case X86ISD::PSHUFLW:
3281   case X86ISD::VPERMILP:
3282   case X86ISD::VPERMI:
3283     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3284   }
3285 }
3286
3287 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3288                                     SDValue V1, SDValue V2, unsigned TargetMask,
3289                                     SelectionDAG &DAG) {
3290   switch(Opc) {
3291   default: llvm_unreachable("Unknown x86 shuffle node");
3292   case X86ISD::PALIGNR:
3293   case X86ISD::SHUFP:
3294   case X86ISD::VPERM2X128:
3295     return DAG.getNode(Opc, dl, VT, V1, V2,
3296                        DAG.getConstant(TargetMask, MVT::i8));
3297   }
3298 }
3299
3300 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3301                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3302   switch(Opc) {
3303   default: llvm_unreachable("Unknown x86 shuffle node");
3304   case X86ISD::MOVLHPS:
3305   case X86ISD::MOVLHPD:
3306   case X86ISD::MOVHLPS:
3307   case X86ISD::MOVLPS:
3308   case X86ISD::MOVLPD:
3309   case X86ISD::MOVSS:
3310   case X86ISD::MOVSD:
3311   case X86ISD::UNPCKL:
3312   case X86ISD::UNPCKH:
3313     return DAG.getNode(Opc, dl, VT, V1, V2);
3314   }
3315 }
3316
3317 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3318   MachineFunction &MF = DAG.getMachineFunction();
3319   const X86RegisterInfo *RegInfo =
3320     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3321   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3322   int ReturnAddrIndex = FuncInfo->getRAIndex();
3323
3324   if (ReturnAddrIndex == 0) {
3325     // Set up a frame object for the return address.
3326     unsigned SlotSize = RegInfo->getSlotSize();
3327     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3328                                                            -(int64_t)SlotSize,
3329                                                            false);
3330     FuncInfo->setRAIndex(ReturnAddrIndex);
3331   }
3332
3333   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3334 }
3335
3336 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3337                                        bool hasSymbolicDisplacement) {
3338   // Offset should fit into 32 bit immediate field.
3339   if (!isInt<32>(Offset))
3340     return false;
3341
3342   // If we don't have a symbolic displacement - we don't have any extra
3343   // restrictions.
3344   if (!hasSymbolicDisplacement)
3345     return true;
3346
3347   // FIXME: Some tweaks might be needed for medium code model.
3348   if (M != CodeModel::Small && M != CodeModel::Kernel)
3349     return false;
3350
3351   // For small code model we assume that latest object is 16MB before end of 31
3352   // bits boundary. We may also accept pretty large negative constants knowing
3353   // that all objects are in the positive half of address space.
3354   if (M == CodeModel::Small && Offset < 16*1024*1024)
3355     return true;
3356
3357   // For kernel code model we know that all object resist in the negative half
3358   // of 32bits address space. We may not accept negative offsets, since they may
3359   // be just off and we may accept pretty large positive ones.
3360   if (M == CodeModel::Kernel && Offset > 0)
3361     return true;
3362
3363   return false;
3364 }
3365
3366 /// isCalleePop - Determines whether the callee is required to pop its
3367 /// own arguments. Callee pop is necessary to support tail calls.
3368 bool X86::isCalleePop(CallingConv::ID CallingConv,
3369                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3370   if (IsVarArg)
3371     return false;
3372
3373   switch (CallingConv) {
3374   default:
3375     return false;
3376   case CallingConv::X86_StdCall:
3377     return !is64Bit;
3378   case CallingConv::X86_FastCall:
3379     return !is64Bit;
3380   case CallingConv::X86_ThisCall:
3381     return !is64Bit;
3382   case CallingConv::Fast:
3383     return TailCallOpt;
3384   case CallingConv::GHC:
3385     return TailCallOpt;
3386   case CallingConv::HiPE:
3387     return TailCallOpt;
3388   }
3389 }
3390
3391 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3392 /// specific condition code, returning the condition code and the LHS/RHS of the
3393 /// comparison to make.
3394 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3395                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3396   if (!isFP) {
3397     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3398       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3399         // X > -1   -> X == 0, jump !sign.
3400         RHS = DAG.getConstant(0, RHS.getValueType());
3401         return X86::COND_NS;
3402       }
3403       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3404         // X < 0   -> X == 0, jump on sign.
3405         return X86::COND_S;
3406       }
3407       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3408         // X < 1   -> X <= 0
3409         RHS = DAG.getConstant(0, RHS.getValueType());
3410         return X86::COND_LE;
3411       }
3412     }
3413
3414     switch (SetCCOpcode) {
3415     default: llvm_unreachable("Invalid integer condition!");
3416     case ISD::SETEQ:  return X86::COND_E;
3417     case ISD::SETGT:  return X86::COND_G;
3418     case ISD::SETGE:  return X86::COND_GE;
3419     case ISD::SETLT:  return X86::COND_L;
3420     case ISD::SETLE:  return X86::COND_LE;
3421     case ISD::SETNE:  return X86::COND_NE;
3422     case ISD::SETULT: return X86::COND_B;
3423     case ISD::SETUGT: return X86::COND_A;
3424     case ISD::SETULE: return X86::COND_BE;
3425     case ISD::SETUGE: return X86::COND_AE;
3426     }
3427   }
3428
3429   // First determine if it is required or is profitable to flip the operands.
3430
3431   // If LHS is a foldable load, but RHS is not, flip the condition.
3432   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3433       !ISD::isNON_EXTLoad(RHS.getNode())) {
3434     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3435     std::swap(LHS, RHS);
3436   }
3437
3438   switch (SetCCOpcode) {
3439   default: break;
3440   case ISD::SETOLT:
3441   case ISD::SETOLE:
3442   case ISD::SETUGT:
3443   case ISD::SETUGE:
3444     std::swap(LHS, RHS);
3445     break;
3446   }
3447
3448   // On a floating point condition, the flags are set as follows:
3449   // ZF  PF  CF   op
3450   //  0 | 0 | 0 | X > Y
3451   //  0 | 0 | 1 | X < Y
3452   //  1 | 0 | 0 | X == Y
3453   //  1 | 1 | 1 | unordered
3454   switch (SetCCOpcode) {
3455   default: llvm_unreachable("Condcode should be pre-legalized away");
3456   case ISD::SETUEQ:
3457   case ISD::SETEQ:   return X86::COND_E;
3458   case ISD::SETOLT:              // flipped
3459   case ISD::SETOGT:
3460   case ISD::SETGT:   return X86::COND_A;
3461   case ISD::SETOLE:              // flipped
3462   case ISD::SETOGE:
3463   case ISD::SETGE:   return X86::COND_AE;
3464   case ISD::SETUGT:              // flipped
3465   case ISD::SETULT:
3466   case ISD::SETLT:   return X86::COND_B;
3467   case ISD::SETUGE:              // flipped
3468   case ISD::SETULE:
3469   case ISD::SETLE:   return X86::COND_BE;
3470   case ISD::SETONE:
3471   case ISD::SETNE:   return X86::COND_NE;
3472   case ISD::SETUO:   return X86::COND_P;
3473   case ISD::SETO:    return X86::COND_NP;
3474   case ISD::SETOEQ:
3475   case ISD::SETUNE:  return X86::COND_INVALID;
3476   }
3477 }
3478
3479 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3480 /// code. Current x86 isa includes the following FP cmov instructions:
3481 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3482 static bool hasFPCMov(unsigned X86CC) {
3483   switch (X86CC) {
3484   default:
3485     return false;
3486   case X86::COND_B:
3487   case X86::COND_BE:
3488   case X86::COND_E:
3489   case X86::COND_P:
3490   case X86::COND_A:
3491   case X86::COND_AE:
3492   case X86::COND_NE:
3493   case X86::COND_NP:
3494     return true;
3495   }
3496 }
3497
3498 /// isFPImmLegal - Returns true if the target can instruction select the
3499 /// specified FP immediate natively. If false, the legalizer will
3500 /// materialize the FP immediate as a load from a constant pool.
3501 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3502   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3503     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3504       return true;
3505   }
3506   return false;
3507 }
3508
3509 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3510 /// the specified range (L, H].
3511 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3512   return (Val < 0) || (Val >= Low && Val < Hi);
3513 }
3514
3515 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3516 /// specified value.
3517 static bool isUndefOrEqual(int Val, int CmpVal) {
3518   return (Val < 0 || Val == CmpVal);
3519 }
3520
3521 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3522 /// from position Pos and ending in Pos+Size, falls within the specified
3523 /// sequential range (L, L+Pos]. or is undef.
3524 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3525                                        unsigned Pos, unsigned Size, int Low) {
3526   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3527     if (!isUndefOrEqual(Mask[i], Low))
3528       return false;
3529   return true;
3530 }
3531
3532 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3533 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3534 /// the second operand.
3535 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3536   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3537     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3538   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3539     return (Mask[0] < 2 && Mask[1] < 2);
3540   return false;
3541 }
3542
3543 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3544 /// is suitable for input to PSHUFHW.
3545 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3546   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3547     return false;
3548
3549   // Lower quadword copied in order or undef.
3550   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3551     return false;
3552
3553   // Upper quadword shuffled.
3554   for (unsigned i = 4; i != 8; ++i)
3555     if (!isUndefOrInRange(Mask[i], 4, 8))
3556       return false;
3557
3558   if (VT == MVT::v16i16) {
3559     // Lower quadword copied in order or undef.
3560     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3561       return false;
3562
3563     // Upper quadword shuffled.
3564     for (unsigned i = 12; i != 16; ++i)
3565       if (!isUndefOrInRange(Mask[i], 12, 16))
3566         return false;
3567   }
3568
3569   return true;
3570 }
3571
3572 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3573 /// is suitable for input to PSHUFLW.
3574 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3575   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3576     return false;
3577
3578   // Upper quadword copied in order.
3579   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3580     return false;
3581
3582   // Lower quadword shuffled.
3583   for (unsigned i = 0; i != 4; ++i)
3584     if (!isUndefOrInRange(Mask[i], 0, 4))
3585       return false;
3586
3587   if (VT == MVT::v16i16) {
3588     // Upper quadword copied in order.
3589     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3590       return false;
3591
3592     // Lower quadword shuffled.
3593     for (unsigned i = 8; i != 12; ++i)
3594       if (!isUndefOrInRange(Mask[i], 8, 12))
3595         return false;
3596   }
3597
3598   return true;
3599 }
3600
3601 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3602 /// is suitable for input to PALIGNR.
3603 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3604                           const X86Subtarget *Subtarget) {
3605   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3606       (VT.is256BitVector() && !Subtarget->hasInt256()))
3607     return false;
3608
3609   unsigned NumElts = VT.getVectorNumElements();
3610   unsigned NumLanes = VT.getSizeInBits()/128;
3611   unsigned NumLaneElts = NumElts/NumLanes;
3612
3613   // Do not handle 64-bit element shuffles with palignr.
3614   if (NumLaneElts == 2)
3615     return false;
3616
3617   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3618     unsigned i;
3619     for (i = 0; i != NumLaneElts; ++i) {
3620       if (Mask[i+l] >= 0)
3621         break;
3622     }
3623
3624     // Lane is all undef, go to next lane
3625     if (i == NumLaneElts)
3626       continue;
3627
3628     int Start = Mask[i+l];
3629
3630     // Make sure its in this lane in one of the sources
3631     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3632         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3633       return false;
3634
3635     // If not lane 0, then we must match lane 0
3636     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3637       return false;
3638
3639     // Correct second source to be contiguous with first source
3640     if (Start >= (int)NumElts)
3641       Start -= NumElts - NumLaneElts;
3642
3643     // Make sure we're shifting in the right direction.
3644     if (Start <= (int)(i+l))
3645       return false;
3646
3647     Start -= i;
3648
3649     // Check the rest of the elements to see if they are consecutive.
3650     for (++i; i != NumLaneElts; ++i) {
3651       int Idx = Mask[i+l];
3652
3653       // Make sure its in this lane
3654       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3655           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3656         return false;
3657
3658       // If not lane 0, then we must match lane 0
3659       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3660         return false;
3661
3662       if (Idx >= (int)NumElts)
3663         Idx -= NumElts - NumLaneElts;
3664
3665       if (!isUndefOrEqual(Idx, Start+i))
3666         return false;
3667
3668     }
3669   }
3670
3671   return true;
3672 }
3673
3674 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3675 /// the two vector operands have swapped position.
3676 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3677                                      unsigned NumElems) {
3678   for (unsigned i = 0; i != NumElems; ++i) {
3679     int idx = Mask[i];
3680     if (idx < 0)
3681       continue;
3682     else if (idx < (int)NumElems)
3683       Mask[i] = idx + NumElems;
3684     else
3685       Mask[i] = idx - NumElems;
3686   }
3687 }
3688
3689 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3690 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3691 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3692 /// reverse of what x86 shuffles want.
3693 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3694                         bool Commuted = false) {
3695   if (!HasFp256 && VT.is256BitVector())
3696     return false;
3697
3698   unsigned NumElems = VT.getVectorNumElements();
3699   unsigned NumLanes = VT.getSizeInBits()/128;
3700   unsigned NumLaneElems = NumElems/NumLanes;
3701
3702   if (NumLaneElems != 2 && NumLaneElems != 4)
3703     return false;
3704
3705   // VSHUFPSY divides the resulting vector into 4 chunks.
3706   // The sources are also splitted into 4 chunks, and each destination
3707   // chunk must come from a different source chunk.
3708   //
3709   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3710   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3711   //
3712   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3713   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3714   //
3715   // VSHUFPDY divides the resulting vector into 4 chunks.
3716   // The sources are also splitted into 4 chunks, and each destination
3717   // chunk must come from a different source chunk.
3718   //
3719   //  SRC1 =>      X3       X2       X1       X0
3720   //  SRC2 =>      Y3       Y2       Y1       Y0
3721   //
3722   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3723   //
3724   unsigned HalfLaneElems = NumLaneElems/2;
3725   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3726     for (unsigned i = 0; i != NumLaneElems; ++i) {
3727       int Idx = Mask[i+l];
3728       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3729       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3730         return false;
3731       // For VSHUFPSY, the mask of the second half must be the same as the
3732       // first but with the appropriate offsets. This works in the same way as
3733       // VPERMILPS works with masks.
3734       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3735         continue;
3736       if (!isUndefOrEqual(Idx, Mask[i]+l))
3737         return false;
3738     }
3739   }
3740
3741   return true;
3742 }
3743
3744 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3745 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3746 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3747   if (!VT.is128BitVector())
3748     return false;
3749
3750   unsigned NumElems = VT.getVectorNumElements();
3751
3752   if (NumElems != 4)
3753     return false;
3754
3755   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3756   return isUndefOrEqual(Mask[0], 6) &&
3757          isUndefOrEqual(Mask[1], 7) &&
3758          isUndefOrEqual(Mask[2], 2) &&
3759          isUndefOrEqual(Mask[3], 3);
3760 }
3761
3762 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3763 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3764 /// <2, 3, 2, 3>
3765 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3766   if (!VT.is128BitVector())
3767     return false;
3768
3769   unsigned NumElems = VT.getVectorNumElements();
3770
3771   if (NumElems != 4)
3772     return false;
3773
3774   return isUndefOrEqual(Mask[0], 2) &&
3775          isUndefOrEqual(Mask[1], 3) &&
3776          isUndefOrEqual(Mask[2], 2) &&
3777          isUndefOrEqual(Mask[3], 3);
3778 }
3779
3780 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3782 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3783   if (!VT.is128BitVector())
3784     return false;
3785
3786   unsigned NumElems = VT.getVectorNumElements();
3787
3788   if (NumElems != 2 && NumElems != 4)
3789     return false;
3790
3791   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3792     if (!isUndefOrEqual(Mask[i], i + NumElems))
3793       return false;
3794
3795   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3796     if (!isUndefOrEqual(Mask[i], i))
3797       return false;
3798
3799   return true;
3800 }
3801
3802 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3803 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3804 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3805   if (!VT.is128BitVector())
3806     return false;
3807
3808   unsigned NumElems = VT.getVectorNumElements();
3809
3810   if (NumElems != 2 && NumElems != 4)
3811     return false;
3812
3813   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3814     if (!isUndefOrEqual(Mask[i], i))
3815       return false;
3816
3817   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3818     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3819       return false;
3820
3821   return true;
3822 }
3823
3824 //
3825 // Some special combinations that can be optimized.
3826 //
3827 static
3828 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3829                                SelectionDAG &DAG) {
3830   MVT VT = SVOp->getValueType(0).getSimpleVT();
3831   SDLoc dl(SVOp);
3832
3833   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3834     return SDValue();
3835
3836   ArrayRef<int> Mask = SVOp->getMask();
3837
3838   // These are the special masks that may be optimized.
3839   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3840   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3841   bool MatchEvenMask = true;
3842   bool MatchOddMask  = true;
3843   for (int i=0; i<8; ++i) {
3844     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3845       MatchEvenMask = false;
3846     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3847       MatchOddMask = false;
3848   }
3849
3850   if (!MatchEvenMask && !MatchOddMask)
3851     return SDValue();
3852
3853   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3854
3855   SDValue Op0 = SVOp->getOperand(0);
3856   SDValue Op1 = SVOp->getOperand(1);
3857
3858   if (MatchEvenMask) {
3859     // Shift the second operand right to 32 bits.
3860     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3861     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3862   } else {
3863     // Shift the first operand left to 32 bits.
3864     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3865     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3866   }
3867   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3868   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3869 }
3870
3871 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3873 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3874                          bool HasInt256, bool V2IsSplat = false) {
3875
3876   if (VT.is512BitVector())
3877     return false;
3878   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3879          "Unsupported vector type for unpckh");
3880
3881   unsigned NumElts = VT.getVectorNumElements();
3882   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3883       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3884     return false;
3885
3886   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3887   // independently on 128-bit lanes.
3888   unsigned NumLanes = VT.getSizeInBits()/128;
3889   unsigned NumLaneElts = NumElts/NumLanes;
3890
3891   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3892     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3893       int BitI  = Mask[l+i];
3894       int BitI1 = Mask[l+i+1];
3895       if (!isUndefOrEqual(BitI, j))
3896         return false;
3897       if (V2IsSplat) {
3898         if (!isUndefOrEqual(BitI1, NumElts))
3899           return false;
3900       } else {
3901         if (!isUndefOrEqual(BitI1, j + NumElts))
3902           return false;
3903       }
3904     }
3905   }
3906
3907   return true;
3908 }
3909
3910 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3912 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3913                          bool HasInt256, bool V2IsSplat = false) {
3914   unsigned NumElts = VT.getVectorNumElements();
3915
3916   if (VT.is512BitVector())
3917     return false;
3918   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3919          "Unsupported vector type for unpckh");
3920
3921   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3922       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3923     return false;
3924
3925   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3926   // independently on 128-bit lanes.
3927   unsigned NumLanes = VT.getSizeInBits()/128;
3928   unsigned NumLaneElts = NumElts/NumLanes;
3929
3930   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3931     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
3932       int BitI  = Mask[l+i];
3933       int BitI1 = Mask[l+i+1];
3934       if (!isUndefOrEqual(BitI, j))
3935         return false;
3936       if (V2IsSplat) {
3937         if (isUndefOrEqual(BitI1, NumElts))
3938           return false;
3939       } else {
3940         if (!isUndefOrEqual(BitI1, j+NumElts))
3941           return false;
3942       }
3943     }
3944   }
3945   return true;
3946 }
3947
3948 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3949 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3950 /// <0, 0, 1, 1>
3951 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3952   unsigned NumElts = VT.getVectorNumElements();
3953   bool Is256BitVec = VT.is256BitVector();
3954
3955   if (VT.is512BitVector())
3956     return false;
3957   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3958          "Unsupported vector type for unpckh");
3959
3960   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3961       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3962     return false;
3963
3964   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3965   // FIXME: Need a better way to get rid of this, there's no latency difference
3966   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3967   // the former later. We should also remove the "_undef" special mask.
3968   if (NumElts == 4 && Is256BitVec)
3969     return false;
3970
3971   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3972   // independently on 128-bit lanes.
3973   unsigned NumLanes = VT.getSizeInBits()/128;
3974   unsigned NumLaneElts = NumElts/NumLanes;
3975
3976   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3977     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3978       int BitI  = Mask[l+i];
3979       int BitI1 = Mask[l+i+1];
3980
3981       if (!isUndefOrEqual(BitI, j))
3982         return false;
3983       if (!isUndefOrEqual(BitI1, j))
3984         return false;
3985     }
3986   }
3987
3988   return true;
3989 }
3990
3991 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3992 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3993 /// <2, 2, 3, 3>
3994 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3995   unsigned NumElts = VT.getVectorNumElements();
3996
3997   if (VT.is512BitVector())
3998     return false;
3999
4000   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4001          "Unsupported vector type for unpckh");
4002
4003   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4004       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4005     return false;
4006
4007   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4008   // independently on 128-bit lanes.
4009   unsigned NumLanes = VT.getSizeInBits()/128;
4010   unsigned NumLaneElts = NumElts/NumLanes;
4011
4012   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4013     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4014       int BitI  = Mask[l+i];
4015       int BitI1 = Mask[l+i+1];
4016       if (!isUndefOrEqual(BitI, j))
4017         return false;
4018       if (!isUndefOrEqual(BitI1, j))
4019         return false;
4020     }
4021   }
4022   return true;
4023 }
4024
4025 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4026 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4027 /// MOVSD, and MOVD, i.e. setting the lowest element.
4028 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4029   if (VT.getVectorElementType().getSizeInBits() < 32)
4030     return false;
4031   if (!VT.is128BitVector())
4032     return false;
4033
4034   unsigned NumElts = VT.getVectorNumElements();
4035
4036   if (!isUndefOrEqual(Mask[0], NumElts))
4037     return false;
4038
4039   for (unsigned i = 1; i != NumElts; ++i)
4040     if (!isUndefOrEqual(Mask[i], i))
4041       return false;
4042
4043   return true;
4044 }
4045
4046 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4047 /// as permutations between 128-bit chunks or halves. As an example: this
4048 /// shuffle bellow:
4049 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4050 /// The first half comes from the second half of V1 and the second half from the
4051 /// the second half of V2.
4052 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4053   if (!HasFp256 || !VT.is256BitVector())
4054     return false;
4055
4056   // The shuffle result is divided into half A and half B. In total the two
4057   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4058   // B must come from C, D, E or F.
4059   unsigned HalfSize = VT.getVectorNumElements()/2;
4060   bool MatchA = false, MatchB = false;
4061
4062   // Check if A comes from one of C, D, E, F.
4063   for (unsigned Half = 0; Half != 4; ++Half) {
4064     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4065       MatchA = true;
4066       break;
4067     }
4068   }
4069
4070   // Check if B comes from one of C, D, E, F.
4071   for (unsigned Half = 0; Half != 4; ++Half) {
4072     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4073       MatchB = true;
4074       break;
4075     }
4076   }
4077
4078   return MatchA && MatchB;
4079 }
4080
4081 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4083 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4084   MVT VT = SVOp->getValueType(0).getSimpleVT();
4085
4086   unsigned HalfSize = VT.getVectorNumElements()/2;
4087
4088   unsigned FstHalf = 0, SndHalf = 0;
4089   for (unsigned i = 0; i < HalfSize; ++i) {
4090     if (SVOp->getMaskElt(i) > 0) {
4091       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4092       break;
4093     }
4094   }
4095   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4096     if (SVOp->getMaskElt(i) > 0) {
4097       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4098       break;
4099     }
4100   }
4101
4102   return (FstHalf | (SndHalf << 4));
4103 }
4104
4105 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4106 static bool isPermImmMask(ArrayRef<int> Mask, EVT VT, unsigned& Imm8) {
4107   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4108   if (EltSize < 32)
4109     return false;
4110
4111   unsigned NumElts = VT.getVectorNumElements();
4112   Imm8 = 0;
4113   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4114     for (unsigned i = 0; i != NumElts; ++i) {
4115       if (Mask[i] < 0)
4116         continue;
4117       Imm8 |= Mask[i] << (i*2);
4118     }
4119     return true;
4120   }
4121
4122   unsigned LaneSize = 4;
4123   SmallVector<int, 4> MaskVal(LaneSize, -1);
4124
4125   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4126     for (unsigned i = 0; i != LaneSize; ++i) {
4127       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4128         return false;
4129       if (Mask[i+l] < 0)
4130         continue;
4131       if (MaskVal[i] < 0) {
4132         MaskVal[i] = Mask[i+l] - l;
4133         Imm8 |= MaskVal[i] << (i*2);
4134         continue;
4135       }
4136       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4137         return false;
4138     }
4139   }
4140   return true;
4141 }
4142
4143 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4144 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4145 /// Note that VPERMIL mask matching is different depending whether theunderlying
4146 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4147 /// to the same elements of the low, but to the higher half of the source.
4148 /// In VPERMILPD the two lanes could be shuffled independently of each other
4149 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4150 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4151   if (!HasFp256)
4152     return false;
4153
4154   unsigned NumElts = VT.getVectorNumElements();
4155   // Only match 256-bit with 32/64-bit types
4156   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4157     return false;
4158
4159   unsigned NumLanes = VT.getSizeInBits()/128;
4160   unsigned LaneSize = NumElts/NumLanes;
4161   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4162     for (unsigned i = 0; i != LaneSize; ++i) {
4163       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4164         return false;
4165       if (NumElts != 8 || l == 0)
4166         continue;
4167       // VPERMILPS handling
4168       if (Mask[i] < 0)
4169         continue;
4170       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4171         return false;
4172     }
4173   }
4174
4175   return true;
4176 }
4177
4178 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4179 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4180 /// element of vector 2 and the other elements to come from vector 1 in order.
4181 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
4182                                bool V2IsSplat = false, bool V2IsUndef = false) {
4183   if (!VT.is128BitVector())
4184     return false;
4185
4186   unsigned NumOps = VT.getVectorNumElements();
4187   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4188     return false;
4189
4190   if (!isUndefOrEqual(Mask[0], 0))
4191     return false;
4192
4193   for (unsigned i = 1; i != NumOps; ++i)
4194     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4195           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4196           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4197       return false;
4198
4199   return true;
4200 }
4201
4202 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4203 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4204 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4205 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
4206                            const X86Subtarget *Subtarget) {
4207   if (!Subtarget->hasSSE3())
4208     return false;
4209
4210   unsigned NumElems = VT.getVectorNumElements();
4211
4212   if ((VT.is128BitVector() && NumElems != 4) ||
4213       (VT.is256BitVector() && NumElems != 8) ||
4214       (VT.is512BitVector() && NumElems != 16))
4215     return false;
4216
4217   // "i+1" is the value the indexed mask element must have
4218   for (unsigned i = 0; i != NumElems; i += 2)
4219     if (!isUndefOrEqual(Mask[i], i+1) ||
4220         !isUndefOrEqual(Mask[i+1], i+1))
4221       return false;
4222
4223   return true;
4224 }
4225
4226 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4227 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4228 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4229 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
4230                            const X86Subtarget *Subtarget) {
4231   if (!Subtarget->hasSSE3())
4232     return false;
4233
4234   unsigned NumElems = VT.getVectorNumElements();
4235
4236   if ((VT.is128BitVector() && NumElems != 4) ||
4237       (VT.is256BitVector() && NumElems != 8) ||
4238       (VT.is512BitVector() && NumElems != 16))
4239     return false;
4240
4241   // "i" is the value the indexed mask element must have
4242   for (unsigned i = 0; i != NumElems; i += 2)
4243     if (!isUndefOrEqual(Mask[i], i) ||
4244         !isUndefOrEqual(Mask[i+1], i))
4245       return false;
4246
4247   return true;
4248 }
4249
4250 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4251 /// specifies a shuffle of elements that is suitable for input to 256-bit
4252 /// version of MOVDDUP.
4253 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4254   if (!HasFp256 || !VT.is256BitVector())
4255     return false;
4256
4257   unsigned NumElts = VT.getVectorNumElements();
4258   if (NumElts != 4)
4259     return false;
4260
4261   for (unsigned i = 0; i != NumElts/2; ++i)
4262     if (!isUndefOrEqual(Mask[i], 0))
4263       return false;
4264   for (unsigned i = NumElts/2; i != NumElts; ++i)
4265     if (!isUndefOrEqual(Mask[i], NumElts/2))
4266       return false;
4267   return true;
4268 }
4269
4270 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4271 /// specifies a shuffle of elements that is suitable for input to 128-bit
4272 /// version of MOVDDUP.
4273 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4274   if (!VT.is128BitVector())
4275     return false;
4276
4277   unsigned e = VT.getVectorNumElements() / 2;
4278   for (unsigned i = 0; i != e; ++i)
4279     if (!isUndefOrEqual(Mask[i], i))
4280       return false;
4281   for (unsigned i = 0; i != e; ++i)
4282     if (!isUndefOrEqual(Mask[e+i], i))
4283       return false;
4284   return true;
4285 }
4286
4287 /// isVEXTRACTIndex - Return true if the specified
4288 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4289 /// suitable for instruction that extract 128 or 256 bit vectors
4290 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4291   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4292   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4293     return false;
4294
4295   // The index should be aligned on a vecWidth-bit boundary.
4296   uint64_t Index =
4297     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4298
4299   MVT VT = N->getValueType(0).getSimpleVT();
4300   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4301   bool Result = (Index * ElSize) % vecWidth == 0;
4302
4303   return Result;
4304 }
4305
4306 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4307 /// operand specifies a subvector insert that is suitable for input to
4308 /// insertion of 128 or 256-bit subvectors
4309 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4310   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4311   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4312     return false;
4313   // The index should be aligned on a vecWidth-bit boundary.
4314   uint64_t Index =
4315     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4316
4317   MVT VT = N->getValueType(0).getSimpleVT();
4318   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4319   bool Result = (Index * ElSize) % vecWidth == 0;
4320
4321   return Result;
4322 }
4323
4324 bool X86::isVINSERT128Index(SDNode *N) {
4325   return isVINSERTIndex(N, 128);
4326 }
4327
4328 bool X86::isVINSERT256Index(SDNode *N) {
4329   return isVINSERTIndex(N, 256);
4330 }
4331
4332 bool X86::isVEXTRACT128Index(SDNode *N) {
4333   return isVEXTRACTIndex(N, 128);
4334 }
4335
4336 bool X86::isVEXTRACT256Index(SDNode *N) {
4337   return isVEXTRACTIndex(N, 256);
4338 }
4339
4340 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4341 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4342 /// Handles 128-bit and 256-bit.
4343 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4344   MVT VT = N->getValueType(0).getSimpleVT();
4345
4346   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4347          "Unsupported vector type for PSHUF/SHUFP");
4348
4349   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4350   // independently on 128-bit lanes.
4351   unsigned NumElts = VT.getVectorNumElements();
4352   unsigned NumLanes = VT.getSizeInBits()/128;
4353   unsigned NumLaneElts = NumElts/NumLanes;
4354
4355   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4356          "Only supports 2 or 4 elements per lane");
4357
4358   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4359   unsigned Mask = 0;
4360   for (unsigned i = 0; i != NumElts; ++i) {
4361     int Elt = N->getMaskElt(i);
4362     if (Elt < 0) continue;
4363     Elt &= NumLaneElts - 1;
4364     unsigned ShAmt = (i << Shift) % 8;
4365     Mask |= Elt << ShAmt;
4366   }
4367
4368   return Mask;
4369 }
4370
4371 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4372 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4373 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4374   MVT VT = N->getValueType(0).getSimpleVT();
4375
4376   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4377          "Unsupported vector type for PSHUFHW");
4378
4379   unsigned NumElts = VT.getVectorNumElements();
4380
4381   unsigned Mask = 0;
4382   for (unsigned l = 0; l != NumElts; l += 8) {
4383     // 8 nodes per lane, but we only care about the last 4.
4384     for (unsigned i = 0; i < 4; ++i) {
4385       int Elt = N->getMaskElt(l+i+4);
4386       if (Elt < 0) continue;
4387       Elt &= 0x3; // only 2-bits.
4388       Mask |= Elt << (i * 2);
4389     }
4390   }
4391
4392   return Mask;
4393 }
4394
4395 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4396 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4397 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4398   MVT VT = N->getValueType(0).getSimpleVT();
4399
4400   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4401          "Unsupported vector type for PSHUFHW");
4402
4403   unsigned NumElts = VT.getVectorNumElements();
4404
4405   unsigned Mask = 0;
4406   for (unsigned l = 0; l != NumElts; l += 8) {
4407     // 8 nodes per lane, but we only care about the first 4.
4408     for (unsigned i = 0; i < 4; ++i) {
4409       int Elt = N->getMaskElt(l+i);
4410       if (Elt < 0) continue;
4411       Elt &= 0x3; // only 2-bits
4412       Mask |= Elt << (i * 2);
4413     }
4414   }
4415
4416   return Mask;
4417 }
4418
4419 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4420 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4421 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4422   MVT VT = SVOp->getValueType(0).getSimpleVT();
4423   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4424
4425   unsigned NumElts = VT.getVectorNumElements();
4426   unsigned NumLanes = VT.getSizeInBits()/128;
4427   unsigned NumLaneElts = NumElts/NumLanes;
4428
4429   int Val = 0;
4430   unsigned i;
4431   for (i = 0; i != NumElts; ++i) {
4432     Val = SVOp->getMaskElt(i);
4433     if (Val >= 0)
4434       break;
4435   }
4436   if (Val >= (int)NumElts)
4437     Val -= NumElts - NumLaneElts;
4438
4439   assert(Val - i > 0 && "PALIGNR imm should be positive");
4440   return (Val - i) * EltSize;
4441 }
4442
4443 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4444   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4445   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4446     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4447
4448   uint64_t Index =
4449     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4450
4451   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4452   MVT ElVT = VecVT.getVectorElementType();
4453
4454   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4455   return Index / NumElemsPerChunk;
4456 }
4457
4458 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4459   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4460   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4461     llvm_unreachable("Illegal insert subvector for VINSERT");
4462
4463   uint64_t Index =
4464     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4465
4466   MVT VecVT = N->getValueType(0).getSimpleVT();
4467   MVT ElVT = VecVT.getVectorElementType();
4468
4469   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4470   return Index / NumElemsPerChunk;
4471 }
4472
4473 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4474 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4475 /// and VINSERTI128 instructions.
4476 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4477   return getExtractVEXTRACTImmediate(N, 128);
4478 }
4479
4480 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4481 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4482 /// and VINSERTI64x4 instructions.
4483 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4484   return getExtractVEXTRACTImmediate(N, 256);
4485 }
4486
4487 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4488 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4489 /// and VINSERTI128 instructions.
4490 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4491   return getInsertVINSERTImmediate(N, 128);
4492 }
4493
4494 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4495 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4496 /// and VINSERTI64x4 instructions.
4497 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4498   return getInsertVINSERTImmediate(N, 256);
4499 }
4500
4501 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4502 /// constant +0.0.
4503 bool X86::isZeroNode(SDValue Elt) {
4504   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4505     return CN->isNullValue();
4506   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4507     return CFP->getValueAPF().isPosZero();
4508   return false;
4509 }
4510
4511 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4512 /// their permute mask.
4513 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4514                                     SelectionDAG &DAG) {
4515   MVT VT = SVOp->getValueType(0).getSimpleVT();
4516   unsigned NumElems = VT.getVectorNumElements();
4517   SmallVector<int, 8> MaskVec;
4518
4519   for (unsigned i = 0; i != NumElems; ++i) {
4520     int Idx = SVOp->getMaskElt(i);
4521     if (Idx >= 0) {
4522       if (Idx < (int)NumElems)
4523         Idx += NumElems;
4524       else
4525         Idx -= NumElems;
4526     }
4527     MaskVec.push_back(Idx);
4528   }
4529   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4530                               SVOp->getOperand(0), &MaskVec[0]);
4531 }
4532
4533 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4534 /// match movhlps. The lower half elements should come from upper half of
4535 /// V1 (and in order), and the upper half elements should come from the upper
4536 /// half of V2 (and in order).
4537 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4538   if (!VT.is128BitVector())
4539     return false;
4540   if (VT.getVectorNumElements() != 4)
4541     return false;
4542   for (unsigned i = 0, e = 2; i != e; ++i)
4543     if (!isUndefOrEqual(Mask[i], i+2))
4544       return false;
4545   for (unsigned i = 2; i != 4; ++i)
4546     if (!isUndefOrEqual(Mask[i], i+4))
4547       return false;
4548   return true;
4549 }
4550
4551 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4552 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4553 /// required.
4554 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4555   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4556     return false;
4557   N = N->getOperand(0).getNode();
4558   if (!ISD::isNON_EXTLoad(N))
4559     return false;
4560   if (LD)
4561     *LD = cast<LoadSDNode>(N);
4562   return true;
4563 }
4564
4565 // Test whether the given value is a vector value which will be legalized
4566 // into a load.
4567 static bool WillBeConstantPoolLoad(SDNode *N) {
4568   if (N->getOpcode() != ISD::BUILD_VECTOR)
4569     return false;
4570
4571   // Check for any non-constant elements.
4572   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4573     switch (N->getOperand(i).getNode()->getOpcode()) {
4574     case ISD::UNDEF:
4575     case ISD::ConstantFP:
4576     case ISD::Constant:
4577       break;
4578     default:
4579       return false;
4580     }
4581
4582   // Vectors of all-zeros and all-ones are materialized with special
4583   // instructions rather than being loaded.
4584   return !ISD::isBuildVectorAllZeros(N) &&
4585          !ISD::isBuildVectorAllOnes(N);
4586 }
4587
4588 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4589 /// match movlp{s|d}. The lower half elements should come from lower half of
4590 /// V1 (and in order), and the upper half elements should come from the upper
4591 /// half of V2 (and in order). And since V1 will become the source of the
4592 /// MOVLP, it must be either a vector load or a scalar load to vector.
4593 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4594                                ArrayRef<int> Mask, EVT VT) {
4595   if (!VT.is128BitVector())
4596     return false;
4597
4598   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4599     return false;
4600   // Is V2 is a vector load, don't do this transformation. We will try to use
4601   // load folding shufps op.
4602   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4603     return false;
4604
4605   unsigned NumElems = VT.getVectorNumElements();
4606
4607   if (NumElems != 2 && NumElems != 4)
4608     return false;
4609   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4610     if (!isUndefOrEqual(Mask[i], i))
4611       return false;
4612   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4613     if (!isUndefOrEqual(Mask[i], i+NumElems))
4614       return false;
4615   return true;
4616 }
4617
4618 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4619 /// all the same.
4620 static bool isSplatVector(SDNode *N) {
4621   if (N->getOpcode() != ISD::BUILD_VECTOR)
4622     return false;
4623
4624   SDValue SplatValue = N->getOperand(0);
4625   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4626     if (N->getOperand(i) != SplatValue)
4627       return false;
4628   return true;
4629 }
4630
4631 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4632 /// to an zero vector.
4633 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4634 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4635   SDValue V1 = N->getOperand(0);
4636   SDValue V2 = N->getOperand(1);
4637   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4638   for (unsigned i = 0; i != NumElems; ++i) {
4639     int Idx = N->getMaskElt(i);
4640     if (Idx >= (int)NumElems) {
4641       unsigned Opc = V2.getOpcode();
4642       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4643         continue;
4644       if (Opc != ISD::BUILD_VECTOR ||
4645           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4646         return false;
4647     } else if (Idx >= 0) {
4648       unsigned Opc = V1.getOpcode();
4649       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4650         continue;
4651       if (Opc != ISD::BUILD_VECTOR ||
4652           !X86::isZeroNode(V1.getOperand(Idx)))
4653         return false;
4654     }
4655   }
4656   return true;
4657 }
4658
4659 /// getZeroVector - Returns a vector of specified type with all zero elements.
4660 ///
4661 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4662                              SelectionDAG &DAG, SDLoc dl) {
4663   assert(VT.isVector() && "Expected a vector type");
4664
4665   // Always build SSE zero vectors as <4 x i32> bitcasted
4666   // to their dest type. This ensures they get CSE'd.
4667   SDValue Vec;
4668   if (VT.is128BitVector()) {  // SSE
4669     if (Subtarget->hasSSE2()) {  // SSE2
4670       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4671       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4672     } else { // SSE1
4673       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4674       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4675     }
4676   } else if (VT.is256BitVector()) { // AVX
4677     if (Subtarget->hasInt256()) { // AVX2
4678       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4679       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4680       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4681                         array_lengthof(Ops));
4682     } else {
4683       // 256-bit logic and arithmetic instructions in AVX are all
4684       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4685       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4686       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4687       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4688                         array_lengthof(Ops));
4689     }
4690   } else
4691     llvm_unreachable("Unexpected vector type");
4692
4693   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4694 }
4695
4696 /// getOnesVector - Returns a vector of specified type with all bits set.
4697 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4698 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4699 /// Then bitcast to their original type, ensuring they get CSE'd.
4700 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4701                              SDLoc dl) {
4702   assert(VT.isVector() && "Expected a vector type");
4703
4704   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4705   SDValue Vec;
4706   if (VT.is256BitVector()) {
4707     if (HasInt256) { // AVX2
4708       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4709       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4710                         array_lengthof(Ops));
4711     } else { // AVX
4712       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4713       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4714     }
4715   } else if (VT.is128BitVector()) {
4716     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4717   } else
4718     llvm_unreachable("Unexpected vector type");
4719
4720   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4721 }
4722
4723 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4724 /// that point to V2 points to its first element.
4725 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4726   for (unsigned i = 0; i != NumElems; ++i) {
4727     if (Mask[i] > (int)NumElems) {
4728       Mask[i] = NumElems;
4729     }
4730   }
4731 }
4732
4733 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4734 /// operation of specified width.
4735 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4736                        SDValue V2) {
4737   unsigned NumElems = VT.getVectorNumElements();
4738   SmallVector<int, 8> Mask;
4739   Mask.push_back(NumElems);
4740   for (unsigned i = 1; i != NumElems; ++i)
4741     Mask.push_back(i);
4742   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4743 }
4744
4745 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4746 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4747                           SDValue V2) {
4748   unsigned NumElems = VT.getVectorNumElements();
4749   SmallVector<int, 8> Mask;
4750   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4751     Mask.push_back(i);
4752     Mask.push_back(i + NumElems);
4753   }
4754   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4755 }
4756
4757 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4758 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4759                           SDValue V2) {
4760   unsigned NumElems = VT.getVectorNumElements();
4761   SmallVector<int, 8> Mask;
4762   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4763     Mask.push_back(i + Half);
4764     Mask.push_back(i + NumElems + Half);
4765   }
4766   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4767 }
4768
4769 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4770 // a generic shuffle instruction because the target has no such instructions.
4771 // Generate shuffles which repeat i16 and i8 several times until they can be
4772 // represented by v4f32 and then be manipulated by target suported shuffles.
4773 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4774   EVT VT = V.getValueType();
4775   int NumElems = VT.getVectorNumElements();
4776   SDLoc dl(V);
4777
4778   while (NumElems > 4) {
4779     if (EltNo < NumElems/2) {
4780       V = getUnpackl(DAG, dl, VT, V, V);
4781     } else {
4782       V = getUnpackh(DAG, dl, VT, V, V);
4783       EltNo -= NumElems/2;
4784     }
4785     NumElems >>= 1;
4786   }
4787   return V;
4788 }
4789
4790 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4791 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4792   EVT VT = V.getValueType();
4793   SDLoc dl(V);
4794
4795   if (VT.is128BitVector()) {
4796     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4797     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4798     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4799                              &SplatMask[0]);
4800   } else if (VT.is256BitVector()) {
4801     // To use VPERMILPS to splat scalars, the second half of indicies must
4802     // refer to the higher part, which is a duplication of the lower one,
4803     // because VPERMILPS can only handle in-lane permutations.
4804     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4805                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4806
4807     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4808     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4809                              &SplatMask[0]);
4810   } else
4811     llvm_unreachable("Vector size not supported");
4812
4813   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4814 }
4815
4816 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4817 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4818   EVT SrcVT = SV->getValueType(0);
4819   SDValue V1 = SV->getOperand(0);
4820   SDLoc dl(SV);
4821
4822   int EltNo = SV->getSplatIndex();
4823   int NumElems = SrcVT.getVectorNumElements();
4824   bool Is256BitVec = SrcVT.is256BitVector();
4825
4826   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4827          "Unknown how to promote splat for type");
4828
4829   // Extract the 128-bit part containing the splat element and update
4830   // the splat element index when it refers to the higher register.
4831   if (Is256BitVec) {
4832     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4833     if (EltNo >= NumElems/2)
4834       EltNo -= NumElems/2;
4835   }
4836
4837   // All i16 and i8 vector types can't be used directly by a generic shuffle
4838   // instruction because the target has no such instruction. Generate shuffles
4839   // which repeat i16 and i8 several times until they fit in i32, and then can
4840   // be manipulated by target suported shuffles.
4841   EVT EltVT = SrcVT.getVectorElementType();
4842   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4843     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4844
4845   // Recreate the 256-bit vector and place the same 128-bit vector
4846   // into the low and high part. This is necessary because we want
4847   // to use VPERM* to shuffle the vectors
4848   if (Is256BitVec) {
4849     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4850   }
4851
4852   return getLegalSplat(DAG, V1, EltNo);
4853 }
4854
4855 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4856 /// vector of zero or undef vector.  This produces a shuffle where the low
4857 /// element of V2 is swizzled into the zero/undef vector, landing at element
4858 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4859 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4860                                            bool IsZero,
4861                                            const X86Subtarget *Subtarget,
4862                                            SelectionDAG &DAG) {
4863   EVT VT = V2.getValueType();
4864   SDValue V1 = IsZero
4865     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4866   unsigned NumElems = VT.getVectorNumElements();
4867   SmallVector<int, 16> MaskVec;
4868   for (unsigned i = 0; i != NumElems; ++i)
4869     // If this is the insertion idx, put the low elt of V2 here.
4870     MaskVec.push_back(i == Idx ? NumElems : i);
4871   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4872 }
4873
4874 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4875 /// target specific opcode. Returns true if the Mask could be calculated.
4876 /// Sets IsUnary to true if only uses one source.
4877 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4878                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4879   unsigned NumElems = VT.getVectorNumElements();
4880   SDValue ImmN;
4881
4882   IsUnary = false;
4883   switch(N->getOpcode()) {
4884   case X86ISD::SHUFP:
4885     ImmN = N->getOperand(N->getNumOperands()-1);
4886     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4887     break;
4888   case X86ISD::UNPCKH:
4889     DecodeUNPCKHMask(VT, Mask);
4890     break;
4891   case X86ISD::UNPCKL:
4892     DecodeUNPCKLMask(VT, Mask);
4893     break;
4894   case X86ISD::MOVHLPS:
4895     DecodeMOVHLPSMask(NumElems, Mask);
4896     break;
4897   case X86ISD::MOVLHPS:
4898     DecodeMOVLHPSMask(NumElems, Mask);
4899     break;
4900   case X86ISD::PALIGNR:
4901     ImmN = N->getOperand(N->getNumOperands()-1);
4902     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4903     break;
4904   case X86ISD::PSHUFD:
4905   case X86ISD::VPERMILP:
4906     ImmN = N->getOperand(N->getNumOperands()-1);
4907     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4908     IsUnary = true;
4909     break;
4910   case X86ISD::PSHUFHW:
4911     ImmN = N->getOperand(N->getNumOperands()-1);
4912     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4913     IsUnary = true;
4914     break;
4915   case X86ISD::PSHUFLW:
4916     ImmN = N->getOperand(N->getNumOperands()-1);
4917     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4918     IsUnary = true;
4919     break;
4920   case X86ISD::VPERMI:
4921     ImmN = N->getOperand(N->getNumOperands()-1);
4922     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4923     IsUnary = true;
4924     break;
4925   case X86ISD::MOVSS:
4926   case X86ISD::MOVSD: {
4927     // The index 0 always comes from the first element of the second source,
4928     // this is why MOVSS and MOVSD are used in the first place. The other
4929     // elements come from the other positions of the first source vector
4930     Mask.push_back(NumElems);
4931     for (unsigned i = 1; i != NumElems; ++i) {
4932       Mask.push_back(i);
4933     }
4934     break;
4935   }
4936   case X86ISD::VPERM2X128:
4937     ImmN = N->getOperand(N->getNumOperands()-1);
4938     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4939     if (Mask.empty()) return false;
4940     break;
4941   case X86ISD::MOVDDUP:
4942   case X86ISD::MOVLHPD:
4943   case X86ISD::MOVLPD:
4944   case X86ISD::MOVLPS:
4945   case X86ISD::MOVSHDUP:
4946   case X86ISD::MOVSLDUP:
4947     // Not yet implemented
4948     return false;
4949   default: llvm_unreachable("unknown target shuffle node");
4950   }
4951
4952   return true;
4953 }
4954
4955 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4956 /// element of the result of the vector shuffle.
4957 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4958                                    unsigned Depth) {
4959   if (Depth == 6)
4960     return SDValue();  // Limit search depth.
4961
4962   SDValue V = SDValue(N, 0);
4963   EVT VT = V.getValueType();
4964   unsigned Opcode = V.getOpcode();
4965
4966   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4967   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4968     int Elt = SV->getMaskElt(Index);
4969
4970     if (Elt < 0)
4971       return DAG.getUNDEF(VT.getVectorElementType());
4972
4973     unsigned NumElems = VT.getVectorNumElements();
4974     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4975                                          : SV->getOperand(1);
4976     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4977   }
4978
4979   // Recurse into target specific vector shuffles to find scalars.
4980   if (isTargetShuffle(Opcode)) {
4981     MVT ShufVT = V.getValueType().getSimpleVT();
4982     unsigned NumElems = ShufVT.getVectorNumElements();
4983     SmallVector<int, 16> ShuffleMask;
4984     bool IsUnary;
4985
4986     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4987       return SDValue();
4988
4989     int Elt = ShuffleMask[Index];
4990     if (Elt < 0)
4991       return DAG.getUNDEF(ShufVT.getVectorElementType());
4992
4993     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4994                                          : N->getOperand(1);
4995     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4996                                Depth+1);
4997   }
4998
4999   // Actual nodes that may contain scalar elements
5000   if (Opcode == ISD::BITCAST) {
5001     V = V.getOperand(0);
5002     EVT SrcVT = V.getValueType();
5003     unsigned NumElems = VT.getVectorNumElements();
5004
5005     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5006       return SDValue();
5007   }
5008
5009   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5010     return (Index == 0) ? V.getOperand(0)
5011                         : DAG.getUNDEF(VT.getVectorElementType());
5012
5013   if (V.getOpcode() == ISD::BUILD_VECTOR)
5014     return V.getOperand(Index);
5015
5016   return SDValue();
5017 }
5018
5019 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5020 /// shuffle operation which come from a consecutively from a zero. The
5021 /// search can start in two different directions, from left or right.
5022 /// We count undefs as zeros until PreferredNum is reached.
5023 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5024                                          unsigned NumElems, bool ZerosFromLeft,
5025                                          SelectionDAG &DAG,
5026                                          unsigned PreferredNum = -1U) {
5027   unsigned NumZeros = 0;
5028   for (unsigned i = 0; i != NumElems; ++i) {
5029     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5030     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5031     if (!Elt.getNode())
5032       break;
5033
5034     if (X86::isZeroNode(Elt))
5035       ++NumZeros;
5036     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5037       NumZeros = std::min(NumZeros + 1, PreferredNum);
5038     else
5039       break;
5040   }
5041
5042   return NumZeros;
5043 }
5044
5045 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5046 /// correspond consecutively to elements from one of the vector operands,
5047 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5048 static
5049 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5050                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5051                               unsigned NumElems, unsigned &OpNum) {
5052   bool SeenV1 = false;
5053   bool SeenV2 = false;
5054
5055   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5056     int Idx = SVOp->getMaskElt(i);
5057     // Ignore undef indicies
5058     if (Idx < 0)
5059       continue;
5060
5061     if (Idx < (int)NumElems)
5062       SeenV1 = true;
5063     else
5064       SeenV2 = true;
5065
5066     // Only accept consecutive elements from the same vector
5067     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5068       return false;
5069   }
5070
5071   OpNum = SeenV1 ? 0 : 1;
5072   return true;
5073 }
5074
5075 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5076 /// logical left shift of a vector.
5077 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5078                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5079   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5080   unsigned NumZeros = getNumOfConsecutiveZeros(
5081       SVOp, NumElems, false /* check zeros from right */, DAG,
5082       SVOp->getMaskElt(0));
5083   unsigned OpSrc;
5084
5085   if (!NumZeros)
5086     return false;
5087
5088   // Considering the elements in the mask that are not consecutive zeros,
5089   // check if they consecutively come from only one of the source vectors.
5090   //
5091   //               V1 = {X, A, B, C}     0
5092   //                         \  \  \    /
5093   //   vector_shuffle V1, V2 <1, 2, 3, X>
5094   //
5095   if (!isShuffleMaskConsecutive(SVOp,
5096             0,                   // Mask Start Index
5097             NumElems-NumZeros,   // Mask End Index(exclusive)
5098             NumZeros,            // Where to start looking in the src vector
5099             NumElems,            // Number of elements in vector
5100             OpSrc))              // Which source operand ?
5101     return false;
5102
5103   isLeft = false;
5104   ShAmt = NumZeros;
5105   ShVal = SVOp->getOperand(OpSrc);
5106   return true;
5107 }
5108
5109 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5110 /// logical left shift of a vector.
5111 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5112                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5113   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5114   unsigned NumZeros = getNumOfConsecutiveZeros(
5115       SVOp, NumElems, true /* check zeros from left */, DAG,
5116       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5117   unsigned OpSrc;
5118
5119   if (!NumZeros)
5120     return false;
5121
5122   // Considering the elements in the mask that are not consecutive zeros,
5123   // check if they consecutively come from only one of the source vectors.
5124   //
5125   //                           0    { A, B, X, X } = V2
5126   //                          / \    /  /
5127   //   vector_shuffle V1, V2 <X, X, 4, 5>
5128   //
5129   if (!isShuffleMaskConsecutive(SVOp,
5130             NumZeros,     // Mask Start Index
5131             NumElems,     // Mask End Index(exclusive)
5132             0,            // Where to start looking in the src vector
5133             NumElems,     // Number of elements in vector
5134             OpSrc))       // Which source operand ?
5135     return false;
5136
5137   isLeft = true;
5138   ShAmt = NumZeros;
5139   ShVal = SVOp->getOperand(OpSrc);
5140   return true;
5141 }
5142
5143 /// isVectorShift - Returns true if the shuffle can be implemented as a
5144 /// logical left or right shift of a vector.
5145 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5146                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5147   // Although the logic below support any bitwidth size, there are no
5148   // shift instructions which handle more than 128-bit vectors.
5149   if (!SVOp->getValueType(0).is128BitVector())
5150     return false;
5151
5152   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5153       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5154     return true;
5155
5156   return false;
5157 }
5158
5159 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5160 ///
5161 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5162                                        unsigned NumNonZero, unsigned NumZero,
5163                                        SelectionDAG &DAG,
5164                                        const X86Subtarget* Subtarget,
5165                                        const TargetLowering &TLI) {
5166   if (NumNonZero > 8)
5167     return SDValue();
5168
5169   SDLoc dl(Op);
5170   SDValue V(0, 0);
5171   bool First = true;
5172   for (unsigned i = 0; i < 16; ++i) {
5173     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5174     if (ThisIsNonZero && First) {
5175       if (NumZero)
5176         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5177       else
5178         V = DAG.getUNDEF(MVT::v8i16);
5179       First = false;
5180     }
5181
5182     if ((i & 1) != 0) {
5183       SDValue ThisElt(0, 0), LastElt(0, 0);
5184       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5185       if (LastIsNonZero) {
5186         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5187                               MVT::i16, Op.getOperand(i-1));
5188       }
5189       if (ThisIsNonZero) {
5190         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5191         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5192                               ThisElt, DAG.getConstant(8, MVT::i8));
5193         if (LastIsNonZero)
5194           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5195       } else
5196         ThisElt = LastElt;
5197
5198       if (ThisElt.getNode())
5199         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5200                         DAG.getIntPtrConstant(i/2));
5201     }
5202   }
5203
5204   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5205 }
5206
5207 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5208 ///
5209 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5210                                      unsigned NumNonZero, unsigned NumZero,
5211                                      SelectionDAG &DAG,
5212                                      const X86Subtarget* Subtarget,
5213                                      const TargetLowering &TLI) {
5214   if (NumNonZero > 4)
5215     return SDValue();
5216
5217   SDLoc dl(Op);
5218   SDValue V(0, 0);
5219   bool First = true;
5220   for (unsigned i = 0; i < 8; ++i) {
5221     bool isNonZero = (NonZeros & (1 << i)) != 0;
5222     if (isNonZero) {
5223       if (First) {
5224         if (NumZero)
5225           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5226         else
5227           V = DAG.getUNDEF(MVT::v8i16);
5228         First = false;
5229       }
5230       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5231                       MVT::v8i16, V, Op.getOperand(i),
5232                       DAG.getIntPtrConstant(i));
5233     }
5234   }
5235
5236   return V;
5237 }
5238
5239 /// getVShift - Return a vector logical shift node.
5240 ///
5241 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5242                          unsigned NumBits, SelectionDAG &DAG,
5243                          const TargetLowering &TLI, SDLoc dl) {
5244   assert(VT.is128BitVector() && "Unknown type for VShift");
5245   EVT ShVT = MVT::v2i64;
5246   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5247   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5248   return DAG.getNode(ISD::BITCAST, dl, VT,
5249                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5250                              DAG.getConstant(NumBits,
5251                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5252 }
5253
5254 SDValue
5255 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5256                                           SelectionDAG &DAG) const {
5257
5258   // Check if the scalar load can be widened into a vector load. And if
5259   // the address is "base + cst" see if the cst can be "absorbed" into
5260   // the shuffle mask.
5261   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5262     SDValue Ptr = LD->getBasePtr();
5263     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5264       return SDValue();
5265     EVT PVT = LD->getValueType(0);
5266     if (PVT != MVT::i32 && PVT != MVT::f32)
5267       return SDValue();
5268
5269     int FI = -1;
5270     int64_t Offset = 0;
5271     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5272       FI = FINode->getIndex();
5273       Offset = 0;
5274     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5275                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5276       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5277       Offset = Ptr.getConstantOperandVal(1);
5278       Ptr = Ptr.getOperand(0);
5279     } else {
5280       return SDValue();
5281     }
5282
5283     // FIXME: 256-bit vector instructions don't require a strict alignment,
5284     // improve this code to support it better.
5285     unsigned RequiredAlign = VT.getSizeInBits()/8;
5286     SDValue Chain = LD->getChain();
5287     // Make sure the stack object alignment is at least 16 or 32.
5288     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5289     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5290       if (MFI->isFixedObjectIndex(FI)) {
5291         // Can't change the alignment. FIXME: It's possible to compute
5292         // the exact stack offset and reference FI + adjust offset instead.
5293         // If someone *really* cares about this. That's the way to implement it.
5294         return SDValue();
5295       } else {
5296         MFI->setObjectAlignment(FI, RequiredAlign);
5297       }
5298     }
5299
5300     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5301     // Ptr + (Offset & ~15).
5302     if (Offset < 0)
5303       return SDValue();
5304     if ((Offset % RequiredAlign) & 3)
5305       return SDValue();
5306     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5307     if (StartOffset)
5308       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5309                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5310
5311     int EltNo = (Offset - StartOffset) >> 2;
5312     unsigned NumElems = VT.getVectorNumElements();
5313
5314     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5315     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5316                              LD->getPointerInfo().getWithOffset(StartOffset),
5317                              false, false, false, 0);
5318
5319     SmallVector<int, 8> Mask;
5320     for (unsigned i = 0; i != NumElems; ++i)
5321       Mask.push_back(EltNo);
5322
5323     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5324   }
5325
5326   return SDValue();
5327 }
5328
5329 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5330 /// vector of type 'VT', see if the elements can be replaced by a single large
5331 /// load which has the same value as a build_vector whose operands are 'elts'.
5332 ///
5333 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5334 ///
5335 /// FIXME: we'd also like to handle the case where the last elements are zero
5336 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5337 /// There's even a handy isZeroNode for that purpose.
5338 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5339                                         SDLoc &DL, SelectionDAG &DAG) {
5340   EVT EltVT = VT.getVectorElementType();
5341   unsigned NumElems = Elts.size();
5342
5343   LoadSDNode *LDBase = NULL;
5344   unsigned LastLoadedElt = -1U;
5345
5346   // For each element in the initializer, see if we've found a load or an undef.
5347   // If we don't find an initial load element, or later load elements are
5348   // non-consecutive, bail out.
5349   for (unsigned i = 0; i < NumElems; ++i) {
5350     SDValue Elt = Elts[i];
5351
5352     if (!Elt.getNode() ||
5353         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5354       return SDValue();
5355     if (!LDBase) {
5356       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5357         return SDValue();
5358       LDBase = cast<LoadSDNode>(Elt.getNode());
5359       LastLoadedElt = i;
5360       continue;
5361     }
5362     if (Elt.getOpcode() == ISD::UNDEF)
5363       continue;
5364
5365     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5366     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5367       return SDValue();
5368     LastLoadedElt = i;
5369   }
5370
5371   // If we have found an entire vector of loads and undefs, then return a large
5372   // load of the entire vector width starting at the base pointer.  If we found
5373   // consecutive loads for the low half, generate a vzext_load node.
5374   if (LastLoadedElt == NumElems - 1) {
5375     SDValue NewLd = SDValue();
5376     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5377       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5378                           LDBase->getPointerInfo(),
5379                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5380                           LDBase->isInvariant(), 0);
5381     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5382                         LDBase->getPointerInfo(),
5383                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5384                         LDBase->isInvariant(), LDBase->getAlignment());
5385
5386     if (LDBase->hasAnyUseOfValue(1)) {
5387       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5388                                      SDValue(LDBase, 1),
5389                                      SDValue(NewLd.getNode(), 1));
5390       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5391       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5392                              SDValue(NewLd.getNode(), 1));
5393     }
5394
5395     return NewLd;
5396   }
5397   if (NumElems == 4 && LastLoadedElt == 1 &&
5398       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5399     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5400     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5401     SDValue ResNode =
5402         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5403                                 array_lengthof(Ops), MVT::i64,
5404                                 LDBase->getPointerInfo(),
5405                                 LDBase->getAlignment(),
5406                                 false/*isVolatile*/, true/*ReadMem*/,
5407                                 false/*WriteMem*/);
5408
5409     // Make sure the newly-created LOAD is in the same position as LDBase in
5410     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5411     // update uses of LDBase's output chain to use the TokenFactor.
5412     if (LDBase->hasAnyUseOfValue(1)) {
5413       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5414                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5415       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5416       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5417                              SDValue(ResNode.getNode(), 1));
5418     }
5419
5420     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5421   }
5422   return SDValue();
5423 }
5424
5425 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5426 /// to generate a splat value for the following cases:
5427 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5428 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5429 /// a scalar load, or a constant.
5430 /// The VBROADCAST node is returned when a pattern is found,
5431 /// or SDValue() otherwise.
5432 SDValue
5433 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5434   if (!Subtarget->hasFp256())
5435     return SDValue();
5436
5437   MVT VT = Op.getValueType().getSimpleVT();
5438   SDLoc dl(Op);
5439
5440   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5441          "Unsupported vector type for broadcast.");
5442
5443   SDValue Ld;
5444   bool ConstSplatVal;
5445
5446   switch (Op.getOpcode()) {
5447     default:
5448       // Unknown pattern found.
5449       return SDValue();
5450
5451     case ISD::BUILD_VECTOR: {
5452       // The BUILD_VECTOR node must be a splat.
5453       if (!isSplatVector(Op.getNode()))
5454         return SDValue();
5455
5456       Ld = Op.getOperand(0);
5457       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5458                      Ld.getOpcode() == ISD::ConstantFP);
5459
5460       // The suspected load node has several users. Make sure that all
5461       // of its users are from the BUILD_VECTOR node.
5462       // Constants may have multiple users.
5463       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5464         return SDValue();
5465       break;
5466     }
5467
5468     case ISD::VECTOR_SHUFFLE: {
5469       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5470
5471       // Shuffles must have a splat mask where the first element is
5472       // broadcasted.
5473       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5474         return SDValue();
5475
5476       SDValue Sc = Op.getOperand(0);
5477       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5478           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5479
5480         if (!Subtarget->hasInt256())
5481           return SDValue();
5482
5483         // Use the register form of the broadcast instruction available on AVX2.
5484         if (VT.is256BitVector())
5485           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5486         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5487       }
5488
5489       Ld = Sc.getOperand(0);
5490       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5491                        Ld.getOpcode() == ISD::ConstantFP);
5492
5493       // The scalar_to_vector node and the suspected
5494       // load node must have exactly one user.
5495       // Constants may have multiple users.
5496
5497       // AVX-512 has register version of the broadcast
5498       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5499         Ld.getValueType().getSizeInBits() >= 32;
5500       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5501           !hasRegVer))
5502         return SDValue();
5503       break;
5504     }
5505   }
5506
5507   bool IsGE256 = (VT.getSizeInBits() >= 256);
5508
5509   // Handle the broadcasting a single constant scalar from the constant pool
5510   // into a vector. On Sandybridge it is still better to load a constant vector
5511   // from the constant pool and not to broadcast it from a scalar.
5512   if (ConstSplatVal && Subtarget->hasInt256()) {
5513     EVT CVT = Ld.getValueType();
5514     assert(!CVT.isVector() && "Must not broadcast a vector type");
5515     unsigned ScalarSize = CVT.getSizeInBits();
5516
5517     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5518       const Constant *C = 0;
5519       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5520         C = CI->getConstantIntValue();
5521       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5522         C = CF->getConstantFPValue();
5523
5524       assert(C && "Invalid constant type");
5525
5526       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5527       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5528       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5529                        MachinePointerInfo::getConstantPool(),
5530                        false, false, false, Alignment);
5531
5532       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5533     }
5534   }
5535
5536   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5537   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5538
5539   // Handle AVX2 in-register broadcasts.
5540   if (!IsLoad && Subtarget->hasInt256() &&
5541       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5542     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5543
5544   // The scalar source must be a normal load.
5545   if (!IsLoad)
5546     return SDValue();
5547
5548   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5549     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5550
5551   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5552   // double since there is no vbroadcastsd xmm
5553   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5554     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5555       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5556   }
5557
5558   // Unsupported broadcast.
5559   return SDValue();
5560 }
5561
5562 SDValue
5563 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5564   EVT VT = Op.getValueType();
5565
5566   // Skip if insert_vec_elt is not supported.
5567   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5568     return SDValue();
5569
5570   SDLoc DL(Op);
5571   unsigned NumElems = Op.getNumOperands();
5572
5573   SDValue VecIn1;
5574   SDValue VecIn2;
5575   SmallVector<unsigned, 4> InsertIndices;
5576   SmallVector<int, 8> Mask(NumElems, -1);
5577
5578   for (unsigned i = 0; i != NumElems; ++i) {
5579     unsigned Opc = Op.getOperand(i).getOpcode();
5580
5581     if (Opc == ISD::UNDEF)
5582       continue;
5583
5584     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5585       // Quit if more than 1 elements need inserting.
5586       if (InsertIndices.size() > 1)
5587         return SDValue();
5588
5589       InsertIndices.push_back(i);
5590       continue;
5591     }
5592
5593     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5594     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5595
5596     // Quit if extracted from vector of different type.
5597     if (ExtractedFromVec.getValueType() != VT)
5598       return SDValue();
5599
5600     // Quit if non-constant index.
5601     if (!isa<ConstantSDNode>(ExtIdx))
5602       return SDValue();
5603
5604     if (VecIn1.getNode() == 0)
5605       VecIn1 = ExtractedFromVec;
5606     else if (VecIn1 != ExtractedFromVec) {
5607       if (VecIn2.getNode() == 0)
5608         VecIn2 = ExtractedFromVec;
5609       else if (VecIn2 != ExtractedFromVec)
5610         // Quit if more than 2 vectors to shuffle
5611         return SDValue();
5612     }
5613
5614     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5615
5616     if (ExtractedFromVec == VecIn1)
5617       Mask[i] = Idx;
5618     else if (ExtractedFromVec == VecIn2)
5619       Mask[i] = Idx + NumElems;
5620   }
5621
5622   if (VecIn1.getNode() == 0)
5623     return SDValue();
5624
5625   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5626   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5627   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5628     unsigned Idx = InsertIndices[i];
5629     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5630                      DAG.getIntPtrConstant(Idx));
5631   }
5632
5633   return NV;
5634 }
5635
5636 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5637 SDValue
5638 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5639
5640   EVT VT = Op.getValueType();
5641   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5642          "Unexpected type in LowerBUILD_VECTORvXi1!");
5643
5644   SDLoc dl(Op);
5645   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5646     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5647     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5648                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5649     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5650                        Ops, VT.getVectorNumElements());
5651   }
5652
5653   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5654     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5655     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5656                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5657     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5658                        Ops, VT.getVectorNumElements());
5659   }
5660
5661   bool AllContants = true;
5662   uint64_t Immediate = 0;
5663   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5664     SDValue In = Op.getOperand(idx);
5665     if (In.getOpcode() == ISD::UNDEF)
5666       continue;
5667     if (!isa<ConstantSDNode>(In)) {
5668       AllContants = false;
5669       break;
5670     }
5671     if (cast<ConstantSDNode>(In)->getZExtValue())
5672       Immediate |= (1ULL << idx);
5673   }
5674
5675   if (AllContants) {
5676     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5677       DAG.getConstant(Immediate, MVT::i16));
5678     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5679                        DAG.getIntPtrConstant(0));
5680   }
5681
5682   if (!isSplatVector(Op.getNode()))
5683     llvm_unreachable("Unsupported predicate operation");
5684
5685   SDValue In = Op.getOperand(0);
5686   SDValue EFLAGS, X86CC;
5687   if (In.getOpcode() == ISD::SETCC) {
5688     SDValue Op0 = In.getOperand(0);
5689     SDValue Op1 = In.getOperand(1);
5690     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5691     bool isFP = Op1.getValueType().isFloatingPoint();
5692     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5693
5694     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5695
5696     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5697     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5698     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5699   } else if (In.getOpcode() == X86ISD::SETCC) {
5700     X86CC = In.getOperand(0);
5701     EFLAGS = In.getOperand(1);
5702   } else {
5703     // The algorithm:
5704     //   Bit1 = In & 0x1
5705     //   if (Bit1 != 0)
5706     //     ZF = 0
5707     //   else
5708     //     ZF = 1
5709     //   if (ZF == 0)
5710     //     res = allOnes ### CMOVNE -1, %res
5711     //   else
5712     //     res = allZero
5713     MVT InVT = In.getValueType().getSimpleVT();
5714     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5715     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5716     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5717   }
5718
5719   if (VT == MVT::v16i1) {
5720     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5721     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5722     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5723           Cst0, Cst1, X86CC, EFLAGS);
5724     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5725   }
5726
5727   if (VT == MVT::v8i1) {
5728     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5729     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5730     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5731           Cst0, Cst1, X86CC, EFLAGS);
5732     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5733     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5734   }
5735   llvm_unreachable("Unsupported predicate operation");
5736 }
5737
5738 SDValue
5739 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5740   SDLoc dl(Op);
5741
5742   MVT VT = Op.getValueType().getSimpleVT();
5743   MVT ExtVT = VT.getVectorElementType();
5744   unsigned NumElems = Op.getNumOperands();
5745
5746   // Generate vectors for predicate vectors.
5747   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5748     return LowerBUILD_VECTORvXi1(Op, DAG);
5749
5750   // Vectors containing all zeros can be matched by pxor and xorps later
5751   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5752     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5753     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5754     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5755       return Op;
5756
5757     return getZeroVector(VT, Subtarget, DAG, dl);
5758   }
5759
5760   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5761   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5762   // vpcmpeqd on 256-bit vectors.
5763   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5764     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5765       return Op;
5766
5767     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5768   }
5769
5770   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5771   if (Broadcast.getNode())
5772     return Broadcast;
5773
5774   unsigned EVTBits = ExtVT.getSizeInBits();
5775
5776   unsigned NumZero  = 0;
5777   unsigned NumNonZero = 0;
5778   unsigned NonZeros = 0;
5779   bool IsAllConstants = true;
5780   SmallSet<SDValue, 8> Values;
5781   for (unsigned i = 0; i < NumElems; ++i) {
5782     SDValue Elt = Op.getOperand(i);
5783     if (Elt.getOpcode() == ISD::UNDEF)
5784       continue;
5785     Values.insert(Elt);
5786     if (Elt.getOpcode() != ISD::Constant &&
5787         Elt.getOpcode() != ISD::ConstantFP)
5788       IsAllConstants = false;
5789     if (X86::isZeroNode(Elt))
5790       NumZero++;
5791     else {
5792       NonZeros |= (1 << i);
5793       NumNonZero++;
5794     }
5795   }
5796
5797   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5798   if (NumNonZero == 0)
5799     return DAG.getUNDEF(VT);
5800
5801   // Special case for single non-zero, non-undef, element.
5802   if (NumNonZero == 1) {
5803     unsigned Idx = countTrailingZeros(NonZeros);
5804     SDValue Item = Op.getOperand(Idx);
5805
5806     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5807     // the value are obviously zero, truncate the value to i32 and do the
5808     // insertion that way.  Only do this if the value is non-constant or if the
5809     // value is a constant being inserted into element 0.  It is cheaper to do
5810     // a constant pool load than it is to do a movd + shuffle.
5811     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5812         (!IsAllConstants || Idx == 0)) {
5813       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5814         // Handle SSE only.
5815         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5816         EVT VecVT = MVT::v4i32;
5817         unsigned VecElts = 4;
5818
5819         // Truncate the value (which may itself be a constant) to i32, and
5820         // convert it to a vector with movd (S2V+shuffle to zero extend).
5821         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5822         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5823         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5824
5825         // Now we have our 32-bit value zero extended in the low element of
5826         // a vector.  If Idx != 0, swizzle it into place.
5827         if (Idx != 0) {
5828           SmallVector<int, 4> Mask;
5829           Mask.push_back(Idx);
5830           for (unsigned i = 1; i != VecElts; ++i)
5831             Mask.push_back(i);
5832           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5833                                       &Mask[0]);
5834         }
5835         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5836       }
5837     }
5838
5839     // If we have a constant or non-constant insertion into the low element of
5840     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5841     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5842     // depending on what the source datatype is.
5843     if (Idx == 0) {
5844       if (NumZero == 0)
5845         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5846
5847       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5848           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5849         if (VT.is256BitVector()) {
5850           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5851           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5852                              Item, DAG.getIntPtrConstant(0));
5853         }
5854         assert(VT.is128BitVector() && "Expected an SSE value type!");
5855         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5856         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5857         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5858       }
5859
5860       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5861         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5862         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5863         if (VT.is256BitVector()) {
5864           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5865           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5866         } else {
5867           assert(VT.is128BitVector() && "Expected an SSE value type!");
5868           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5869         }
5870         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5871       }
5872     }
5873
5874     // Is it a vector logical left shift?
5875     if (NumElems == 2 && Idx == 1 &&
5876         X86::isZeroNode(Op.getOperand(0)) &&
5877         !X86::isZeroNode(Op.getOperand(1))) {
5878       unsigned NumBits = VT.getSizeInBits();
5879       return getVShift(true, VT,
5880                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5881                                    VT, Op.getOperand(1)),
5882                        NumBits/2, DAG, *this, dl);
5883     }
5884
5885     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5886       return SDValue();
5887
5888     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5889     // is a non-constant being inserted into an element other than the low one,
5890     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5891     // movd/movss) to move this into the low element, then shuffle it into
5892     // place.
5893     if (EVTBits == 32) {
5894       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5895
5896       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5897       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5898       SmallVector<int, 8> MaskVec;
5899       for (unsigned i = 0; i != NumElems; ++i)
5900         MaskVec.push_back(i == Idx ? 0 : 1);
5901       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5902     }
5903   }
5904
5905   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5906   if (Values.size() == 1) {
5907     if (EVTBits == 32) {
5908       // Instead of a shuffle like this:
5909       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5910       // Check if it's possible to issue this instead.
5911       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5912       unsigned Idx = countTrailingZeros(NonZeros);
5913       SDValue Item = Op.getOperand(Idx);
5914       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5915         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5916     }
5917     return SDValue();
5918   }
5919
5920   // A vector full of immediates; various special cases are already
5921   // handled, so this is best done with a single constant-pool load.
5922   if (IsAllConstants)
5923     return SDValue();
5924
5925   // For AVX-length vectors, build the individual 128-bit pieces and use
5926   // shuffles to put them in place.
5927   if (VT.is256BitVector()) {
5928     SmallVector<SDValue, 32> V;
5929     for (unsigned i = 0; i != NumElems; ++i)
5930       V.push_back(Op.getOperand(i));
5931
5932     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5933
5934     // Build both the lower and upper subvector.
5935     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5936     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5937                                 NumElems/2);
5938
5939     // Recreate the wider vector with the lower and upper part.
5940     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5941   }
5942
5943   // Let legalizer expand 2-wide build_vectors.
5944   if (EVTBits == 64) {
5945     if (NumNonZero == 1) {
5946       // One half is zero or undef.
5947       unsigned Idx = countTrailingZeros(NonZeros);
5948       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5949                                  Op.getOperand(Idx));
5950       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5951     }
5952     return SDValue();
5953   }
5954
5955   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5956   if (EVTBits == 8 && NumElems == 16) {
5957     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5958                                         Subtarget, *this);
5959     if (V.getNode()) return V;
5960   }
5961
5962   if (EVTBits == 16 && NumElems == 8) {
5963     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5964                                       Subtarget, *this);
5965     if (V.getNode()) return V;
5966   }
5967
5968   // If element VT is == 32 bits, turn it into a number of shuffles.
5969   SmallVector<SDValue, 8> V(NumElems);
5970   if (NumElems == 4 && NumZero > 0) {
5971     for (unsigned i = 0; i < 4; ++i) {
5972       bool isZero = !(NonZeros & (1 << i));
5973       if (isZero)
5974         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5975       else
5976         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5977     }
5978
5979     for (unsigned i = 0; i < 2; ++i) {
5980       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5981         default: break;
5982         case 0:
5983           V[i] = V[i*2];  // Must be a zero vector.
5984           break;
5985         case 1:
5986           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5987           break;
5988         case 2:
5989           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5990           break;
5991         case 3:
5992           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5993           break;
5994       }
5995     }
5996
5997     bool Reverse1 = (NonZeros & 0x3) == 2;
5998     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5999     int MaskVec[] = {
6000       Reverse1 ? 1 : 0,
6001       Reverse1 ? 0 : 1,
6002       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6003       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6004     };
6005     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6006   }
6007
6008   if (Values.size() > 1 && VT.is128BitVector()) {
6009     // Check for a build vector of consecutive loads.
6010     for (unsigned i = 0; i < NumElems; ++i)
6011       V[i] = Op.getOperand(i);
6012
6013     // Check for elements which are consecutive loads.
6014     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
6015     if (LD.getNode())
6016       return LD;
6017
6018     // Check for a build vector from mostly shuffle plus few inserting.
6019     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6020     if (Sh.getNode())
6021       return Sh;
6022
6023     // For SSE 4.1, use insertps to put the high elements into the low element.
6024     if (getSubtarget()->hasSSE41()) {
6025       SDValue Result;
6026       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6027         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6028       else
6029         Result = DAG.getUNDEF(VT);
6030
6031       for (unsigned i = 1; i < NumElems; ++i) {
6032         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6033         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6034                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6035       }
6036       return Result;
6037     }
6038
6039     // Otherwise, expand into a number of unpckl*, start by extending each of
6040     // our (non-undef) elements to the full vector width with the element in the
6041     // bottom slot of the vector (which generates no code for SSE).
6042     for (unsigned i = 0; i < NumElems; ++i) {
6043       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6044         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6045       else
6046         V[i] = DAG.getUNDEF(VT);
6047     }
6048
6049     // Next, we iteratively mix elements, e.g. for v4f32:
6050     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6051     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6052     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6053     unsigned EltStride = NumElems >> 1;
6054     while (EltStride != 0) {
6055       for (unsigned i = 0; i < EltStride; ++i) {
6056         // If V[i+EltStride] is undef and this is the first round of mixing,
6057         // then it is safe to just drop this shuffle: V[i] is already in the
6058         // right place, the one element (since it's the first round) being
6059         // inserted as undef can be dropped.  This isn't safe for successive
6060         // rounds because they will permute elements within both vectors.
6061         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6062             EltStride == NumElems/2)
6063           continue;
6064
6065         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6066       }
6067       EltStride >>= 1;
6068     }
6069     return V[0];
6070   }
6071   return SDValue();
6072 }
6073
6074 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6075 // to create 256-bit vectors from two other 128-bit ones.
6076 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6077   SDLoc dl(Op);
6078   MVT ResVT = Op.getValueType().getSimpleVT();
6079
6080   assert((ResVT.is256BitVector() ||
6081           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6082
6083   SDValue V1 = Op.getOperand(0);
6084   SDValue V2 = Op.getOperand(1);
6085   unsigned NumElems = ResVT.getVectorNumElements();
6086   if(ResVT.is256BitVector())
6087     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6088
6089   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6090 }
6091
6092 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6093   assert(Op.getNumOperands() == 2);
6094
6095   // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
6096   // from two other 128-bit ones.
6097   return LowerAVXCONCAT_VECTORS(Op, DAG);
6098 }
6099
6100 // Try to lower a shuffle node into a simple blend instruction.
6101 static SDValue
6102 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6103                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6104   SDValue V1 = SVOp->getOperand(0);
6105   SDValue V2 = SVOp->getOperand(1);
6106   SDLoc dl(SVOp);
6107   MVT VT = SVOp->getValueType(0).getSimpleVT();
6108   MVT EltVT = VT.getVectorElementType();
6109   unsigned NumElems = VT.getVectorNumElements();
6110
6111   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6112     return SDValue();
6113   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6114     return SDValue();
6115
6116   // Check the mask for BLEND and build the value.
6117   unsigned MaskValue = 0;
6118   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6119   unsigned NumLanes = (NumElems-1)/8 + 1;
6120   unsigned NumElemsInLane = NumElems / NumLanes;
6121
6122   // Blend for v16i16 should be symetric for the both lanes.
6123   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6124
6125     int SndLaneEltIdx = (NumLanes == 2) ?
6126       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6127     int EltIdx = SVOp->getMaskElt(i);
6128
6129     if ((EltIdx < 0 || EltIdx == (int)i) &&
6130         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6131       continue;
6132
6133     if (((unsigned)EltIdx == (i + NumElems)) &&
6134         (SndLaneEltIdx < 0 ||
6135          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6136       MaskValue |= (1<<i);
6137     else
6138       return SDValue();
6139   }
6140
6141   // Convert i32 vectors to floating point if it is not AVX2.
6142   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6143   MVT BlendVT = VT;
6144   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6145     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6146                                NumElems);
6147     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6148     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6149   }
6150
6151   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6152                             DAG.getConstant(MaskValue, MVT::i32));
6153   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6154 }
6155
6156 // v8i16 shuffles - Prefer shuffles in the following order:
6157 // 1. [all]   pshuflw, pshufhw, optional move
6158 // 2. [ssse3] 1 x pshufb
6159 // 3. [ssse3] 2 x pshufb + 1 x por
6160 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6161 static SDValue
6162 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6163                          SelectionDAG &DAG) {
6164   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6165   SDValue V1 = SVOp->getOperand(0);
6166   SDValue V2 = SVOp->getOperand(1);
6167   SDLoc dl(SVOp);
6168   SmallVector<int, 8> MaskVals;
6169
6170   // Determine if more than 1 of the words in each of the low and high quadwords
6171   // of the result come from the same quadword of one of the two inputs.  Undef
6172   // mask values count as coming from any quadword, for better codegen.
6173   unsigned LoQuad[] = { 0, 0, 0, 0 };
6174   unsigned HiQuad[] = { 0, 0, 0, 0 };
6175   std::bitset<4> InputQuads;
6176   for (unsigned i = 0; i < 8; ++i) {
6177     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6178     int EltIdx = SVOp->getMaskElt(i);
6179     MaskVals.push_back(EltIdx);
6180     if (EltIdx < 0) {
6181       ++Quad[0];
6182       ++Quad[1];
6183       ++Quad[2];
6184       ++Quad[3];
6185       continue;
6186     }
6187     ++Quad[EltIdx / 4];
6188     InputQuads.set(EltIdx / 4);
6189   }
6190
6191   int BestLoQuad = -1;
6192   unsigned MaxQuad = 1;
6193   for (unsigned i = 0; i < 4; ++i) {
6194     if (LoQuad[i] > MaxQuad) {
6195       BestLoQuad = i;
6196       MaxQuad = LoQuad[i];
6197     }
6198   }
6199
6200   int BestHiQuad = -1;
6201   MaxQuad = 1;
6202   for (unsigned i = 0; i < 4; ++i) {
6203     if (HiQuad[i] > MaxQuad) {
6204       BestHiQuad = i;
6205       MaxQuad = HiQuad[i];
6206     }
6207   }
6208
6209   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6210   // of the two input vectors, shuffle them into one input vector so only a
6211   // single pshufb instruction is necessary. If There are more than 2 input
6212   // quads, disable the next transformation since it does not help SSSE3.
6213   bool V1Used = InputQuads[0] || InputQuads[1];
6214   bool V2Used = InputQuads[2] || InputQuads[3];
6215   if (Subtarget->hasSSSE3()) {
6216     if (InputQuads.count() == 2 && V1Used && V2Used) {
6217       BestLoQuad = InputQuads[0] ? 0 : 1;
6218       BestHiQuad = InputQuads[2] ? 2 : 3;
6219     }
6220     if (InputQuads.count() > 2) {
6221       BestLoQuad = -1;
6222       BestHiQuad = -1;
6223     }
6224   }
6225
6226   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6227   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6228   // words from all 4 input quadwords.
6229   SDValue NewV;
6230   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6231     int MaskV[] = {
6232       BestLoQuad < 0 ? 0 : BestLoQuad,
6233       BestHiQuad < 0 ? 1 : BestHiQuad
6234     };
6235     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6236                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6237                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6238     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6239
6240     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6241     // source words for the shuffle, to aid later transformations.
6242     bool AllWordsInNewV = true;
6243     bool InOrder[2] = { true, true };
6244     for (unsigned i = 0; i != 8; ++i) {
6245       int idx = MaskVals[i];
6246       if (idx != (int)i)
6247         InOrder[i/4] = false;
6248       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6249         continue;
6250       AllWordsInNewV = false;
6251       break;
6252     }
6253
6254     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6255     if (AllWordsInNewV) {
6256       for (int i = 0; i != 8; ++i) {
6257         int idx = MaskVals[i];
6258         if (idx < 0)
6259           continue;
6260         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6261         if ((idx != i) && idx < 4)
6262           pshufhw = false;
6263         if ((idx != i) && idx > 3)
6264           pshuflw = false;
6265       }
6266       V1 = NewV;
6267       V2Used = false;
6268       BestLoQuad = 0;
6269       BestHiQuad = 1;
6270     }
6271
6272     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6273     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6274     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6275       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6276       unsigned TargetMask = 0;
6277       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6278                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6279       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6280       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6281                              getShufflePSHUFLWImmediate(SVOp);
6282       V1 = NewV.getOperand(0);
6283       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6284     }
6285   }
6286
6287   // Promote splats to a larger type which usually leads to more efficient code.
6288   // FIXME: Is this true if pshufb is available?
6289   if (SVOp->isSplat())
6290     return PromoteSplat(SVOp, DAG);
6291
6292   // If we have SSSE3, and all words of the result are from 1 input vector,
6293   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6294   // is present, fall back to case 4.
6295   if (Subtarget->hasSSSE3()) {
6296     SmallVector<SDValue,16> pshufbMask;
6297
6298     // If we have elements from both input vectors, set the high bit of the
6299     // shuffle mask element to zero out elements that come from V2 in the V1
6300     // mask, and elements that come from V1 in the V2 mask, so that the two
6301     // results can be OR'd together.
6302     bool TwoInputs = V1Used && V2Used;
6303     for (unsigned i = 0; i != 8; ++i) {
6304       int EltIdx = MaskVals[i] * 2;
6305       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6306       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6307       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6308       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6309     }
6310     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6311     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6312                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6313                                  MVT::v16i8, &pshufbMask[0], 16));
6314     if (!TwoInputs)
6315       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6316
6317     // Calculate the shuffle mask for the second input, shuffle it, and
6318     // OR it with the first shuffled input.
6319     pshufbMask.clear();
6320     for (unsigned i = 0; i != 8; ++i) {
6321       int EltIdx = MaskVals[i] * 2;
6322       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6323       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6324       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6325       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6326     }
6327     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6328     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6329                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6330                                  MVT::v16i8, &pshufbMask[0], 16));
6331     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6332     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6333   }
6334
6335   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6336   // and update MaskVals with new element order.
6337   std::bitset<8> InOrder;
6338   if (BestLoQuad >= 0) {
6339     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6340     for (int i = 0; i != 4; ++i) {
6341       int idx = MaskVals[i];
6342       if (idx < 0) {
6343         InOrder.set(i);
6344       } else if ((idx / 4) == BestLoQuad) {
6345         MaskV[i] = idx & 3;
6346         InOrder.set(i);
6347       }
6348     }
6349     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6350                                 &MaskV[0]);
6351
6352     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6353       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6354       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6355                                   NewV.getOperand(0),
6356                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6357     }
6358   }
6359
6360   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6361   // and update MaskVals with the new element order.
6362   if (BestHiQuad >= 0) {
6363     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6364     for (unsigned i = 4; i != 8; ++i) {
6365       int idx = MaskVals[i];
6366       if (idx < 0) {
6367         InOrder.set(i);
6368       } else if ((idx / 4) == BestHiQuad) {
6369         MaskV[i] = (idx & 3) + 4;
6370         InOrder.set(i);
6371       }
6372     }
6373     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6374                                 &MaskV[0]);
6375
6376     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6377       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6378       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6379                                   NewV.getOperand(0),
6380                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6381     }
6382   }
6383
6384   // In case BestHi & BestLo were both -1, which means each quadword has a word
6385   // from each of the four input quadwords, calculate the InOrder bitvector now
6386   // before falling through to the insert/extract cleanup.
6387   if (BestLoQuad == -1 && BestHiQuad == -1) {
6388     NewV = V1;
6389     for (int i = 0; i != 8; ++i)
6390       if (MaskVals[i] < 0 || MaskVals[i] == i)
6391         InOrder.set(i);
6392   }
6393
6394   // The other elements are put in the right place using pextrw and pinsrw.
6395   for (unsigned i = 0; i != 8; ++i) {
6396     if (InOrder[i])
6397       continue;
6398     int EltIdx = MaskVals[i];
6399     if (EltIdx < 0)
6400       continue;
6401     SDValue ExtOp = (EltIdx < 8) ?
6402       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6403                   DAG.getIntPtrConstant(EltIdx)) :
6404       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6405                   DAG.getIntPtrConstant(EltIdx - 8));
6406     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6407                        DAG.getIntPtrConstant(i));
6408   }
6409   return NewV;
6410 }
6411
6412 // v16i8 shuffles - Prefer shuffles in the following order:
6413 // 1. [ssse3] 1 x pshufb
6414 // 2. [ssse3] 2 x pshufb + 1 x por
6415 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6416 static
6417 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6418                                  SelectionDAG &DAG,
6419                                  const X86TargetLowering &TLI) {
6420   SDValue V1 = SVOp->getOperand(0);
6421   SDValue V2 = SVOp->getOperand(1);
6422   SDLoc dl(SVOp);
6423   ArrayRef<int> MaskVals = SVOp->getMask();
6424
6425   // Promote splats to a larger type which usually leads to more efficient code.
6426   // FIXME: Is this true if pshufb is available?
6427   if (SVOp->isSplat())
6428     return PromoteSplat(SVOp, DAG);
6429
6430   // If we have SSSE3, case 1 is generated when all result bytes come from
6431   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6432   // present, fall back to case 3.
6433
6434   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6435   if (TLI.getSubtarget()->hasSSSE3()) {
6436     SmallVector<SDValue,16> pshufbMask;
6437
6438     // If all result elements are from one input vector, then only translate
6439     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6440     //
6441     // Otherwise, we have elements from both input vectors, and must zero out
6442     // elements that come from V2 in the first mask, and V1 in the second mask
6443     // so that we can OR them together.
6444     for (unsigned i = 0; i != 16; ++i) {
6445       int EltIdx = MaskVals[i];
6446       if (EltIdx < 0 || EltIdx >= 16)
6447         EltIdx = 0x80;
6448       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6449     }
6450     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6451                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6452                                  MVT::v16i8, &pshufbMask[0], 16));
6453
6454     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6455     // the 2nd operand if it's undefined or zero.
6456     if (V2.getOpcode() == ISD::UNDEF ||
6457         ISD::isBuildVectorAllZeros(V2.getNode()))
6458       return V1;
6459
6460     // Calculate the shuffle mask for the second input, shuffle it, and
6461     // OR it with the first shuffled input.
6462     pshufbMask.clear();
6463     for (unsigned i = 0; i != 16; ++i) {
6464       int EltIdx = MaskVals[i];
6465       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6466       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6467     }
6468     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6469                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6470                                  MVT::v16i8, &pshufbMask[0], 16));
6471     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6472   }
6473
6474   // No SSSE3 - Calculate in place words and then fix all out of place words
6475   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6476   // the 16 different words that comprise the two doublequadword input vectors.
6477   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6478   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6479   SDValue NewV = V1;
6480   for (int i = 0; i != 8; ++i) {
6481     int Elt0 = MaskVals[i*2];
6482     int Elt1 = MaskVals[i*2+1];
6483
6484     // This word of the result is all undef, skip it.
6485     if (Elt0 < 0 && Elt1 < 0)
6486       continue;
6487
6488     // This word of the result is already in the correct place, skip it.
6489     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6490       continue;
6491
6492     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6493     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6494     SDValue InsElt;
6495
6496     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6497     // using a single extract together, load it and store it.
6498     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6499       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6500                            DAG.getIntPtrConstant(Elt1 / 2));
6501       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6502                         DAG.getIntPtrConstant(i));
6503       continue;
6504     }
6505
6506     // If Elt1 is defined, extract it from the appropriate source.  If the
6507     // source byte is not also odd, shift the extracted word left 8 bits
6508     // otherwise clear the bottom 8 bits if we need to do an or.
6509     if (Elt1 >= 0) {
6510       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6511                            DAG.getIntPtrConstant(Elt1 / 2));
6512       if ((Elt1 & 1) == 0)
6513         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6514                              DAG.getConstant(8,
6515                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6516       else if (Elt0 >= 0)
6517         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6518                              DAG.getConstant(0xFF00, MVT::i16));
6519     }
6520     // If Elt0 is defined, extract it from the appropriate source.  If the
6521     // source byte is not also even, shift the extracted word right 8 bits. If
6522     // Elt1 was also defined, OR the extracted values together before
6523     // inserting them in the result.
6524     if (Elt0 >= 0) {
6525       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6526                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6527       if ((Elt0 & 1) != 0)
6528         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6529                               DAG.getConstant(8,
6530                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6531       else if (Elt1 >= 0)
6532         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6533                              DAG.getConstant(0x00FF, MVT::i16));
6534       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6535                          : InsElt0;
6536     }
6537     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6538                        DAG.getIntPtrConstant(i));
6539   }
6540   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6541 }
6542
6543 // v32i8 shuffles - Translate to VPSHUFB if possible.
6544 static
6545 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6546                                  const X86Subtarget *Subtarget,
6547                                  SelectionDAG &DAG) {
6548   MVT VT = SVOp->getValueType(0).getSimpleVT();
6549   SDValue V1 = SVOp->getOperand(0);
6550   SDValue V2 = SVOp->getOperand(1);
6551   SDLoc dl(SVOp);
6552   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6553
6554   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6555   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6556   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6557
6558   // VPSHUFB may be generated if
6559   // (1) one of input vector is undefined or zeroinitializer.
6560   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6561   // And (2) the mask indexes don't cross the 128-bit lane.
6562   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6563       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6564     return SDValue();
6565
6566   if (V1IsAllZero && !V2IsAllZero) {
6567     CommuteVectorShuffleMask(MaskVals, 32);
6568     V1 = V2;
6569   }
6570   SmallVector<SDValue, 32> pshufbMask;
6571   for (unsigned i = 0; i != 32; i++) {
6572     int EltIdx = MaskVals[i];
6573     if (EltIdx < 0 || EltIdx >= 32)
6574       EltIdx = 0x80;
6575     else {
6576       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6577         // Cross lane is not allowed.
6578         return SDValue();
6579       EltIdx &= 0xf;
6580     }
6581     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6582   }
6583   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6584                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6585                                   MVT::v32i8, &pshufbMask[0], 32));
6586 }
6587
6588 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6589 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6590 /// done when every pair / quad of shuffle mask elements point to elements in
6591 /// the right sequence. e.g.
6592 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6593 static
6594 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6595                                  SelectionDAG &DAG) {
6596   MVT VT = SVOp->getValueType(0).getSimpleVT();
6597   SDLoc dl(SVOp);
6598   unsigned NumElems = VT.getVectorNumElements();
6599   MVT NewVT;
6600   unsigned Scale;
6601   switch (VT.SimpleTy) {
6602   default: llvm_unreachable("Unexpected!");
6603   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6604   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6605   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6606   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6607   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6608   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6609   }
6610
6611   SmallVector<int, 8> MaskVec;
6612   for (unsigned i = 0; i != NumElems; i += Scale) {
6613     int StartIdx = -1;
6614     for (unsigned j = 0; j != Scale; ++j) {
6615       int EltIdx = SVOp->getMaskElt(i+j);
6616       if (EltIdx < 0)
6617         continue;
6618       if (StartIdx < 0)
6619         StartIdx = (EltIdx / Scale);
6620       if (EltIdx != (int)(StartIdx*Scale + j))
6621         return SDValue();
6622     }
6623     MaskVec.push_back(StartIdx);
6624   }
6625
6626   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6627   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6628   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6629 }
6630
6631 /// getVZextMovL - Return a zero-extending vector move low node.
6632 ///
6633 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6634                             SDValue SrcOp, SelectionDAG &DAG,
6635                             const X86Subtarget *Subtarget, SDLoc dl) {
6636   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6637     LoadSDNode *LD = NULL;
6638     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6639       LD = dyn_cast<LoadSDNode>(SrcOp);
6640     if (!LD) {
6641       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6642       // instead.
6643       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6644       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6645           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6646           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6647           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6648         // PR2108
6649         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6650         return DAG.getNode(ISD::BITCAST, dl, VT,
6651                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6652                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6653                                                    OpVT,
6654                                                    SrcOp.getOperand(0)
6655                                                           .getOperand(0))));
6656       }
6657     }
6658   }
6659
6660   return DAG.getNode(ISD::BITCAST, dl, VT,
6661                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6662                                  DAG.getNode(ISD::BITCAST, dl,
6663                                              OpVT, SrcOp)));
6664 }
6665
6666 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6667 /// which could not be matched by any known target speficic shuffle
6668 static SDValue
6669 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6670
6671   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6672   if (NewOp.getNode())
6673     return NewOp;
6674
6675   MVT VT = SVOp->getValueType(0).getSimpleVT();
6676
6677   unsigned NumElems = VT.getVectorNumElements();
6678   unsigned NumLaneElems = NumElems / 2;
6679
6680   SDLoc dl(SVOp);
6681   MVT EltVT = VT.getVectorElementType();
6682   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6683   SDValue Output[2];
6684
6685   SmallVector<int, 16> Mask;
6686   for (unsigned l = 0; l < 2; ++l) {
6687     // Build a shuffle mask for the output, discovering on the fly which
6688     // input vectors to use as shuffle operands (recorded in InputUsed).
6689     // If building a suitable shuffle vector proves too hard, then bail
6690     // out with UseBuildVector set.
6691     bool UseBuildVector = false;
6692     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6693     unsigned LaneStart = l * NumLaneElems;
6694     for (unsigned i = 0; i != NumLaneElems; ++i) {
6695       // The mask element.  This indexes into the input.
6696       int Idx = SVOp->getMaskElt(i+LaneStart);
6697       if (Idx < 0) {
6698         // the mask element does not index into any input vector.
6699         Mask.push_back(-1);
6700         continue;
6701       }
6702
6703       // The input vector this mask element indexes into.
6704       int Input = Idx / NumLaneElems;
6705
6706       // Turn the index into an offset from the start of the input vector.
6707       Idx -= Input * NumLaneElems;
6708
6709       // Find or create a shuffle vector operand to hold this input.
6710       unsigned OpNo;
6711       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6712         if (InputUsed[OpNo] == Input)
6713           // This input vector is already an operand.
6714           break;
6715         if (InputUsed[OpNo] < 0) {
6716           // Create a new operand for this input vector.
6717           InputUsed[OpNo] = Input;
6718           break;
6719         }
6720       }
6721
6722       if (OpNo >= array_lengthof(InputUsed)) {
6723         // More than two input vectors used!  Give up on trying to create a
6724         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6725         UseBuildVector = true;
6726         break;
6727       }
6728
6729       // Add the mask index for the new shuffle vector.
6730       Mask.push_back(Idx + OpNo * NumLaneElems);
6731     }
6732
6733     if (UseBuildVector) {
6734       SmallVector<SDValue, 16> SVOps;
6735       for (unsigned i = 0; i != NumLaneElems; ++i) {
6736         // The mask element.  This indexes into the input.
6737         int Idx = SVOp->getMaskElt(i+LaneStart);
6738         if (Idx < 0) {
6739           SVOps.push_back(DAG.getUNDEF(EltVT));
6740           continue;
6741         }
6742
6743         // The input vector this mask element indexes into.
6744         int Input = Idx / NumElems;
6745
6746         // Turn the index into an offset from the start of the input vector.
6747         Idx -= Input * NumElems;
6748
6749         // Extract the vector element by hand.
6750         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6751                                     SVOp->getOperand(Input),
6752                                     DAG.getIntPtrConstant(Idx)));
6753       }
6754
6755       // Construct the output using a BUILD_VECTOR.
6756       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6757                               SVOps.size());
6758     } else if (InputUsed[0] < 0) {
6759       // No input vectors were used! The result is undefined.
6760       Output[l] = DAG.getUNDEF(NVT);
6761     } else {
6762       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6763                                         (InputUsed[0] % 2) * NumLaneElems,
6764                                         DAG, dl);
6765       // If only one input was used, use an undefined vector for the other.
6766       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6767         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6768                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6769       // At least one input vector was used. Create a new shuffle vector.
6770       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6771     }
6772
6773     Mask.clear();
6774   }
6775
6776   // Concatenate the result back
6777   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6778 }
6779
6780 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6781 /// 4 elements, and match them with several different shuffle types.
6782 static SDValue
6783 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6784   SDValue V1 = SVOp->getOperand(0);
6785   SDValue V2 = SVOp->getOperand(1);
6786   SDLoc dl(SVOp);
6787   MVT VT = SVOp->getValueType(0).getSimpleVT();
6788
6789   assert(VT.is128BitVector() && "Unsupported vector size");
6790
6791   std::pair<int, int> Locs[4];
6792   int Mask1[] = { -1, -1, -1, -1 };
6793   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6794
6795   unsigned NumHi = 0;
6796   unsigned NumLo = 0;
6797   for (unsigned i = 0; i != 4; ++i) {
6798     int Idx = PermMask[i];
6799     if (Idx < 0) {
6800       Locs[i] = std::make_pair(-1, -1);
6801     } else {
6802       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6803       if (Idx < 4) {
6804         Locs[i] = std::make_pair(0, NumLo);
6805         Mask1[NumLo] = Idx;
6806         NumLo++;
6807       } else {
6808         Locs[i] = std::make_pair(1, NumHi);
6809         if (2+NumHi < 4)
6810           Mask1[2+NumHi] = Idx;
6811         NumHi++;
6812       }
6813     }
6814   }
6815
6816   if (NumLo <= 2 && NumHi <= 2) {
6817     // If no more than two elements come from either vector. This can be
6818     // implemented with two shuffles. First shuffle gather the elements.
6819     // The second shuffle, which takes the first shuffle as both of its
6820     // vector operands, put the elements into the right order.
6821     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6822
6823     int Mask2[] = { -1, -1, -1, -1 };
6824
6825     for (unsigned i = 0; i != 4; ++i)
6826       if (Locs[i].first != -1) {
6827         unsigned Idx = (i < 2) ? 0 : 4;
6828         Idx += Locs[i].first * 2 + Locs[i].second;
6829         Mask2[i] = Idx;
6830       }
6831
6832     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6833   }
6834
6835   if (NumLo == 3 || NumHi == 3) {
6836     // Otherwise, we must have three elements from one vector, call it X, and
6837     // one element from the other, call it Y.  First, use a shufps to build an
6838     // intermediate vector with the one element from Y and the element from X
6839     // that will be in the same half in the final destination (the indexes don't
6840     // matter). Then, use a shufps to build the final vector, taking the half
6841     // containing the element from Y from the intermediate, and the other half
6842     // from X.
6843     if (NumHi == 3) {
6844       // Normalize it so the 3 elements come from V1.
6845       CommuteVectorShuffleMask(PermMask, 4);
6846       std::swap(V1, V2);
6847     }
6848
6849     // Find the element from V2.
6850     unsigned HiIndex;
6851     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6852       int Val = PermMask[HiIndex];
6853       if (Val < 0)
6854         continue;
6855       if (Val >= 4)
6856         break;
6857     }
6858
6859     Mask1[0] = PermMask[HiIndex];
6860     Mask1[1] = -1;
6861     Mask1[2] = PermMask[HiIndex^1];
6862     Mask1[3] = -1;
6863     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6864
6865     if (HiIndex >= 2) {
6866       Mask1[0] = PermMask[0];
6867       Mask1[1] = PermMask[1];
6868       Mask1[2] = HiIndex & 1 ? 6 : 4;
6869       Mask1[3] = HiIndex & 1 ? 4 : 6;
6870       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6871     }
6872
6873     Mask1[0] = HiIndex & 1 ? 2 : 0;
6874     Mask1[1] = HiIndex & 1 ? 0 : 2;
6875     Mask1[2] = PermMask[2];
6876     Mask1[3] = PermMask[3];
6877     if (Mask1[2] >= 0)
6878       Mask1[2] += 4;
6879     if (Mask1[3] >= 0)
6880       Mask1[3] += 4;
6881     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6882   }
6883
6884   // Break it into (shuffle shuffle_hi, shuffle_lo).
6885   int LoMask[] = { -1, -1, -1, -1 };
6886   int HiMask[] = { -1, -1, -1, -1 };
6887
6888   int *MaskPtr = LoMask;
6889   unsigned MaskIdx = 0;
6890   unsigned LoIdx = 0;
6891   unsigned HiIdx = 2;
6892   for (unsigned i = 0; i != 4; ++i) {
6893     if (i == 2) {
6894       MaskPtr = HiMask;
6895       MaskIdx = 1;
6896       LoIdx = 0;
6897       HiIdx = 2;
6898     }
6899     int Idx = PermMask[i];
6900     if (Idx < 0) {
6901       Locs[i] = std::make_pair(-1, -1);
6902     } else if (Idx < 4) {
6903       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6904       MaskPtr[LoIdx] = Idx;
6905       LoIdx++;
6906     } else {
6907       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6908       MaskPtr[HiIdx] = Idx;
6909       HiIdx++;
6910     }
6911   }
6912
6913   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6914   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6915   int MaskOps[] = { -1, -1, -1, -1 };
6916   for (unsigned i = 0; i != 4; ++i)
6917     if (Locs[i].first != -1)
6918       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6919   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6920 }
6921
6922 static bool MayFoldVectorLoad(SDValue V) {
6923   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6924     V = V.getOperand(0);
6925
6926   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6927     V = V.getOperand(0);
6928   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6929       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6930     // BUILD_VECTOR (load), undef
6931     V = V.getOperand(0);
6932
6933   return MayFoldLoad(V);
6934 }
6935
6936 static
6937 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6938   EVT VT = Op.getValueType();
6939
6940   // Canonizalize to v2f64.
6941   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6942   return DAG.getNode(ISD::BITCAST, dl, VT,
6943                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6944                                           V1, DAG));
6945 }
6946
6947 static
6948 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6949                         bool HasSSE2) {
6950   SDValue V1 = Op.getOperand(0);
6951   SDValue V2 = Op.getOperand(1);
6952   EVT VT = Op.getValueType();
6953
6954   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6955
6956   if (HasSSE2 && VT == MVT::v2f64)
6957     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6958
6959   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6960   return DAG.getNode(ISD::BITCAST, dl, VT,
6961                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6962                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6963                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6964 }
6965
6966 static
6967 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6968   SDValue V1 = Op.getOperand(0);
6969   SDValue V2 = Op.getOperand(1);
6970   EVT VT = Op.getValueType();
6971
6972   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6973          "unsupported shuffle type");
6974
6975   if (V2.getOpcode() == ISD::UNDEF)
6976     V2 = V1;
6977
6978   // v4i32 or v4f32
6979   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6980 }
6981
6982 static
6983 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6984   SDValue V1 = Op.getOperand(0);
6985   SDValue V2 = Op.getOperand(1);
6986   EVT VT = Op.getValueType();
6987   unsigned NumElems = VT.getVectorNumElements();
6988
6989   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6990   // operand of these instructions is only memory, so check if there's a
6991   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6992   // same masks.
6993   bool CanFoldLoad = false;
6994
6995   // Trivial case, when V2 comes from a load.
6996   if (MayFoldVectorLoad(V2))
6997     CanFoldLoad = true;
6998
6999   // When V1 is a load, it can be folded later into a store in isel, example:
7000   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7001   //    turns into:
7002   //  (MOVLPSmr addr:$src1, VR128:$src2)
7003   // So, recognize this potential and also use MOVLPS or MOVLPD
7004   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7005     CanFoldLoad = true;
7006
7007   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7008   if (CanFoldLoad) {
7009     if (HasSSE2 && NumElems == 2)
7010       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7011
7012     if (NumElems == 4)
7013       // If we don't care about the second element, proceed to use movss.
7014       if (SVOp->getMaskElt(1) != -1)
7015         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7016   }
7017
7018   // movl and movlp will both match v2i64, but v2i64 is never matched by
7019   // movl earlier because we make it strict to avoid messing with the movlp load
7020   // folding logic (see the code above getMOVLP call). Match it here then,
7021   // this is horrible, but will stay like this until we move all shuffle
7022   // matching to x86 specific nodes. Note that for the 1st condition all
7023   // types are matched with movsd.
7024   if (HasSSE2) {
7025     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7026     // as to remove this logic from here, as much as possible
7027     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7028       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7029     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7030   }
7031
7032   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7033
7034   // Invert the operand order and use SHUFPS to match it.
7035   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7036                               getShuffleSHUFImmediate(SVOp), DAG);
7037 }
7038
7039 // Reduce a vector shuffle to zext.
7040 SDValue
7041 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
7042   // PMOVZX is only available from SSE41.
7043   if (!Subtarget->hasSSE41())
7044     return SDValue();
7045
7046   EVT VT = Op.getValueType();
7047
7048   // Only AVX2 support 256-bit vector integer extending.
7049   if (!Subtarget->hasInt256() && VT.is256BitVector())
7050     return SDValue();
7051
7052   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7053   SDLoc DL(Op);
7054   SDValue V1 = Op.getOperand(0);
7055   SDValue V2 = Op.getOperand(1);
7056   unsigned NumElems = VT.getVectorNumElements();
7057
7058   // Extending is an unary operation and the element type of the source vector
7059   // won't be equal to or larger than i64.
7060   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7061       VT.getVectorElementType() == MVT::i64)
7062     return SDValue();
7063
7064   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7065   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7066   while ((1U << Shift) < NumElems) {
7067     if (SVOp->getMaskElt(1U << Shift) == 1)
7068       break;
7069     Shift += 1;
7070     // The maximal ratio is 8, i.e. from i8 to i64.
7071     if (Shift > 3)
7072       return SDValue();
7073   }
7074
7075   // Check the shuffle mask.
7076   unsigned Mask = (1U << Shift) - 1;
7077   for (unsigned i = 0; i != NumElems; ++i) {
7078     int EltIdx = SVOp->getMaskElt(i);
7079     if ((i & Mask) != 0 && EltIdx != -1)
7080       return SDValue();
7081     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7082       return SDValue();
7083   }
7084
7085   LLVMContext *Context = DAG.getContext();
7086   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7087   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
7088   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
7089
7090   if (!isTypeLegal(NVT))
7091     return SDValue();
7092
7093   // Simplify the operand as it's prepared to be fed into shuffle.
7094   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7095   if (V1.getOpcode() == ISD::BITCAST &&
7096       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7097       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7098       V1.getOperand(0)
7099         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
7100     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7101     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7102     ConstantSDNode *CIdx =
7103       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7104     // If it's foldable, i.e. normal load with single use, we will let code
7105     // selection to fold it. Otherwise, we will short the conversion sequence.
7106     if (CIdx && CIdx->getZExtValue() == 0 &&
7107         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7108       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
7109         // The "ext_vec_elt" node is wider than the result node.
7110         // In this case we should extract subvector from V.
7111         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7112         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
7113         EVT FullVT = V.getValueType();
7114         EVT SubVecVT = EVT::getVectorVT(*Context,
7115                                         FullVT.getVectorElementType(),
7116                                         FullVT.getVectorNumElements()/Ratio);
7117         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7118                         DAG.getIntPtrConstant(0));
7119       }
7120       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
7121     }
7122   }
7123
7124   return DAG.getNode(ISD::BITCAST, DL, VT,
7125                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7126 }
7127
7128 SDValue
7129 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
7130   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7131   MVT VT = Op.getValueType().getSimpleVT();
7132   SDLoc dl(Op);
7133   SDValue V1 = Op.getOperand(0);
7134   SDValue V2 = Op.getOperand(1);
7135
7136   if (isZeroShuffle(SVOp))
7137     return getZeroVector(VT, Subtarget, DAG, dl);
7138
7139   // Handle splat operations
7140   if (SVOp->isSplat()) {
7141     // Use vbroadcast whenever the splat comes from a foldable load
7142     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
7143     if (Broadcast.getNode())
7144       return Broadcast;
7145   }
7146
7147   // Check integer expanding shuffles.
7148   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
7149   if (NewOp.getNode())
7150     return NewOp;
7151
7152   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7153   // do it!
7154   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7155       VT == MVT::v16i16 || VT == MVT::v32i8) {
7156     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7157     if (NewOp.getNode())
7158       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7159   } else if ((VT == MVT::v4i32 ||
7160              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7161     // FIXME: Figure out a cleaner way to do this.
7162     // Try to make use of movq to zero out the top part.
7163     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7164       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7165       if (NewOp.getNode()) {
7166         MVT NewVT = NewOp.getValueType().getSimpleVT();
7167         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7168                                NewVT, true, false))
7169           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7170                               DAG, Subtarget, dl);
7171       }
7172     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7173       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7174       if (NewOp.getNode()) {
7175         MVT NewVT = NewOp.getValueType().getSimpleVT();
7176         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7177           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7178                               DAG, Subtarget, dl);
7179       }
7180     }
7181   }
7182   return SDValue();
7183 }
7184
7185 SDValue
7186 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7187   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7188   SDValue V1 = Op.getOperand(0);
7189   SDValue V2 = Op.getOperand(1);
7190   MVT VT = Op.getValueType().getSimpleVT();
7191   SDLoc dl(Op);
7192   unsigned NumElems = VT.getVectorNumElements();
7193   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7194   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7195   bool V1IsSplat = false;
7196   bool V2IsSplat = false;
7197   bool HasSSE2 = Subtarget->hasSSE2();
7198   bool HasFp256    = Subtarget->hasFp256();
7199   bool HasInt256   = Subtarget->hasInt256();
7200   MachineFunction &MF = DAG.getMachineFunction();
7201   bool OptForSize = MF.getFunction()->getAttributes().
7202     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7203
7204   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7205
7206   if (V1IsUndef && V2IsUndef)
7207     return DAG.getUNDEF(VT);
7208
7209   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7210
7211   // Vector shuffle lowering takes 3 steps:
7212   //
7213   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7214   //    narrowing and commutation of operands should be handled.
7215   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7216   //    shuffle nodes.
7217   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7218   //    so the shuffle can be broken into other shuffles and the legalizer can
7219   //    try the lowering again.
7220   //
7221   // The general idea is that no vector_shuffle operation should be left to
7222   // be matched during isel, all of them must be converted to a target specific
7223   // node here.
7224
7225   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7226   // narrowing and commutation of operands should be handled. The actual code
7227   // doesn't include all of those, work in progress...
7228   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
7229   if (NewOp.getNode())
7230     return NewOp;
7231
7232   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7233
7234   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7235   // unpckh_undef). Only use pshufd if speed is more important than size.
7236   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7237     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7238   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7239     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7240
7241   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7242       V2IsUndef && MayFoldVectorLoad(V1))
7243     return getMOVDDup(Op, dl, V1, DAG);
7244
7245   if (isMOVHLPS_v_undef_Mask(M, VT))
7246     return getMOVHighToLow(Op, dl, DAG);
7247
7248   // Use to match splats
7249   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7250       (VT == MVT::v2f64 || VT == MVT::v2i64))
7251     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7252
7253   if (isPSHUFDMask(M, VT)) {
7254     // The actual implementation will match the mask in the if above and then
7255     // during isel it can match several different instructions, not only pshufd
7256     // as its name says, sad but true, emulate the behavior for now...
7257     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7258       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7259
7260     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7261
7262     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7263       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7264
7265     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7266       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7267                                   DAG);
7268
7269     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7270                                 TargetMask, DAG);
7271   }
7272
7273   if (isPALIGNRMask(M, VT, Subtarget))
7274     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7275                                 getShufflePALIGNRImmediate(SVOp),
7276                                 DAG);
7277
7278   // Check if this can be converted into a logical shift.
7279   bool isLeft = false;
7280   unsigned ShAmt = 0;
7281   SDValue ShVal;
7282   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7283   if (isShift && ShVal.hasOneUse()) {
7284     // If the shifted value has multiple uses, it may be cheaper to use
7285     // v_set0 + movlhps or movhlps, etc.
7286     MVT EltVT = VT.getVectorElementType();
7287     ShAmt *= EltVT.getSizeInBits();
7288     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7289   }
7290
7291   if (isMOVLMask(M, VT)) {
7292     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7293       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7294     if (!isMOVLPMask(M, VT)) {
7295       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7296         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7297
7298       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7299         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7300     }
7301   }
7302
7303   // FIXME: fold these into legal mask.
7304   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7305     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7306
7307   if (isMOVHLPSMask(M, VT))
7308     return getMOVHighToLow(Op, dl, DAG);
7309
7310   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7311     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7312
7313   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7314     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7315
7316   if (isMOVLPMask(M, VT))
7317     return getMOVLP(Op, dl, DAG, HasSSE2);
7318
7319   if (ShouldXformToMOVHLPS(M, VT) ||
7320       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7321     return CommuteVectorShuffle(SVOp, DAG);
7322
7323   if (isShift) {
7324     // No better options. Use a vshldq / vsrldq.
7325     MVT EltVT = VT.getVectorElementType();
7326     ShAmt *= EltVT.getSizeInBits();
7327     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7328   }
7329
7330   bool Commuted = false;
7331   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7332   // 1,1,1,1 -> v8i16 though.
7333   V1IsSplat = isSplatVector(V1.getNode());
7334   V2IsSplat = isSplatVector(V2.getNode());
7335
7336   // Canonicalize the splat or undef, if present, to be on the RHS.
7337   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7338     CommuteVectorShuffleMask(M, NumElems);
7339     std::swap(V1, V2);
7340     std::swap(V1IsSplat, V2IsSplat);
7341     Commuted = true;
7342   }
7343
7344   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7345     // Shuffling low element of v1 into undef, just return v1.
7346     if (V2IsUndef)
7347       return V1;
7348     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7349     // the instruction selector will not match, so get a canonical MOVL with
7350     // swapped operands to undo the commute.
7351     return getMOVL(DAG, dl, VT, V2, V1);
7352   }
7353
7354   if (isUNPCKLMask(M, VT, HasInt256))
7355     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7356
7357   if (isUNPCKHMask(M, VT, HasInt256))
7358     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7359
7360   if (V2IsSplat) {
7361     // Normalize mask so all entries that point to V2 points to its first
7362     // element then try to match unpck{h|l} again. If match, return a
7363     // new vector_shuffle with the corrected mask.p
7364     SmallVector<int, 8> NewMask(M.begin(), M.end());
7365     NormalizeMask(NewMask, NumElems);
7366     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7367       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7368     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7369       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7370   }
7371
7372   if (Commuted) {
7373     // Commute is back and try unpck* again.
7374     // FIXME: this seems wrong.
7375     CommuteVectorShuffleMask(M, NumElems);
7376     std::swap(V1, V2);
7377     std::swap(V1IsSplat, V2IsSplat);
7378     Commuted = false;
7379
7380     if (isUNPCKLMask(M, VT, HasInt256))
7381       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7382
7383     if (isUNPCKHMask(M, VT, HasInt256))
7384       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7385   }
7386
7387   // Normalize the node to match x86 shuffle ops if needed
7388   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7389     return CommuteVectorShuffle(SVOp, DAG);
7390
7391   // The checks below are all present in isShuffleMaskLegal, but they are
7392   // inlined here right now to enable us to directly emit target specific
7393   // nodes, and remove one by one until they don't return Op anymore.
7394
7395   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7396       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7397     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7398       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7399   }
7400
7401   if (isPSHUFHWMask(M, VT, HasInt256))
7402     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7403                                 getShufflePSHUFHWImmediate(SVOp),
7404                                 DAG);
7405
7406   if (isPSHUFLWMask(M, VT, HasInt256))
7407     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7408                                 getShufflePSHUFLWImmediate(SVOp),
7409                                 DAG);
7410
7411   if (isSHUFPMask(M, VT, HasFp256))
7412     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7413                                 getShuffleSHUFImmediate(SVOp), DAG);
7414
7415   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7416     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7417   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7418     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7419
7420   //===--------------------------------------------------------------------===//
7421   // Generate target specific nodes for 128 or 256-bit shuffles only
7422   // supported in the AVX instruction set.
7423   //
7424
7425   // Handle VMOVDDUPY permutations
7426   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7427     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7428
7429   // Handle VPERMILPS/D* permutations
7430   if (isVPERMILPMask(M, VT, HasFp256)) {
7431     if (HasInt256 && VT == MVT::v8i32)
7432       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7433                                   getShuffleSHUFImmediate(SVOp), DAG);
7434     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7435                                 getShuffleSHUFImmediate(SVOp), DAG);
7436   }
7437
7438   // Handle VPERM2F128/VPERM2I128 permutations
7439   if (isVPERM2X128Mask(M, VT, HasFp256))
7440     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7441                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7442
7443   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7444   if (BlendOp.getNode())
7445     return BlendOp;
7446
7447   unsigned Imm8;
7448   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7449     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7450
7451   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7452       VT.is512BitVector()) {
7453     EVT MaskEltVT = EVT::getIntegerVT(*DAG.getContext(),
7454       VT.getVectorElementType().getSizeInBits());
7455     EVT MaskVectorVT =
7456         EVT::getVectorVT(*DAG.getContext(),MaskEltVT, NumElems);
7457     SmallVector<SDValue, 16> permclMask;
7458     for (unsigned i = 0; i != NumElems; ++i) {
7459       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7460     }
7461
7462     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7463                                 &permclMask[0], NumElems);
7464     if (V2IsUndef)
7465       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7466       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7467                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7468     return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7469                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7470   }
7471
7472   //===--------------------------------------------------------------------===//
7473   // Since no target specific shuffle was selected for this generic one,
7474   // lower it into other known shuffles. FIXME: this isn't true yet, but
7475   // this is the plan.
7476   //
7477
7478   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7479   if (VT == MVT::v8i16) {
7480     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7481     if (NewOp.getNode())
7482       return NewOp;
7483   }
7484
7485   if (VT == MVT::v16i8) {
7486     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7487     if (NewOp.getNode())
7488       return NewOp;
7489   }
7490
7491   if (VT == MVT::v32i8) {
7492     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7493     if (NewOp.getNode())
7494       return NewOp;
7495   }
7496
7497   // Handle all 128-bit wide vectors with 4 elements, and match them with
7498   // several different shuffle types.
7499   if (NumElems == 4 && VT.is128BitVector())
7500     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7501
7502   // Handle general 256-bit shuffles
7503   if (VT.is256BitVector())
7504     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7505
7506   return SDValue();
7507 }
7508
7509 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7510   MVT VT = Op.getValueType().getSimpleVT();
7511   SDLoc dl(Op);
7512
7513   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7514     return SDValue();
7515
7516   if (VT.getSizeInBits() == 8) {
7517     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7518                                   Op.getOperand(0), Op.getOperand(1));
7519     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7520                                   DAG.getValueType(VT));
7521     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7522   }
7523
7524   if (VT.getSizeInBits() == 16) {
7525     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7526     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7527     if (Idx == 0)
7528       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7529                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7530                                      DAG.getNode(ISD::BITCAST, dl,
7531                                                  MVT::v4i32,
7532                                                  Op.getOperand(0)),
7533                                      Op.getOperand(1)));
7534     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7535                                   Op.getOperand(0), Op.getOperand(1));
7536     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7537                                   DAG.getValueType(VT));
7538     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7539   }
7540
7541   if (VT == MVT::f32) {
7542     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7543     // the result back to FR32 register. It's only worth matching if the
7544     // result has a single use which is a store or a bitcast to i32.  And in
7545     // the case of a store, it's not worth it if the index is a constant 0,
7546     // because a MOVSSmr can be used instead, which is smaller and faster.
7547     if (!Op.hasOneUse())
7548       return SDValue();
7549     SDNode *User = *Op.getNode()->use_begin();
7550     if ((User->getOpcode() != ISD::STORE ||
7551          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7552           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7553         (User->getOpcode() != ISD::BITCAST ||
7554          User->getValueType(0) != MVT::i32))
7555       return SDValue();
7556     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7557                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7558                                               Op.getOperand(0)),
7559                                               Op.getOperand(1));
7560     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7561   }
7562
7563   if (VT == MVT::i32 || VT == MVT::i64) {
7564     // ExtractPS/pextrq works with constant index.
7565     if (isa<ConstantSDNode>(Op.getOperand(1)))
7566       return Op;
7567   }
7568   return SDValue();
7569 }
7570
7571 SDValue
7572 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7573                                            SelectionDAG &DAG) const {
7574   SDLoc dl(Op);
7575   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7576     return SDValue();
7577
7578   SDValue Vec = Op.getOperand(0);
7579   MVT VecVT = Vec.getValueType().getSimpleVT();
7580
7581   // If this is a 256-bit vector result, first extract the 128-bit vector and
7582   // then extract the element from the 128-bit vector.
7583   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7584     SDValue Idx = Op.getOperand(1);
7585     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7586
7587     // Get the 128-bit vector.
7588     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7589     EVT EltVT = VecVT.getVectorElementType();
7590
7591     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7592
7593     //if (IdxVal >= NumElems/2)
7594     //  IdxVal -= NumElems/2;
7595     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7596     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7597                        DAG.getConstant(IdxVal, MVT::i32));
7598   }
7599
7600   assert(VecVT.is128BitVector() && "Unexpected vector length");
7601
7602   if (Subtarget->hasSSE41()) {
7603     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7604     if (Res.getNode())
7605       return Res;
7606   }
7607
7608   MVT VT = Op.getValueType().getSimpleVT();
7609   // TODO: handle v16i8.
7610   if (VT.getSizeInBits() == 16) {
7611     SDValue Vec = Op.getOperand(0);
7612     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7613     if (Idx == 0)
7614       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7615                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7616                                      DAG.getNode(ISD::BITCAST, dl,
7617                                                  MVT::v4i32, Vec),
7618                                      Op.getOperand(1)));
7619     // Transform it so it match pextrw which produces a 32-bit result.
7620     MVT EltVT = MVT::i32;
7621     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7622                                   Op.getOperand(0), Op.getOperand(1));
7623     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7624                                   DAG.getValueType(VT));
7625     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7626   }
7627
7628   if (VT.getSizeInBits() == 32) {
7629     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7630     if (Idx == 0)
7631       return Op;
7632
7633     // SHUFPS the element to the lowest double word, then movss.
7634     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7635     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7636     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7637                                        DAG.getUNDEF(VVT), Mask);
7638     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7639                        DAG.getIntPtrConstant(0));
7640   }
7641
7642   if (VT.getSizeInBits() == 64) {
7643     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7644     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7645     //        to match extract_elt for f64.
7646     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7647     if (Idx == 0)
7648       return Op;
7649
7650     // UNPCKHPD the element to the lowest double word, then movsd.
7651     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7652     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7653     int Mask[2] = { 1, -1 };
7654     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7655     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7656                                        DAG.getUNDEF(VVT), Mask);
7657     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7658                        DAG.getIntPtrConstant(0));
7659   }
7660
7661   return SDValue();
7662 }
7663
7664 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7665   MVT VT = Op.getValueType().getSimpleVT();
7666   MVT EltVT = VT.getVectorElementType();
7667   SDLoc dl(Op);
7668
7669   SDValue N0 = Op.getOperand(0);
7670   SDValue N1 = Op.getOperand(1);
7671   SDValue N2 = Op.getOperand(2);
7672
7673   if (!VT.is128BitVector())
7674     return SDValue();
7675
7676   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7677       isa<ConstantSDNode>(N2)) {
7678     unsigned Opc;
7679     if (VT == MVT::v8i16)
7680       Opc = X86ISD::PINSRW;
7681     else if (VT == MVT::v16i8)
7682       Opc = X86ISD::PINSRB;
7683     else
7684       Opc = X86ISD::PINSRB;
7685
7686     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7687     // argument.
7688     if (N1.getValueType() != MVT::i32)
7689       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7690     if (N2.getValueType() != MVT::i32)
7691       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7692     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7693   }
7694
7695   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7696     // Bits [7:6] of the constant are the source select.  This will always be
7697     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7698     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7699     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7700     // Bits [5:4] of the constant are the destination select.  This is the
7701     //  value of the incoming immediate.
7702     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7703     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7704     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7705     // Create this as a scalar to vector..
7706     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7707     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7708   }
7709
7710   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7711     // PINSR* works with constant index.
7712     return Op;
7713   }
7714   return SDValue();
7715 }
7716
7717 SDValue
7718 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7719   MVT VT = Op.getValueType().getSimpleVT();
7720   MVT EltVT = VT.getVectorElementType();
7721
7722   SDLoc dl(Op);
7723   SDValue N0 = Op.getOperand(0);
7724   SDValue N1 = Op.getOperand(1);
7725   SDValue N2 = Op.getOperand(2);
7726
7727   // If this is a 256-bit vector result, first extract the 128-bit vector,
7728   // insert the element into the extracted half and then place it back.
7729   if (VT.is256BitVector() || VT.is512BitVector()) {
7730     if (!isa<ConstantSDNode>(N2))
7731       return SDValue();
7732
7733     // Get the desired 128-bit vector half.
7734     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7735     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7736
7737     // Insert the element into the desired half.
7738     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7739     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7740
7741     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7742                     DAG.getConstant(IdxIn128, MVT::i32));
7743
7744     // Insert the changed part back to the 256-bit vector
7745     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7746   }
7747
7748   if (Subtarget->hasSSE41())
7749     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7750
7751   if (EltVT == MVT::i8)
7752     return SDValue();
7753
7754   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7755     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7756     // as its second argument.
7757     if (N1.getValueType() != MVT::i32)
7758       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7759     if (N2.getValueType() != MVT::i32)
7760       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7761     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7762   }
7763   return SDValue();
7764 }
7765
7766 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7767   LLVMContext *Context = DAG.getContext();
7768   SDLoc dl(Op);
7769   MVT OpVT = Op.getValueType().getSimpleVT();
7770
7771   // If this is a 256-bit vector result, first insert into a 128-bit
7772   // vector and then insert into the 256-bit vector.
7773   if (!OpVT.is128BitVector()) {
7774     // Insert into a 128-bit vector.
7775     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7776     EVT VT128 = EVT::getVectorVT(*Context,
7777                                  OpVT.getVectorElementType(),
7778                                  OpVT.getVectorNumElements() / SizeFactor);
7779
7780     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7781
7782     // Insert the 128-bit vector.
7783     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7784   }
7785
7786   if (OpVT == MVT::v1i64 &&
7787       Op.getOperand(0).getValueType() == MVT::i64)
7788     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7789
7790   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7791   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7792   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7793                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7794 }
7795
7796 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7797 // a simple subregister reference or explicit instructions to grab
7798 // upper bits of a vector.
7799 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7800                                       SelectionDAG &DAG) {
7801   SDLoc dl(Op);
7802   SDValue In =  Op.getOperand(0);
7803   SDValue Idx = Op.getOperand(1);
7804   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7805   EVT ResVT   = Op.getValueType();
7806   EVT InVT    = In.getValueType();
7807
7808   if (Subtarget->hasFp256()) {
7809     if (ResVT.is128BitVector() &&
7810         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7811         isa<ConstantSDNode>(Idx)) {
7812       return Extract128BitVector(In, IdxVal, DAG, dl);
7813     }
7814     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7815         isa<ConstantSDNode>(Idx)) {
7816       return Extract256BitVector(In, IdxVal, DAG, dl);
7817     }
7818   }
7819   return SDValue();
7820 }
7821
7822 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7823 // simple superregister reference or explicit instructions to insert
7824 // the upper bits of a vector.
7825 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7826                                      SelectionDAG &DAG) {
7827   if (Subtarget->hasFp256()) {
7828     SDLoc dl(Op.getNode());
7829     SDValue Vec = Op.getNode()->getOperand(0);
7830     SDValue SubVec = Op.getNode()->getOperand(1);
7831     SDValue Idx = Op.getNode()->getOperand(2);
7832
7833     if ((Op.getNode()->getValueType(0).is256BitVector() ||
7834          Op.getNode()->getValueType(0).is512BitVector()) &&
7835         SubVec.getNode()->getValueType(0).is128BitVector() &&
7836         isa<ConstantSDNode>(Idx)) {
7837       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7838       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7839     }
7840
7841     if (Op.getNode()->getValueType(0).is512BitVector() &&
7842         SubVec.getNode()->getValueType(0).is256BitVector() &&
7843         isa<ConstantSDNode>(Idx)) {
7844       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7845       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7846     }
7847   }
7848   return SDValue();
7849 }
7850
7851 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7852 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7853 // one of the above mentioned nodes. It has to be wrapped because otherwise
7854 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7855 // be used to form addressing mode. These wrapped nodes will be selected
7856 // into MOV32ri.
7857 SDValue
7858 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7859   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7860
7861   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7862   // global base reg.
7863   unsigned char OpFlag = 0;
7864   unsigned WrapperKind = X86ISD::Wrapper;
7865   CodeModel::Model M = getTargetMachine().getCodeModel();
7866
7867   if (Subtarget->isPICStyleRIPRel() &&
7868       (M == CodeModel::Small || M == CodeModel::Kernel))
7869     WrapperKind = X86ISD::WrapperRIP;
7870   else if (Subtarget->isPICStyleGOT())
7871     OpFlag = X86II::MO_GOTOFF;
7872   else if (Subtarget->isPICStyleStubPIC())
7873     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7874
7875   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7876                                              CP->getAlignment(),
7877                                              CP->getOffset(), OpFlag);
7878   SDLoc DL(CP);
7879   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7880   // With PIC, the address is actually $g + Offset.
7881   if (OpFlag) {
7882     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7883                          DAG.getNode(X86ISD::GlobalBaseReg,
7884                                      SDLoc(), getPointerTy()),
7885                          Result);
7886   }
7887
7888   return Result;
7889 }
7890
7891 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7892   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7893
7894   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7895   // global base reg.
7896   unsigned char OpFlag = 0;
7897   unsigned WrapperKind = X86ISD::Wrapper;
7898   CodeModel::Model M = getTargetMachine().getCodeModel();
7899
7900   if (Subtarget->isPICStyleRIPRel() &&
7901       (M == CodeModel::Small || M == CodeModel::Kernel))
7902     WrapperKind = X86ISD::WrapperRIP;
7903   else if (Subtarget->isPICStyleGOT())
7904     OpFlag = X86II::MO_GOTOFF;
7905   else if (Subtarget->isPICStyleStubPIC())
7906     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7907
7908   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7909                                           OpFlag);
7910   SDLoc DL(JT);
7911   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7912
7913   // With PIC, the address is actually $g + Offset.
7914   if (OpFlag)
7915     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7916                          DAG.getNode(X86ISD::GlobalBaseReg,
7917                                      SDLoc(), getPointerTy()),
7918                          Result);
7919
7920   return Result;
7921 }
7922
7923 SDValue
7924 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7925   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7926
7927   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7928   // global base reg.
7929   unsigned char OpFlag = 0;
7930   unsigned WrapperKind = X86ISD::Wrapper;
7931   CodeModel::Model M = getTargetMachine().getCodeModel();
7932
7933   if (Subtarget->isPICStyleRIPRel() &&
7934       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7935     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7936       OpFlag = X86II::MO_GOTPCREL;
7937     WrapperKind = X86ISD::WrapperRIP;
7938   } else if (Subtarget->isPICStyleGOT()) {
7939     OpFlag = X86II::MO_GOT;
7940   } else if (Subtarget->isPICStyleStubPIC()) {
7941     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7942   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7943     OpFlag = X86II::MO_DARWIN_NONLAZY;
7944   }
7945
7946   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7947
7948   SDLoc DL(Op);
7949   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7950
7951   // With PIC, the address is actually $g + Offset.
7952   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7953       !Subtarget->is64Bit()) {
7954     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7955                          DAG.getNode(X86ISD::GlobalBaseReg,
7956                                      SDLoc(), getPointerTy()),
7957                          Result);
7958   }
7959
7960   // For symbols that require a load from a stub to get the address, emit the
7961   // load.
7962   if (isGlobalStubReference(OpFlag))
7963     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7964                          MachinePointerInfo::getGOT(), false, false, false, 0);
7965
7966   return Result;
7967 }
7968
7969 SDValue
7970 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7971   // Create the TargetBlockAddressAddress node.
7972   unsigned char OpFlags =
7973     Subtarget->ClassifyBlockAddressReference();
7974   CodeModel::Model M = getTargetMachine().getCodeModel();
7975   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7976   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7977   SDLoc dl(Op);
7978   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7979                                              OpFlags);
7980
7981   if (Subtarget->isPICStyleRIPRel() &&
7982       (M == CodeModel::Small || M == CodeModel::Kernel))
7983     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7984   else
7985     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7986
7987   // With PIC, the address is actually $g + Offset.
7988   if (isGlobalRelativeToPICBase(OpFlags)) {
7989     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7990                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7991                          Result);
7992   }
7993
7994   return Result;
7995 }
7996
7997 SDValue
7998 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7999                                       int64_t Offset, SelectionDAG &DAG) const {
8000   // Create the TargetGlobalAddress node, folding in the constant
8001   // offset if it is legal.
8002   unsigned char OpFlags =
8003     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8004   CodeModel::Model M = getTargetMachine().getCodeModel();
8005   SDValue Result;
8006   if (OpFlags == X86II::MO_NO_FLAG &&
8007       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8008     // A direct static reference to a global.
8009     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8010     Offset = 0;
8011   } else {
8012     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8013   }
8014
8015   if (Subtarget->isPICStyleRIPRel() &&
8016       (M == CodeModel::Small || M == CodeModel::Kernel))
8017     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8018   else
8019     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8020
8021   // With PIC, the address is actually $g + Offset.
8022   if (isGlobalRelativeToPICBase(OpFlags)) {
8023     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8024                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8025                          Result);
8026   }
8027
8028   // For globals that require a load from a stub to get the address, emit the
8029   // load.
8030   if (isGlobalStubReference(OpFlags))
8031     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8032                          MachinePointerInfo::getGOT(), false, false, false, 0);
8033
8034   // If there was a non-zero offset that we didn't fold, create an explicit
8035   // addition for it.
8036   if (Offset != 0)
8037     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8038                          DAG.getConstant(Offset, getPointerTy()));
8039
8040   return Result;
8041 }
8042
8043 SDValue
8044 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8045   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8046   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8047   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8048 }
8049
8050 static SDValue
8051 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8052            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8053            unsigned char OperandFlags, bool LocalDynamic = false) {
8054   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8055   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8056   SDLoc dl(GA);
8057   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8058                                            GA->getValueType(0),
8059                                            GA->getOffset(),
8060                                            OperandFlags);
8061
8062   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8063                                            : X86ISD::TLSADDR;
8064
8065   if (InFlag) {
8066     SDValue Ops[] = { Chain,  TGA, *InFlag };
8067     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8068   } else {
8069     SDValue Ops[]  = { Chain, TGA };
8070     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8071   }
8072
8073   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8074   MFI->setAdjustsStack(true);
8075
8076   SDValue Flag = Chain.getValue(1);
8077   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8078 }
8079
8080 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8081 static SDValue
8082 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8083                                 const EVT PtrVT) {
8084   SDValue InFlag;
8085   SDLoc dl(GA);  // ? function entry point might be better
8086   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8087                                    DAG.getNode(X86ISD::GlobalBaseReg,
8088                                                SDLoc(), PtrVT), InFlag);
8089   InFlag = Chain.getValue(1);
8090
8091   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8092 }
8093
8094 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8095 static SDValue
8096 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8097                                 const EVT PtrVT) {
8098   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8099                     X86::RAX, X86II::MO_TLSGD);
8100 }
8101
8102 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8103                                            SelectionDAG &DAG,
8104                                            const EVT PtrVT,
8105                                            bool is64Bit) {
8106   SDLoc dl(GA);
8107
8108   // Get the start address of the TLS block for this module.
8109   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8110       .getInfo<X86MachineFunctionInfo>();
8111   MFI->incNumLocalDynamicTLSAccesses();
8112
8113   SDValue Base;
8114   if (is64Bit) {
8115     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8116                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8117   } else {
8118     SDValue InFlag;
8119     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8120         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8121     InFlag = Chain.getValue(1);
8122     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8123                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8124   }
8125
8126   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8127   // of Base.
8128
8129   // Build x@dtpoff.
8130   unsigned char OperandFlags = X86II::MO_DTPOFF;
8131   unsigned WrapperKind = X86ISD::Wrapper;
8132   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8133                                            GA->getValueType(0),
8134                                            GA->getOffset(), OperandFlags);
8135   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8136
8137   // Add x@dtpoff with the base.
8138   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8139 }
8140
8141 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8142 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8143                                    const EVT PtrVT, TLSModel::Model model,
8144                                    bool is64Bit, bool isPIC) {
8145   SDLoc dl(GA);
8146
8147   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8148   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8149                                                          is64Bit ? 257 : 256));
8150
8151   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8152                                       DAG.getIntPtrConstant(0),
8153                                       MachinePointerInfo(Ptr),
8154                                       false, false, false, 0);
8155
8156   unsigned char OperandFlags = 0;
8157   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8158   // initialexec.
8159   unsigned WrapperKind = X86ISD::Wrapper;
8160   if (model == TLSModel::LocalExec) {
8161     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8162   } else if (model == TLSModel::InitialExec) {
8163     if (is64Bit) {
8164       OperandFlags = X86II::MO_GOTTPOFF;
8165       WrapperKind = X86ISD::WrapperRIP;
8166     } else {
8167       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8168     }
8169   } else {
8170     llvm_unreachable("Unexpected model");
8171   }
8172
8173   // emit "addl x@ntpoff,%eax" (local exec)
8174   // or "addl x@indntpoff,%eax" (initial exec)
8175   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8176   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8177                                            GA->getValueType(0),
8178                                            GA->getOffset(), OperandFlags);
8179   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8180
8181   if (model == TLSModel::InitialExec) {
8182     if (isPIC && !is64Bit) {
8183       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8184                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8185                            Offset);
8186     }
8187
8188     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8189                          MachinePointerInfo::getGOT(), false, false, false,
8190                          0);
8191   }
8192
8193   // The address of the thread local variable is the add of the thread
8194   // pointer with the offset of the variable.
8195   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8196 }
8197
8198 SDValue
8199 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8200
8201   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8202   const GlobalValue *GV = GA->getGlobal();
8203
8204   if (Subtarget->isTargetELF()) {
8205     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8206
8207     switch (model) {
8208       case TLSModel::GeneralDynamic:
8209         if (Subtarget->is64Bit())
8210           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8211         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8212       case TLSModel::LocalDynamic:
8213         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8214                                            Subtarget->is64Bit());
8215       case TLSModel::InitialExec:
8216       case TLSModel::LocalExec:
8217         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8218                                    Subtarget->is64Bit(),
8219                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8220     }
8221     llvm_unreachable("Unknown TLS model.");
8222   }
8223
8224   if (Subtarget->isTargetDarwin()) {
8225     // Darwin only has one model of TLS.  Lower to that.
8226     unsigned char OpFlag = 0;
8227     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8228                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8229
8230     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8231     // global base reg.
8232     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8233                   !Subtarget->is64Bit();
8234     if (PIC32)
8235       OpFlag = X86II::MO_TLVP_PIC_BASE;
8236     else
8237       OpFlag = X86II::MO_TLVP;
8238     SDLoc DL(Op);
8239     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8240                                                 GA->getValueType(0),
8241                                                 GA->getOffset(), OpFlag);
8242     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8243
8244     // With PIC32, the address is actually $g + Offset.
8245     if (PIC32)
8246       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8247                            DAG.getNode(X86ISD::GlobalBaseReg,
8248                                        SDLoc(), getPointerTy()),
8249                            Offset);
8250
8251     // Lowering the machine isd will make sure everything is in the right
8252     // location.
8253     SDValue Chain = DAG.getEntryNode();
8254     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8255     SDValue Args[] = { Chain, Offset };
8256     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8257
8258     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8259     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8260     MFI->setAdjustsStack(true);
8261
8262     // And our return value (tls address) is in the standard call return value
8263     // location.
8264     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8265     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8266                               Chain.getValue(1));
8267   }
8268
8269   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8270     // Just use the implicit TLS architecture
8271     // Need to generate someting similar to:
8272     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8273     //                                  ; from TEB
8274     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8275     //   mov     rcx, qword [rdx+rcx*8]
8276     //   mov     eax, .tls$:tlsvar
8277     //   [rax+rcx] contains the address
8278     // Windows 64bit: gs:0x58
8279     // Windows 32bit: fs:__tls_array
8280
8281     // If GV is an alias then use the aliasee for determining
8282     // thread-localness.
8283     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8284       GV = GA->resolveAliasedGlobal(false);
8285     SDLoc dl(GA);
8286     SDValue Chain = DAG.getEntryNode();
8287
8288     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8289     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8290     // use its literal value of 0x2C.
8291     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8292                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8293                                                              256)
8294                                         : Type::getInt32PtrTy(*DAG.getContext(),
8295                                                               257));
8296
8297     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8298       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8299         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8300
8301     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8302                                         MachinePointerInfo(Ptr),
8303                                         false, false, false, 0);
8304
8305     // Load the _tls_index variable
8306     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8307     if (Subtarget->is64Bit())
8308       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8309                            IDX, MachinePointerInfo(), MVT::i32,
8310                            false, false, 0);
8311     else
8312       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8313                         false, false, false, 0);
8314
8315     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8316                                     getPointerTy());
8317     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8318
8319     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8320     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8321                       false, false, false, 0);
8322
8323     // Get the offset of start of .tls section
8324     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8325                                              GA->getValueType(0),
8326                                              GA->getOffset(), X86II::MO_SECREL);
8327     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8328
8329     // The address of the thread local variable is the add of the thread
8330     // pointer with the offset of the variable.
8331     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8332   }
8333
8334   llvm_unreachable("TLS not implemented for this target.");
8335 }
8336
8337 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8338 /// and take a 2 x i32 value to shift plus a shift amount.
8339 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8340   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8341   EVT VT = Op.getValueType();
8342   unsigned VTBits = VT.getSizeInBits();
8343   SDLoc dl(Op);
8344   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8345   SDValue ShOpLo = Op.getOperand(0);
8346   SDValue ShOpHi = Op.getOperand(1);
8347   SDValue ShAmt  = Op.getOperand(2);
8348   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8349                                      DAG.getConstant(VTBits - 1, MVT::i8))
8350                        : DAG.getConstant(0, VT);
8351
8352   SDValue Tmp2, Tmp3;
8353   if (Op.getOpcode() == ISD::SHL_PARTS) {
8354     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8355     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8356   } else {
8357     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8358     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8359   }
8360
8361   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8362                                 DAG.getConstant(VTBits, MVT::i8));
8363   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8364                              AndNode, DAG.getConstant(0, MVT::i8));
8365
8366   SDValue Hi, Lo;
8367   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8368   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8369   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8370
8371   if (Op.getOpcode() == ISD::SHL_PARTS) {
8372     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8373     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8374   } else {
8375     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8376     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8377   }
8378
8379   SDValue Ops[2] = { Lo, Hi };
8380   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8381 }
8382
8383 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8384                                            SelectionDAG &DAG) const {
8385   EVT SrcVT = Op.getOperand(0).getValueType();
8386
8387   if (SrcVT.isVector())
8388     return SDValue();
8389
8390   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8391          "Unknown SINT_TO_FP to lower!");
8392
8393   // These are really Legal; return the operand so the caller accepts it as
8394   // Legal.
8395   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8396     return Op;
8397   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8398       Subtarget->is64Bit()) {
8399     return Op;
8400   }
8401
8402   SDLoc dl(Op);
8403   unsigned Size = SrcVT.getSizeInBits()/8;
8404   MachineFunction &MF = DAG.getMachineFunction();
8405   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8406   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8407   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8408                                StackSlot,
8409                                MachinePointerInfo::getFixedStack(SSFI),
8410                                false, false, 0);
8411   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8412 }
8413
8414 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8415                                      SDValue StackSlot,
8416                                      SelectionDAG &DAG) const {
8417   // Build the FILD
8418   SDLoc DL(Op);
8419   SDVTList Tys;
8420   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8421   if (useSSE)
8422     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8423   else
8424     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8425
8426   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8427
8428   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8429   MachineMemOperand *MMO;
8430   if (FI) {
8431     int SSFI = FI->getIndex();
8432     MMO =
8433       DAG.getMachineFunction()
8434       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8435                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8436   } else {
8437     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8438     StackSlot = StackSlot.getOperand(1);
8439   }
8440   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8441   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8442                                            X86ISD::FILD, DL,
8443                                            Tys, Ops, array_lengthof(Ops),
8444                                            SrcVT, MMO);
8445
8446   if (useSSE) {
8447     Chain = Result.getValue(1);
8448     SDValue InFlag = Result.getValue(2);
8449
8450     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8451     // shouldn't be necessary except that RFP cannot be live across
8452     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8453     MachineFunction &MF = DAG.getMachineFunction();
8454     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8455     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8456     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8457     Tys = DAG.getVTList(MVT::Other);
8458     SDValue Ops[] = {
8459       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8460     };
8461     MachineMemOperand *MMO =
8462       DAG.getMachineFunction()
8463       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8464                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8465
8466     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8467                                     Ops, array_lengthof(Ops),
8468                                     Op.getValueType(), MMO);
8469     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8470                          MachinePointerInfo::getFixedStack(SSFI),
8471                          false, false, false, 0);
8472   }
8473
8474   return Result;
8475 }
8476
8477 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8478 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8479                                                SelectionDAG &DAG) const {
8480   // This algorithm is not obvious. Here it is what we're trying to output:
8481   /*
8482      movq       %rax,  %xmm0
8483      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8484      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8485      #ifdef __SSE3__
8486        haddpd   %xmm0, %xmm0
8487      #else
8488        pshufd   $0x4e, %xmm0, %xmm1
8489        addpd    %xmm1, %xmm0
8490      #endif
8491   */
8492
8493   SDLoc dl(Op);
8494   LLVMContext *Context = DAG.getContext();
8495
8496   // Build some magic constants.
8497   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8498   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8499   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8500
8501   SmallVector<Constant*,2> CV1;
8502   CV1.push_back(
8503     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8504                                       APInt(64, 0x4330000000000000ULL))));
8505   CV1.push_back(
8506     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8507                                       APInt(64, 0x4530000000000000ULL))));
8508   Constant *C1 = ConstantVector::get(CV1);
8509   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8510
8511   // Load the 64-bit value into an XMM register.
8512   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8513                             Op.getOperand(0));
8514   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8515                               MachinePointerInfo::getConstantPool(),
8516                               false, false, false, 16);
8517   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8518                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8519                               CLod0);
8520
8521   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8522                               MachinePointerInfo::getConstantPool(),
8523                               false, false, false, 16);
8524   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8525   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8526   SDValue Result;
8527
8528   if (Subtarget->hasSSE3()) {
8529     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8530     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8531   } else {
8532     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8533     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8534                                            S2F, 0x4E, DAG);
8535     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8536                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8537                          Sub);
8538   }
8539
8540   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8541                      DAG.getIntPtrConstant(0));
8542 }
8543
8544 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8545 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8546                                                SelectionDAG &DAG) const {
8547   SDLoc dl(Op);
8548   // FP constant to bias correct the final result.
8549   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8550                                    MVT::f64);
8551
8552   // Load the 32-bit value into an XMM register.
8553   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8554                              Op.getOperand(0));
8555
8556   // Zero out the upper parts of the register.
8557   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8558
8559   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8560                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8561                      DAG.getIntPtrConstant(0));
8562
8563   // Or the load with the bias.
8564   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8565                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8566                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8567                                                    MVT::v2f64, Load)),
8568                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8569                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8570                                                    MVT::v2f64, Bias)));
8571   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8572                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8573                    DAG.getIntPtrConstant(0));
8574
8575   // Subtract the bias.
8576   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8577
8578   // Handle final rounding.
8579   EVT DestVT = Op.getValueType();
8580
8581   if (DestVT.bitsLT(MVT::f64))
8582     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8583                        DAG.getIntPtrConstant(0));
8584   if (DestVT.bitsGT(MVT::f64))
8585     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8586
8587   // Handle final rounding.
8588   return Sub;
8589 }
8590
8591 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8592                                                SelectionDAG &DAG) const {
8593   SDValue N0 = Op.getOperand(0);
8594   EVT SVT = N0.getValueType();
8595   SDLoc dl(Op);
8596
8597   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8598           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8599          "Custom UINT_TO_FP is not supported!");
8600
8601   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8602                              SVT.getVectorNumElements());
8603   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8604                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8605 }
8606
8607 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8608                                            SelectionDAG &DAG) const {
8609   SDValue N0 = Op.getOperand(0);
8610   SDLoc dl(Op);
8611
8612   if (Op.getValueType().isVector())
8613     return lowerUINT_TO_FP_vec(Op, DAG);
8614
8615   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8616   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8617   // the optimization here.
8618   if (DAG.SignBitIsZero(N0))
8619     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8620
8621   EVT SrcVT = N0.getValueType();
8622   EVT DstVT = Op.getValueType();
8623   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8624     return LowerUINT_TO_FP_i64(Op, DAG);
8625   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8626     return LowerUINT_TO_FP_i32(Op, DAG);
8627   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8628     return SDValue();
8629
8630   // Make a 64-bit buffer, and use it to build an FILD.
8631   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8632   if (SrcVT == MVT::i32) {
8633     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8634     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8635                                      getPointerTy(), StackSlot, WordOff);
8636     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8637                                   StackSlot, MachinePointerInfo(),
8638                                   false, false, 0);
8639     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8640                                   OffsetSlot, MachinePointerInfo(),
8641                                   false, false, 0);
8642     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8643     return Fild;
8644   }
8645
8646   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8647   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8648                                StackSlot, MachinePointerInfo(),
8649                                false, false, 0);
8650   // For i64 source, we need to add the appropriate power of 2 if the input
8651   // was negative.  This is the same as the optimization in
8652   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8653   // we must be careful to do the computation in x87 extended precision, not
8654   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8655   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8656   MachineMemOperand *MMO =
8657     DAG.getMachineFunction()
8658     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8659                           MachineMemOperand::MOLoad, 8, 8);
8660
8661   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8662   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8663   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8664                                          array_lengthof(Ops), MVT::i64, MMO);
8665
8666   APInt FF(32, 0x5F800000ULL);
8667
8668   // Check whether the sign bit is set.
8669   SDValue SignSet = DAG.getSetCC(dl,
8670                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8671                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8672                                  ISD::SETLT);
8673
8674   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8675   SDValue FudgePtr = DAG.getConstantPool(
8676                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8677                                          getPointerTy());
8678
8679   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8680   SDValue Zero = DAG.getIntPtrConstant(0);
8681   SDValue Four = DAG.getIntPtrConstant(4);
8682   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8683                                Zero, Four);
8684   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8685
8686   // Load the value out, extending it from f32 to f80.
8687   // FIXME: Avoid the extend by constructing the right constant pool?
8688   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8689                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8690                                  MVT::f32, false, false, 4);
8691   // Extend everything to 80 bits to force it to be done on x87.
8692   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8693   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8694 }
8695
8696 std::pair<SDValue,SDValue>
8697 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8698                                     bool IsSigned, bool IsReplace) const {
8699   SDLoc DL(Op);
8700
8701   EVT DstTy = Op.getValueType();
8702
8703   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8704     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8705     DstTy = MVT::i64;
8706   }
8707
8708   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8709          DstTy.getSimpleVT() >= MVT::i16 &&
8710          "Unknown FP_TO_INT to lower!");
8711
8712   // These are really Legal.
8713   if (DstTy == MVT::i32 &&
8714       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8715     return std::make_pair(SDValue(), SDValue());
8716   if (Subtarget->is64Bit() &&
8717       DstTy == MVT::i64 &&
8718       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8719     return std::make_pair(SDValue(), SDValue());
8720
8721   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8722   // stack slot, or into the FTOL runtime function.
8723   MachineFunction &MF = DAG.getMachineFunction();
8724   unsigned MemSize = DstTy.getSizeInBits()/8;
8725   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8726   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8727
8728   unsigned Opc;
8729   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8730     Opc = X86ISD::WIN_FTOL;
8731   else
8732     switch (DstTy.getSimpleVT().SimpleTy) {
8733     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8734     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8735     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8736     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8737     }
8738
8739   SDValue Chain = DAG.getEntryNode();
8740   SDValue Value = Op.getOperand(0);
8741   EVT TheVT = Op.getOperand(0).getValueType();
8742   // FIXME This causes a redundant load/store if the SSE-class value is already
8743   // in memory, such as if it is on the callstack.
8744   if (isScalarFPTypeInSSEReg(TheVT)) {
8745     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8746     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8747                          MachinePointerInfo::getFixedStack(SSFI),
8748                          false, false, 0);
8749     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8750     SDValue Ops[] = {
8751       Chain, StackSlot, DAG.getValueType(TheVT)
8752     };
8753
8754     MachineMemOperand *MMO =
8755       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8756                               MachineMemOperand::MOLoad, MemSize, MemSize);
8757     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8758                                     array_lengthof(Ops), DstTy, MMO);
8759     Chain = Value.getValue(1);
8760     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8761     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8762   }
8763
8764   MachineMemOperand *MMO =
8765     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8766                             MachineMemOperand::MOStore, MemSize, MemSize);
8767
8768   if (Opc != X86ISD::WIN_FTOL) {
8769     // Build the FP_TO_INT*_IN_MEM
8770     SDValue Ops[] = { Chain, Value, StackSlot };
8771     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8772                                            Ops, array_lengthof(Ops), DstTy,
8773                                            MMO);
8774     return std::make_pair(FIST, StackSlot);
8775   } else {
8776     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8777       DAG.getVTList(MVT::Other, MVT::Glue),
8778       Chain, Value);
8779     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8780       MVT::i32, ftol.getValue(1));
8781     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8782       MVT::i32, eax.getValue(2));
8783     SDValue Ops[] = { eax, edx };
8784     SDValue pair = IsReplace
8785       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8786       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8787     return std::make_pair(pair, SDValue());
8788   }
8789 }
8790
8791 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8792                               const X86Subtarget *Subtarget) {
8793   MVT VT = Op->getValueType(0).getSimpleVT();
8794   SDValue In = Op->getOperand(0);
8795   MVT InVT = In.getValueType().getSimpleVT();
8796   SDLoc dl(Op);
8797
8798   // Optimize vectors in AVX mode:
8799   //
8800   //   v8i16 -> v8i32
8801   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8802   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8803   //   Concat upper and lower parts.
8804   //
8805   //   v4i32 -> v4i64
8806   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8807   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8808   //   Concat upper and lower parts.
8809   //
8810
8811   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8812       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8813     return SDValue();
8814
8815   if (Subtarget->hasInt256())
8816     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8817
8818   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8819   SDValue Undef = DAG.getUNDEF(InVT);
8820   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8821   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8822   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8823
8824   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8825                              VT.getVectorNumElements()/2);
8826
8827   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8828   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8829
8830   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8831 }
8832
8833 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8834                                            SelectionDAG &DAG) const {
8835   if (Subtarget->hasFp256()) {
8836     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8837     if (Res.getNode())
8838       return Res;
8839   }
8840
8841   return SDValue();
8842 }
8843 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8844                                             SelectionDAG &DAG) const {
8845   SDLoc DL(Op);
8846   MVT VT = Op.getValueType().getSimpleVT();
8847   SDValue In = Op.getOperand(0);
8848   MVT SVT = In.getValueType().getSimpleVT();
8849
8850   if (Subtarget->hasFp256()) {
8851     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8852     if (Res.getNode())
8853       return Res;
8854   }
8855
8856   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8857       VT.getVectorNumElements() != SVT.getVectorNumElements())
8858     return SDValue();
8859
8860   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8861
8862   // AVX2 has better support of integer extending.
8863   if (Subtarget->hasInt256())
8864     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8865
8866   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8867   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8868   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8869                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8870                                                 DAG.getUNDEF(MVT::v8i16),
8871                                                 &Mask[0]));
8872
8873   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8874 }
8875
8876 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8877   SDLoc DL(Op);
8878   MVT VT = Op.getValueType().getSimpleVT();
8879   SDValue In = Op.getOperand(0);
8880   MVT SVT = In.getValueType().getSimpleVT();
8881
8882   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8883     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8884     if (Subtarget->hasInt256()) {
8885       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8886       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8887       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8888                                 ShufMask);
8889       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8890                          DAG.getIntPtrConstant(0));
8891     }
8892
8893     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8894     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8895                                DAG.getIntPtrConstant(0));
8896     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8897                                DAG.getIntPtrConstant(2));
8898
8899     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8900     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8901
8902     // The PSHUFD mask:
8903     static const int ShufMask1[] = {0, 2, 0, 0};
8904     SDValue Undef = DAG.getUNDEF(VT);
8905     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8906     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8907
8908     // The MOVLHPS mask:
8909     static const int ShufMask2[] = {0, 1, 4, 5};
8910     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8911   }
8912
8913   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8914     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8915     if (Subtarget->hasInt256()) {
8916       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8917
8918       SmallVector<SDValue,32> pshufbMask;
8919       for (unsigned i = 0; i < 2; ++i) {
8920         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8921         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8922         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8923         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8924         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8925         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8926         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8927         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8928         for (unsigned j = 0; j < 8; ++j)
8929           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8930       }
8931       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8932                                &pshufbMask[0], 32);
8933       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8934       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8935
8936       static const int ShufMask[] = {0,  2,  -1,  -1};
8937       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8938                                 &ShufMask[0]);
8939       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8940                        DAG.getIntPtrConstant(0));
8941       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8942     }
8943
8944     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8945                                DAG.getIntPtrConstant(0));
8946
8947     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8948                                DAG.getIntPtrConstant(4));
8949
8950     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8951     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8952
8953     // The PSHUFB mask:
8954     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8955                                    -1, -1, -1, -1, -1, -1, -1, -1};
8956
8957     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8958     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8959     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8960
8961     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8962     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8963
8964     // The MOVLHPS Mask:
8965     static const int ShufMask2[] = {0, 1, 4, 5};
8966     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8967     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8968   }
8969
8970   // Handle truncation of V256 to V128 using shuffles.
8971   if (!VT.is128BitVector() || !SVT.is256BitVector())
8972     return SDValue();
8973
8974   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8975          "Invalid op");
8976   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8977
8978   unsigned NumElems = VT.getVectorNumElements();
8979   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8980                              NumElems * 2);
8981
8982   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8983   // Prepare truncation shuffle mask
8984   for (unsigned i = 0; i != NumElems; ++i)
8985     MaskVec[i] = i * 2;
8986   SDValue V = DAG.getVectorShuffle(NVT, DL,
8987                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8988                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8989   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8990                      DAG.getIntPtrConstant(0));
8991 }
8992
8993 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8994                                            SelectionDAG &DAG) const {
8995   MVT VT = Op.getValueType().getSimpleVT();
8996   if (VT.isVector()) {
8997     if (VT == MVT::v8i16)
8998       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8999                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9000                                      MVT::v8i32, Op.getOperand(0)));
9001     return SDValue();
9002   }
9003
9004   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9005     /*IsSigned=*/ true, /*IsReplace=*/ false);
9006   SDValue FIST = Vals.first, StackSlot = Vals.second;
9007   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9008   if (FIST.getNode() == 0) return Op;
9009
9010   if (StackSlot.getNode())
9011     // Load the result.
9012     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9013                        FIST, StackSlot, MachinePointerInfo(),
9014                        false, false, false, 0);
9015
9016   // The node is the result.
9017   return FIST;
9018 }
9019
9020 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9021                                            SelectionDAG &DAG) const {
9022   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9023     /*IsSigned=*/ false, /*IsReplace=*/ false);
9024   SDValue FIST = Vals.first, StackSlot = Vals.second;
9025   assert(FIST.getNode() && "Unexpected failure");
9026
9027   if (StackSlot.getNode())
9028     // Load the result.
9029     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9030                        FIST, StackSlot, MachinePointerInfo(),
9031                        false, false, false, 0);
9032
9033   // The node is the result.
9034   return FIST;
9035 }
9036
9037 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9038   SDLoc DL(Op);
9039   MVT VT = Op.getValueType().getSimpleVT();
9040   SDValue In = Op.getOperand(0);
9041   MVT SVT = In.getValueType().getSimpleVT();
9042
9043   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9044
9045   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9046                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9047                                  In, DAG.getUNDEF(SVT)));
9048 }
9049
9050 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9051   LLVMContext *Context = DAG.getContext();
9052   SDLoc dl(Op);
9053   MVT VT = Op.getValueType().getSimpleVT();
9054   MVT EltVT = VT;
9055   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9056   if (VT.isVector()) {
9057     EltVT = VT.getVectorElementType();
9058     NumElts = VT.getVectorNumElements();
9059   }
9060   Constant *C;
9061   if (EltVT == MVT::f64)
9062     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9063                                           APInt(64, ~(1ULL << 63))));
9064   else
9065     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9066                                           APInt(32, ~(1U << 31))));
9067   C = ConstantVector::getSplat(NumElts, C);
9068   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9069   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9070   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9071                              MachinePointerInfo::getConstantPool(),
9072                              false, false, false, Alignment);
9073   if (VT.isVector()) {
9074     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9075     return DAG.getNode(ISD::BITCAST, dl, VT,
9076                        DAG.getNode(ISD::AND, dl, ANDVT,
9077                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9078                                                Op.getOperand(0)),
9079                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9080   }
9081   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9082 }
9083
9084 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9085   LLVMContext *Context = DAG.getContext();
9086   SDLoc dl(Op);
9087   MVT VT = Op.getValueType().getSimpleVT();
9088   MVT EltVT = VT;
9089   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9090   if (VT.isVector()) {
9091     EltVT = VT.getVectorElementType();
9092     NumElts = VT.getVectorNumElements();
9093   }
9094   Constant *C;
9095   if (EltVT == MVT::f64)
9096     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9097                                           APInt(64, 1ULL << 63)));
9098   else
9099     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9100                                           APInt(32, 1U << 31)));
9101   C = ConstantVector::getSplat(NumElts, C);
9102   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9103   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9104   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9105                              MachinePointerInfo::getConstantPool(),
9106                              false, false, false, Alignment);
9107   if (VT.isVector()) {
9108     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9109     return DAG.getNode(ISD::BITCAST, dl, VT,
9110                        DAG.getNode(ISD::XOR, dl, XORVT,
9111                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9112                                                Op.getOperand(0)),
9113                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9114   }
9115
9116   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9117 }
9118
9119 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9120   LLVMContext *Context = DAG.getContext();
9121   SDValue Op0 = Op.getOperand(0);
9122   SDValue Op1 = Op.getOperand(1);
9123   SDLoc dl(Op);
9124   MVT VT = Op.getValueType().getSimpleVT();
9125   MVT SrcVT = Op1.getValueType().getSimpleVT();
9126
9127   // If second operand is smaller, extend it first.
9128   if (SrcVT.bitsLT(VT)) {
9129     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9130     SrcVT = VT;
9131   }
9132   // And if it is bigger, shrink it first.
9133   if (SrcVT.bitsGT(VT)) {
9134     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9135     SrcVT = VT;
9136   }
9137
9138   // At this point the operands and the result should have the same
9139   // type, and that won't be f80 since that is not custom lowered.
9140
9141   // First get the sign bit of second operand.
9142   SmallVector<Constant*,4> CV;
9143   if (SrcVT == MVT::f64) {
9144     const fltSemantics &Sem = APFloat::IEEEdouble;
9145     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9146     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9147   } else {
9148     const fltSemantics &Sem = APFloat::IEEEsingle;
9149     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9150     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9151     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9152     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9153   }
9154   Constant *C = ConstantVector::get(CV);
9155   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9156   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9157                               MachinePointerInfo::getConstantPool(),
9158                               false, false, false, 16);
9159   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9160
9161   // Shift sign bit right or left if the two operands have different types.
9162   if (SrcVT.bitsGT(VT)) {
9163     // Op0 is MVT::f32, Op1 is MVT::f64.
9164     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9165     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9166                           DAG.getConstant(32, MVT::i32));
9167     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9168     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9169                           DAG.getIntPtrConstant(0));
9170   }
9171
9172   // Clear first operand sign bit.
9173   CV.clear();
9174   if (VT == MVT::f64) {
9175     const fltSemantics &Sem = APFloat::IEEEdouble;
9176     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9177                                                    APInt(64, ~(1ULL << 63)))));
9178     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9179   } else {
9180     const fltSemantics &Sem = APFloat::IEEEsingle;
9181     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9182                                                    APInt(32, ~(1U << 31)))));
9183     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9184     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9185     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9186   }
9187   C = ConstantVector::get(CV);
9188   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9189   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9190                               MachinePointerInfo::getConstantPool(),
9191                               false, false, false, 16);
9192   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9193
9194   // Or the value with the sign bit.
9195   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9196 }
9197
9198 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9199   SDValue N0 = Op.getOperand(0);
9200   SDLoc dl(Op);
9201   MVT VT = Op.getValueType().getSimpleVT();
9202
9203   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9204   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9205                                   DAG.getConstant(1, VT));
9206   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9207 }
9208
9209 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9210 //
9211 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
9212                                                   SelectionDAG &DAG) const {
9213   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9214
9215   if (!Subtarget->hasSSE41())
9216     return SDValue();
9217
9218   if (!Op->hasOneUse())
9219     return SDValue();
9220
9221   SDNode *N = Op.getNode();
9222   SDLoc DL(N);
9223
9224   SmallVector<SDValue, 8> Opnds;
9225   DenseMap<SDValue, unsigned> VecInMap;
9226   EVT VT = MVT::Other;
9227
9228   // Recognize a special case where a vector is casted into wide integer to
9229   // test all 0s.
9230   Opnds.push_back(N->getOperand(0));
9231   Opnds.push_back(N->getOperand(1));
9232
9233   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9234     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9235     // BFS traverse all OR'd operands.
9236     if (I->getOpcode() == ISD::OR) {
9237       Opnds.push_back(I->getOperand(0));
9238       Opnds.push_back(I->getOperand(1));
9239       // Re-evaluate the number of nodes to be traversed.
9240       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9241       continue;
9242     }
9243
9244     // Quit if a non-EXTRACT_VECTOR_ELT
9245     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9246       return SDValue();
9247
9248     // Quit if without a constant index.
9249     SDValue Idx = I->getOperand(1);
9250     if (!isa<ConstantSDNode>(Idx))
9251       return SDValue();
9252
9253     SDValue ExtractedFromVec = I->getOperand(0);
9254     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9255     if (M == VecInMap.end()) {
9256       VT = ExtractedFromVec.getValueType();
9257       // Quit if not 128/256-bit vector.
9258       if (!VT.is128BitVector() && !VT.is256BitVector())
9259         return SDValue();
9260       // Quit if not the same type.
9261       if (VecInMap.begin() != VecInMap.end() &&
9262           VT != VecInMap.begin()->first.getValueType())
9263         return SDValue();
9264       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9265     }
9266     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9267   }
9268
9269   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9270          "Not extracted from 128-/256-bit vector.");
9271
9272   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9273   SmallVector<SDValue, 8> VecIns;
9274
9275   for (DenseMap<SDValue, unsigned>::const_iterator
9276         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9277     // Quit if not all elements are used.
9278     if (I->second != FullMask)
9279       return SDValue();
9280     VecIns.push_back(I->first);
9281   }
9282
9283   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9284
9285   // Cast all vectors into TestVT for PTEST.
9286   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9287     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9288
9289   // If more than one full vectors are evaluated, OR them first before PTEST.
9290   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9291     // Each iteration will OR 2 nodes and append the result until there is only
9292     // 1 node left, i.e. the final OR'd value of all vectors.
9293     SDValue LHS = VecIns[Slot];
9294     SDValue RHS = VecIns[Slot + 1];
9295     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9296   }
9297
9298   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9299                      VecIns.back(), VecIns.back());
9300 }
9301
9302 /// Emit nodes that will be selected as "test Op0,Op0", or something
9303 /// equivalent.
9304 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9305                                     SelectionDAG &DAG) const {
9306   SDLoc dl(Op);
9307
9308   // CF and OF aren't always set the way we want. Determine which
9309   // of these we need.
9310   bool NeedCF = false;
9311   bool NeedOF = false;
9312   switch (X86CC) {
9313   default: break;
9314   case X86::COND_A: case X86::COND_AE:
9315   case X86::COND_B: case X86::COND_BE:
9316     NeedCF = true;
9317     break;
9318   case X86::COND_G: case X86::COND_GE:
9319   case X86::COND_L: case X86::COND_LE:
9320   case X86::COND_O: case X86::COND_NO:
9321     NeedOF = true;
9322     break;
9323   }
9324
9325   // See if we can use the EFLAGS value from the operand instead of
9326   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9327   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9328   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9329     // Emit a CMP with 0, which is the TEST pattern.
9330     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9331                        DAG.getConstant(0, Op.getValueType()));
9332
9333   unsigned Opcode = 0;
9334   unsigned NumOperands = 0;
9335
9336   // Truncate operations may prevent the merge of the SETCC instruction
9337   // and the arithmetic intruction before it. Attempt to truncate the operands
9338   // of the arithmetic instruction and use a reduced bit-width instruction.
9339   bool NeedTruncation = false;
9340   SDValue ArithOp = Op;
9341   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9342     SDValue Arith = Op->getOperand(0);
9343     // Both the trunc and the arithmetic op need to have one user each.
9344     if (Arith->hasOneUse())
9345       switch (Arith.getOpcode()) {
9346         default: break;
9347         case ISD::ADD:
9348         case ISD::SUB:
9349         case ISD::AND:
9350         case ISD::OR:
9351         case ISD::XOR: {
9352           NeedTruncation = true;
9353           ArithOp = Arith;
9354         }
9355       }
9356   }
9357
9358   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9359   // which may be the result of a CAST.  We use the variable 'Op', which is the
9360   // non-casted variable when we check for possible users.
9361   switch (ArithOp.getOpcode()) {
9362   case ISD::ADD:
9363     // Due to an isel shortcoming, be conservative if this add is likely to be
9364     // selected as part of a load-modify-store instruction. When the root node
9365     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9366     // uses of other nodes in the match, such as the ADD in this case. This
9367     // leads to the ADD being left around and reselected, with the result being
9368     // two adds in the output.  Alas, even if none our users are stores, that
9369     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9370     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9371     // climbing the DAG back to the root, and it doesn't seem to be worth the
9372     // effort.
9373     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9374          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9375       if (UI->getOpcode() != ISD::CopyToReg &&
9376           UI->getOpcode() != ISD::SETCC &&
9377           UI->getOpcode() != ISD::STORE)
9378         goto default_case;
9379
9380     if (ConstantSDNode *C =
9381         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9382       // An add of one will be selected as an INC.
9383       if (C->getAPIntValue() == 1) {
9384         Opcode = X86ISD::INC;
9385         NumOperands = 1;
9386         break;
9387       }
9388
9389       // An add of negative one (subtract of one) will be selected as a DEC.
9390       if (C->getAPIntValue().isAllOnesValue()) {
9391         Opcode = X86ISD::DEC;
9392         NumOperands = 1;
9393         break;
9394       }
9395     }
9396
9397     // Otherwise use a regular EFLAGS-setting add.
9398     Opcode = X86ISD::ADD;
9399     NumOperands = 2;
9400     break;
9401   case ISD::AND: {
9402     // If the primary and result isn't used, don't bother using X86ISD::AND,
9403     // because a TEST instruction will be better.
9404     bool NonFlagUse = false;
9405     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9406            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9407       SDNode *User = *UI;
9408       unsigned UOpNo = UI.getOperandNo();
9409       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9410         // Look pass truncate.
9411         UOpNo = User->use_begin().getOperandNo();
9412         User = *User->use_begin();
9413       }
9414
9415       if (User->getOpcode() != ISD::BRCOND &&
9416           User->getOpcode() != ISD::SETCC &&
9417           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9418         NonFlagUse = true;
9419         break;
9420       }
9421     }
9422
9423     if (!NonFlagUse)
9424       break;
9425   }
9426     // FALL THROUGH
9427   case ISD::SUB:
9428   case ISD::OR:
9429   case ISD::XOR:
9430     // Due to the ISEL shortcoming noted above, be conservative if this op is
9431     // likely to be selected as part of a load-modify-store instruction.
9432     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9433            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9434       if (UI->getOpcode() == ISD::STORE)
9435         goto default_case;
9436
9437     // Otherwise use a regular EFLAGS-setting instruction.
9438     switch (ArithOp.getOpcode()) {
9439     default: llvm_unreachable("unexpected operator!");
9440     case ISD::SUB: Opcode = X86ISD::SUB; break;
9441     case ISD::XOR: Opcode = X86ISD::XOR; break;
9442     case ISD::AND: Opcode = X86ISD::AND; break;
9443     case ISD::OR: {
9444       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9445         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9446         if (EFLAGS.getNode())
9447           return EFLAGS;
9448       }
9449       Opcode = X86ISD::OR;
9450       break;
9451     }
9452     }
9453
9454     NumOperands = 2;
9455     break;
9456   case X86ISD::ADD:
9457   case X86ISD::SUB:
9458   case X86ISD::INC:
9459   case X86ISD::DEC:
9460   case X86ISD::OR:
9461   case X86ISD::XOR:
9462   case X86ISD::AND:
9463     return SDValue(Op.getNode(), 1);
9464   default:
9465   default_case:
9466     break;
9467   }
9468
9469   // If we found that truncation is beneficial, perform the truncation and
9470   // update 'Op'.
9471   if (NeedTruncation) {
9472     EVT VT = Op.getValueType();
9473     SDValue WideVal = Op->getOperand(0);
9474     EVT WideVT = WideVal.getValueType();
9475     unsigned ConvertedOp = 0;
9476     // Use a target machine opcode to prevent further DAGCombine
9477     // optimizations that may separate the arithmetic operations
9478     // from the setcc node.
9479     switch (WideVal.getOpcode()) {
9480       default: break;
9481       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9482       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9483       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9484       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9485       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9486     }
9487
9488     if (ConvertedOp) {
9489       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9490       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9491         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9492         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9493         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9494       }
9495     }
9496   }
9497
9498   if (Opcode == 0)
9499     // Emit a CMP with 0, which is the TEST pattern.
9500     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9501                        DAG.getConstant(0, Op.getValueType()));
9502
9503   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9504   SmallVector<SDValue, 4> Ops;
9505   for (unsigned i = 0; i != NumOperands; ++i)
9506     Ops.push_back(Op.getOperand(i));
9507
9508   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9509   DAG.ReplaceAllUsesWith(Op, New);
9510   return SDValue(New.getNode(), 1);
9511 }
9512
9513 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9514 /// equivalent.
9515 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9516                                    SelectionDAG &DAG) const {
9517   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9518     if (C->getAPIntValue() == 0)
9519       return EmitTest(Op0, X86CC, DAG);
9520
9521   SDLoc dl(Op0);
9522   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9523        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9524     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9525     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9526     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9527                               Op0, Op1);
9528     return SDValue(Sub.getNode(), 1);
9529   }
9530   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9531 }
9532
9533 /// Convert a comparison if required by the subtarget.
9534 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9535                                                  SelectionDAG &DAG) const {
9536   // If the subtarget does not support the FUCOMI instruction, floating-point
9537   // comparisons have to be converted.
9538   if (Subtarget->hasCMov() ||
9539       Cmp.getOpcode() != X86ISD::CMP ||
9540       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9541       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9542     return Cmp;
9543
9544   // The instruction selector will select an FUCOM instruction instead of
9545   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9546   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9547   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9548   SDLoc dl(Cmp);
9549   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9550   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9551   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9552                             DAG.getConstant(8, MVT::i8));
9553   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9554   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9555 }
9556
9557 static bool isAllOnes(SDValue V) {
9558   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9559   return C && C->isAllOnesValue();
9560 }
9561
9562 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9563 /// if it's possible.
9564 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9565                                      SDLoc dl, SelectionDAG &DAG) const {
9566   SDValue Op0 = And.getOperand(0);
9567   SDValue Op1 = And.getOperand(1);
9568   if (Op0.getOpcode() == ISD::TRUNCATE)
9569     Op0 = Op0.getOperand(0);
9570   if (Op1.getOpcode() == ISD::TRUNCATE)
9571     Op1 = Op1.getOperand(0);
9572
9573   SDValue LHS, RHS;
9574   if (Op1.getOpcode() == ISD::SHL)
9575     std::swap(Op0, Op1);
9576   if (Op0.getOpcode() == ISD::SHL) {
9577     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9578       if (And00C->getZExtValue() == 1) {
9579         // If we looked past a truncate, check that it's only truncating away
9580         // known zeros.
9581         unsigned BitWidth = Op0.getValueSizeInBits();
9582         unsigned AndBitWidth = And.getValueSizeInBits();
9583         if (BitWidth > AndBitWidth) {
9584           APInt Zeros, Ones;
9585           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9586           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9587             return SDValue();
9588         }
9589         LHS = Op1;
9590         RHS = Op0.getOperand(1);
9591       }
9592   } else if (Op1.getOpcode() == ISD::Constant) {
9593     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9594     uint64_t AndRHSVal = AndRHS->getZExtValue();
9595     SDValue AndLHS = Op0;
9596
9597     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9598       LHS = AndLHS.getOperand(0);
9599       RHS = AndLHS.getOperand(1);
9600     }
9601
9602     // Use BT if the immediate can't be encoded in a TEST instruction.
9603     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9604       LHS = AndLHS;
9605       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9606     }
9607   }
9608
9609   if (LHS.getNode()) {
9610     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9611     // instruction.  Since the shift amount is in-range-or-undefined, we know
9612     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9613     // the encoding for the i16 version is larger than the i32 version.
9614     // Also promote i16 to i32 for performance / code size reason.
9615     if (LHS.getValueType() == MVT::i8 ||
9616         LHS.getValueType() == MVT::i16)
9617       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9618
9619     // If the operand types disagree, extend the shift amount to match.  Since
9620     // BT ignores high bits (like shifts) we can use anyextend.
9621     if (LHS.getValueType() != RHS.getValueType())
9622       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9623
9624     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9625     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9626     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9627                        DAG.getConstant(Cond, MVT::i8), BT);
9628   }
9629
9630   return SDValue();
9631 }
9632
9633 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9634 /// mask CMPs.
9635 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9636                               SDValue &Op1) {
9637   unsigned SSECC;
9638   bool Swap = false;
9639
9640   // SSE Condition code mapping:
9641   //  0 - EQ
9642   //  1 - LT
9643   //  2 - LE
9644   //  3 - UNORD
9645   //  4 - NEQ
9646   //  5 - NLT
9647   //  6 - NLE
9648   //  7 - ORD
9649   switch (SetCCOpcode) {
9650   default: llvm_unreachable("Unexpected SETCC condition");
9651   case ISD::SETOEQ:
9652   case ISD::SETEQ:  SSECC = 0; break;
9653   case ISD::SETOGT:
9654   case ISD::SETGT:  Swap = true; // Fallthrough
9655   case ISD::SETLT:
9656   case ISD::SETOLT: SSECC = 1; break;
9657   case ISD::SETOGE:
9658   case ISD::SETGE:  Swap = true; // Fallthrough
9659   case ISD::SETLE:
9660   case ISD::SETOLE: SSECC = 2; break;
9661   case ISD::SETUO:  SSECC = 3; break;
9662   case ISD::SETUNE:
9663   case ISD::SETNE:  SSECC = 4; break;
9664   case ISD::SETULE: Swap = true; // Fallthrough
9665   case ISD::SETUGE: SSECC = 5; break;
9666   case ISD::SETULT: Swap = true; // Fallthrough
9667   case ISD::SETUGT: SSECC = 6; break;
9668   case ISD::SETO:   SSECC = 7; break;
9669   case ISD::SETUEQ:
9670   case ISD::SETONE: SSECC = 8; break;
9671   }
9672   if (Swap)
9673     std::swap(Op0, Op1);
9674
9675   return SSECC;
9676 }
9677
9678 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9679 // ones, and then concatenate the result back.
9680 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9681   MVT VT = Op.getValueType().getSimpleVT();
9682
9683   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9684          "Unsupported value type for operation");
9685
9686   unsigned NumElems = VT.getVectorNumElements();
9687   SDLoc dl(Op);
9688   SDValue CC = Op.getOperand(2);
9689
9690   // Extract the LHS vectors
9691   SDValue LHS = Op.getOperand(0);
9692   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9693   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9694
9695   // Extract the RHS vectors
9696   SDValue RHS = Op.getOperand(1);
9697   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9698   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9699
9700   // Issue the operation on the smaller types and concatenate the result back
9701   MVT EltVT = VT.getVectorElementType();
9702   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9703   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9704                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9705                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9706 }
9707
9708 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9709                            SelectionDAG &DAG) {
9710   SDValue Cond;
9711   SDValue Op0 = Op.getOperand(0);
9712   SDValue Op1 = Op.getOperand(1);
9713   SDValue CC = Op.getOperand(2);
9714   MVT VT = Op.getValueType().getSimpleVT();
9715   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9716   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9717   SDLoc dl(Op);
9718
9719   if (isFP) {
9720 #ifndef NDEBUG
9721     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9722     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9723 #endif
9724
9725     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
9726
9727     // In the two special cases we can't handle, emit two comparisons.
9728     if (SSECC == 8) {
9729       unsigned CC0, CC1;
9730       unsigned CombineOpc;
9731       if (SetCCOpcode == ISD::SETUEQ) {
9732         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9733       } else {
9734         assert(SetCCOpcode == ISD::SETONE);
9735         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9736       }
9737
9738       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9739                                  DAG.getConstant(CC0, MVT::i8));
9740       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9741                                  DAG.getConstant(CC1, MVT::i8));
9742       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9743     }
9744     // Handle all other FP comparisons here.
9745     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9746                        DAG.getConstant(SSECC, MVT::i8));
9747   }
9748
9749   // Break 256-bit integer vector compare into smaller ones.
9750   if (VT.is256BitVector() && !Subtarget->hasInt256())
9751     return Lower256IntVSETCC(Op, DAG);
9752
9753   // We are handling one of the integer comparisons here.  Since SSE only has
9754   // GT and EQ comparisons for integer, swapping operands and multiple
9755   // operations may be required for some comparisons.
9756   unsigned Opc;
9757   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9758   
9759   switch (SetCCOpcode) {
9760   default: llvm_unreachable("Unexpected SETCC condition");
9761   case ISD::SETNE:  Invert = true;
9762   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9763   case ISD::SETLT:  Swap = true;
9764   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9765   case ISD::SETGE:  Swap = true;
9766   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9767   case ISD::SETULT: Swap = true;
9768   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9769   case ISD::SETUGE: Swap = true;
9770   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9771   }
9772   
9773   // Special case: Use min/max operations for SETULE/SETUGE
9774   MVT VET = VT.getVectorElementType();
9775   bool hasMinMax =
9776        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9777     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
9778   
9779   if (hasMinMax) {
9780     switch (SetCCOpcode) {
9781     default: break;
9782     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9783     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9784     }
9785     
9786     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9787   }
9788   
9789   if (Swap)
9790     std::swap(Op0, Op1);
9791
9792   // Check that the operation in question is available (most are plain SSE2,
9793   // but PCMPGTQ and PCMPEQQ have different requirements).
9794   if (VT == MVT::v2i64) {
9795     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9796       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9797
9798       // First cast everything to the right type.
9799       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9800       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9801
9802       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9803       // bits of the inputs before performing those operations. The lower
9804       // compare is always unsigned.
9805       SDValue SB;
9806       if (FlipSigns) {
9807         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9808       } else {
9809         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9810         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9811         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9812                          Sign, Zero, Sign, Zero);
9813       }
9814       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9815       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9816
9817       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9818       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9819       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9820
9821       // Create masks for only the low parts/high parts of the 64 bit integers.
9822       static const int MaskHi[] = { 1, 1, 3, 3 };
9823       static const int MaskLo[] = { 0, 0, 2, 2 };
9824       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9825       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9826       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9827
9828       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9829       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9830
9831       if (Invert)
9832         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9833
9834       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9835     }
9836
9837     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9838       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9839       // pcmpeqd + pshufd + pand.
9840       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9841
9842       // First cast everything to the right type.
9843       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9844       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9845
9846       // Do the compare.
9847       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9848
9849       // Make sure the lower and upper halves are both all-ones.
9850       static const int Mask[] = { 1, 0, 3, 2 };
9851       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9852       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9853
9854       if (Invert)
9855         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9856
9857       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9858     }
9859   }
9860
9861   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9862   // bits of the inputs before performing those operations.
9863   if (FlipSigns) {
9864     EVT EltVT = VT.getVectorElementType();
9865     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9866     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9867     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9868   }
9869
9870   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9871
9872   // If the logical-not of the result is required, perform that now.
9873   if (Invert)
9874     Result = DAG.getNOT(dl, Result, VT);
9875   
9876   if (MinMax)
9877     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9878
9879   return Result;
9880 }
9881
9882 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9883
9884   MVT VT = Op.getValueType().getSimpleVT();
9885
9886   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9887
9888   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9889   SDValue Op0 = Op.getOperand(0);
9890   SDValue Op1 = Op.getOperand(1);
9891   SDLoc dl(Op);
9892   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9893
9894   // Optimize to BT if possible.
9895   // Lower (X & (1 << N)) == 0 to BT(X, N).
9896   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9897   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9898   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9899       Op1.getOpcode() == ISD::Constant &&
9900       cast<ConstantSDNode>(Op1)->isNullValue() &&
9901       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9902     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9903     if (NewSetCC.getNode())
9904       return NewSetCC;
9905   }
9906
9907   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9908   // these.
9909   if (Op1.getOpcode() == ISD::Constant &&
9910       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9911        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9912       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9913
9914     // If the input is a setcc, then reuse the input setcc or use a new one with
9915     // the inverted condition.
9916     if (Op0.getOpcode() == X86ISD::SETCC) {
9917       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9918       bool Invert = (CC == ISD::SETNE) ^
9919         cast<ConstantSDNode>(Op1)->isNullValue();
9920       if (!Invert) return Op0;
9921
9922       CCode = X86::GetOppositeBranchCondition(CCode);
9923       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9924                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9925     }
9926   }
9927
9928   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9929   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9930   if (X86CC == X86::COND_INVALID)
9931     return SDValue();
9932
9933   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9934   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9935   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9936                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9937 }
9938
9939 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9940 static bool isX86LogicalCmp(SDValue Op) {
9941   unsigned Opc = Op.getNode()->getOpcode();
9942   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9943       Opc == X86ISD::SAHF)
9944     return true;
9945   if (Op.getResNo() == 1 &&
9946       (Opc == X86ISD::ADD ||
9947        Opc == X86ISD::SUB ||
9948        Opc == X86ISD::ADC ||
9949        Opc == X86ISD::SBB ||
9950        Opc == X86ISD::SMUL ||
9951        Opc == X86ISD::UMUL ||
9952        Opc == X86ISD::INC ||
9953        Opc == X86ISD::DEC ||
9954        Opc == X86ISD::OR ||
9955        Opc == X86ISD::XOR ||
9956        Opc == X86ISD::AND))
9957     return true;
9958
9959   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9960     return true;
9961
9962   return false;
9963 }
9964
9965 static bool isZero(SDValue V) {
9966   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9967   return C && C->isNullValue();
9968 }
9969
9970 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9971   if (V.getOpcode() != ISD::TRUNCATE)
9972     return false;
9973
9974   SDValue VOp0 = V.getOperand(0);
9975   unsigned InBits = VOp0.getValueSizeInBits();
9976   unsigned Bits = V.getValueSizeInBits();
9977   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9978 }
9979
9980 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9981   bool addTest = true;
9982   SDValue Cond  = Op.getOperand(0);
9983   SDValue Op1 = Op.getOperand(1);
9984   SDValue Op2 = Op.getOperand(2);
9985   SDLoc DL(Op);
9986   EVT VT = Op1.getValueType();
9987   SDValue CC;
9988
9989   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
9990   // are available. Otherwise fp cmovs get lowered into a less efficient branch
9991   // sequence later on.
9992   if (Cond.getOpcode() == ISD::SETCC &&
9993       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
9994        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
9995       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
9996     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
9997     int SSECC = translateX86FSETCC(
9998         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
9999
10000     if (SSECC != 8) {
10001       unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd;
10002       SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1,
10003                                 DAG.getConstant(SSECC, MVT::i8));
10004       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10005       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10006       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10007     }
10008   }
10009
10010   if (Cond.getOpcode() == ISD::SETCC) {
10011     SDValue NewCond = LowerSETCC(Cond, DAG);
10012     if (NewCond.getNode())
10013       Cond = NewCond;
10014   }
10015
10016   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10017   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10018   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10019   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10020   if (Cond.getOpcode() == X86ISD::SETCC &&
10021       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10022       isZero(Cond.getOperand(1).getOperand(1))) {
10023     SDValue Cmp = Cond.getOperand(1);
10024
10025     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10026
10027     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10028         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10029       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10030
10031       SDValue CmpOp0 = Cmp.getOperand(0);
10032       // Apply further optimizations for special cases
10033       // (select (x != 0), -1, 0) -> neg & sbb
10034       // (select (x == 0), 0, -1) -> neg & sbb
10035       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10036         if (YC->isNullValue() &&
10037             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10038           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10039           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10040                                     DAG.getConstant(0, CmpOp0.getValueType()),
10041                                     CmpOp0);
10042           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10043                                     DAG.getConstant(X86::COND_B, MVT::i8),
10044                                     SDValue(Neg.getNode(), 1));
10045           return Res;
10046         }
10047
10048       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10049                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10050       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10051
10052       SDValue Res =   // Res = 0 or -1.
10053         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10054                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10055
10056       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10057         Res = DAG.getNOT(DL, Res, Res.getValueType());
10058
10059       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10060       if (N2C == 0 || !N2C->isNullValue())
10061         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10062       return Res;
10063     }
10064   }
10065
10066   // Look past (and (setcc_carry (cmp ...)), 1).
10067   if (Cond.getOpcode() == ISD::AND &&
10068       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10069     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10070     if (C && C->getAPIntValue() == 1)
10071       Cond = Cond.getOperand(0);
10072   }
10073
10074   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10075   // setting operand in place of the X86ISD::SETCC.
10076   unsigned CondOpcode = Cond.getOpcode();
10077   if (CondOpcode == X86ISD::SETCC ||
10078       CondOpcode == X86ISD::SETCC_CARRY) {
10079     CC = Cond.getOperand(0);
10080
10081     SDValue Cmp = Cond.getOperand(1);
10082     unsigned Opc = Cmp.getOpcode();
10083     MVT VT = Op.getValueType().getSimpleVT();
10084
10085     bool IllegalFPCMov = false;
10086     if (VT.isFloatingPoint() && !VT.isVector() &&
10087         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10088       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10089
10090     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10091         Opc == X86ISD::BT) { // FIXME
10092       Cond = Cmp;
10093       addTest = false;
10094     }
10095   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10096              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10097              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10098               Cond.getOperand(0).getValueType() != MVT::i8)) {
10099     SDValue LHS = Cond.getOperand(0);
10100     SDValue RHS = Cond.getOperand(1);
10101     unsigned X86Opcode;
10102     unsigned X86Cond;
10103     SDVTList VTs;
10104     switch (CondOpcode) {
10105     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10106     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10107     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10108     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10109     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10110     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10111     default: llvm_unreachable("unexpected overflowing operator");
10112     }
10113     if (CondOpcode == ISD::UMULO)
10114       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10115                           MVT::i32);
10116     else
10117       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10118
10119     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10120
10121     if (CondOpcode == ISD::UMULO)
10122       Cond = X86Op.getValue(2);
10123     else
10124       Cond = X86Op.getValue(1);
10125
10126     CC = DAG.getConstant(X86Cond, MVT::i8);
10127     addTest = false;
10128   }
10129
10130   if (addTest) {
10131     // Look pass the truncate if the high bits are known zero.
10132     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10133         Cond = Cond.getOperand(0);
10134
10135     // We know the result of AND is compared against zero. Try to match
10136     // it to BT.
10137     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10138       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10139       if (NewSetCC.getNode()) {
10140         CC = NewSetCC.getOperand(0);
10141         Cond = NewSetCC.getOperand(1);
10142         addTest = false;
10143       }
10144     }
10145   }
10146
10147   if (addTest) {
10148     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10149     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10150   }
10151
10152   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10153   // a <  b ?  0 : -1 -> RES = setcc_carry
10154   // a >= b ? -1 :  0 -> RES = setcc_carry
10155   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10156   if (Cond.getOpcode() == X86ISD::SUB) {
10157     Cond = ConvertCmpIfNecessary(Cond, DAG);
10158     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10159
10160     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10161         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10162       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10163                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10164       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10165         return DAG.getNOT(DL, Res, Res.getValueType());
10166       return Res;
10167     }
10168   }
10169
10170   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10171   // widen the cmov and push the truncate through. This avoids introducing a new
10172   // branch during isel and doesn't add any extensions.
10173   if (Op.getValueType() == MVT::i8 &&
10174       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10175     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10176     if (T1.getValueType() == T2.getValueType() &&
10177         // Blacklist CopyFromReg to avoid partial register stalls.
10178         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10179       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10180       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10181       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10182     }
10183   }
10184
10185   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10186   // condition is true.
10187   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10188   SDValue Ops[] = { Op2, Op1, CC, Cond };
10189   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10190 }
10191
10192 SDValue X86TargetLowering::LowerSIGN_EXTEND_AVX512(SDValue Op,
10193                                                  SelectionDAG &DAG) const {
10194   EVT VT = Op->getValueType(0);
10195   SDValue In = Op->getOperand(0);
10196   EVT InVT = In.getValueType();
10197   SDLoc dl(Op);
10198
10199   if (InVT.getVectorElementType().getSizeInBits() >=8 &&
10200       VT.getVectorElementType().getSizeInBits() >= 32)
10201     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10202
10203   if (InVT.getVectorElementType() == MVT::i1) {
10204     unsigned int NumElts = InVT.getVectorNumElements();
10205     assert ((NumElts == 8 || NumElts == 16) &&
10206       "Unsupported SIGN_EXTEND operation");
10207     if (VT.getVectorElementType().getSizeInBits() >= 32) {
10208       Constant *C =
10209        ConstantInt::get(*DAG.getContext(),
10210                         (NumElts == 8)? APInt(64, ~0ULL): APInt(32, ~0U));
10211       SDValue CP = DAG.getConstantPool(C, getPointerTy());
10212       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10213       SDValue Ld = DAG.getLoad(VT.getScalarType(), dl, DAG.getEntryNode(), CP,
10214                              MachinePointerInfo::getConstantPool(),
10215                              false, false, false, Alignment);
10216       return DAG.getNode(X86ISD::VBROADCASTM, dl, VT, In, Ld);
10217     }
10218   }
10219   return SDValue();
10220 }
10221
10222 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10223                                             SelectionDAG &DAG) const {
10224   MVT VT = Op->getValueType(0).getSimpleVT();
10225   SDValue In = Op->getOperand(0);
10226   MVT InVT = In.getValueType().getSimpleVT();
10227   SDLoc dl(Op);
10228
10229   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10230     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10231
10232   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10233       (VT != MVT::v8i32 || InVT != MVT::v8i16))
10234     return SDValue();
10235
10236   if (Subtarget->hasInt256())
10237     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10238
10239   // Optimize vectors in AVX mode
10240   // Sign extend  v8i16 to v8i32 and
10241   //              v4i32 to v4i64
10242   //
10243   // Divide input vector into two parts
10244   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10245   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10246   // concat the vectors to original VT
10247
10248   unsigned NumElems = InVT.getVectorNumElements();
10249   SDValue Undef = DAG.getUNDEF(InVT);
10250
10251   SmallVector<int,8> ShufMask1(NumElems, -1);
10252   for (unsigned i = 0; i != NumElems/2; ++i)
10253     ShufMask1[i] = i;
10254
10255   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10256
10257   SmallVector<int,8> ShufMask2(NumElems, -1);
10258   for (unsigned i = 0; i != NumElems/2; ++i)
10259     ShufMask2[i] = i + NumElems/2;
10260
10261   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10262
10263   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10264                                 VT.getVectorNumElements()/2);
10265
10266   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10267   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10268
10269   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10270 }
10271
10272 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10273 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10274 // from the AND / OR.
10275 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10276   Opc = Op.getOpcode();
10277   if (Opc != ISD::OR && Opc != ISD::AND)
10278     return false;
10279   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10280           Op.getOperand(0).hasOneUse() &&
10281           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10282           Op.getOperand(1).hasOneUse());
10283 }
10284
10285 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10286 // 1 and that the SETCC node has a single use.
10287 static bool isXor1OfSetCC(SDValue Op) {
10288   if (Op.getOpcode() != ISD::XOR)
10289     return false;
10290   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10291   if (N1C && N1C->getAPIntValue() == 1) {
10292     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10293       Op.getOperand(0).hasOneUse();
10294   }
10295   return false;
10296 }
10297
10298 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10299   bool addTest = true;
10300   SDValue Chain = Op.getOperand(0);
10301   SDValue Cond  = Op.getOperand(1);
10302   SDValue Dest  = Op.getOperand(2);
10303   SDLoc dl(Op);
10304   SDValue CC;
10305   bool Inverted = false;
10306
10307   if (Cond.getOpcode() == ISD::SETCC) {
10308     // Check for setcc([su]{add,sub,mul}o == 0).
10309     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10310         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10311         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10312         Cond.getOperand(0).getResNo() == 1 &&
10313         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10314          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10315          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10316          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10317          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10318          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10319       Inverted = true;
10320       Cond = Cond.getOperand(0);
10321     } else {
10322       SDValue NewCond = LowerSETCC(Cond, DAG);
10323       if (NewCond.getNode())
10324         Cond = NewCond;
10325     }
10326   }
10327 #if 0
10328   // FIXME: LowerXALUO doesn't handle these!!
10329   else if (Cond.getOpcode() == X86ISD::ADD  ||
10330            Cond.getOpcode() == X86ISD::SUB  ||
10331            Cond.getOpcode() == X86ISD::SMUL ||
10332            Cond.getOpcode() == X86ISD::UMUL)
10333     Cond = LowerXALUO(Cond, DAG);
10334 #endif
10335
10336   // Look pass (and (setcc_carry (cmp ...)), 1).
10337   if (Cond.getOpcode() == ISD::AND &&
10338       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10339     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10340     if (C && C->getAPIntValue() == 1)
10341       Cond = Cond.getOperand(0);
10342   }
10343
10344   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10345   // setting operand in place of the X86ISD::SETCC.
10346   unsigned CondOpcode = Cond.getOpcode();
10347   if (CondOpcode == X86ISD::SETCC ||
10348       CondOpcode == X86ISD::SETCC_CARRY) {
10349     CC = Cond.getOperand(0);
10350
10351     SDValue Cmp = Cond.getOperand(1);
10352     unsigned Opc = Cmp.getOpcode();
10353     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10354     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10355       Cond = Cmp;
10356       addTest = false;
10357     } else {
10358       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10359       default: break;
10360       case X86::COND_O:
10361       case X86::COND_B:
10362         // These can only come from an arithmetic instruction with overflow,
10363         // e.g. SADDO, UADDO.
10364         Cond = Cond.getNode()->getOperand(1);
10365         addTest = false;
10366         break;
10367       }
10368     }
10369   }
10370   CondOpcode = Cond.getOpcode();
10371   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10372       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10373       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10374        Cond.getOperand(0).getValueType() != MVT::i8)) {
10375     SDValue LHS = Cond.getOperand(0);
10376     SDValue RHS = Cond.getOperand(1);
10377     unsigned X86Opcode;
10378     unsigned X86Cond;
10379     SDVTList VTs;
10380     switch (CondOpcode) {
10381     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10382     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10383     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10384     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10385     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10386     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10387     default: llvm_unreachable("unexpected overflowing operator");
10388     }
10389     if (Inverted)
10390       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10391     if (CondOpcode == ISD::UMULO)
10392       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10393                           MVT::i32);
10394     else
10395       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10396
10397     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10398
10399     if (CondOpcode == ISD::UMULO)
10400       Cond = X86Op.getValue(2);
10401     else
10402       Cond = X86Op.getValue(1);
10403
10404     CC = DAG.getConstant(X86Cond, MVT::i8);
10405     addTest = false;
10406   } else {
10407     unsigned CondOpc;
10408     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10409       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10410       if (CondOpc == ISD::OR) {
10411         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10412         // two branches instead of an explicit OR instruction with a
10413         // separate test.
10414         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10415             isX86LogicalCmp(Cmp)) {
10416           CC = Cond.getOperand(0).getOperand(0);
10417           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10418                               Chain, Dest, CC, Cmp);
10419           CC = Cond.getOperand(1).getOperand(0);
10420           Cond = Cmp;
10421           addTest = false;
10422         }
10423       } else { // ISD::AND
10424         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10425         // two branches instead of an explicit AND instruction with a
10426         // separate test. However, we only do this if this block doesn't
10427         // have a fall-through edge, because this requires an explicit
10428         // jmp when the condition is false.
10429         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10430             isX86LogicalCmp(Cmp) &&
10431             Op.getNode()->hasOneUse()) {
10432           X86::CondCode CCode =
10433             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10434           CCode = X86::GetOppositeBranchCondition(CCode);
10435           CC = DAG.getConstant(CCode, MVT::i8);
10436           SDNode *User = *Op.getNode()->use_begin();
10437           // Look for an unconditional branch following this conditional branch.
10438           // We need this because we need to reverse the successors in order
10439           // to implement FCMP_OEQ.
10440           if (User->getOpcode() == ISD::BR) {
10441             SDValue FalseBB = User->getOperand(1);
10442             SDNode *NewBR =
10443               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10444             assert(NewBR == User);
10445             (void)NewBR;
10446             Dest = FalseBB;
10447
10448             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10449                                 Chain, Dest, CC, Cmp);
10450             X86::CondCode CCode =
10451               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10452             CCode = X86::GetOppositeBranchCondition(CCode);
10453             CC = DAG.getConstant(CCode, MVT::i8);
10454             Cond = Cmp;
10455             addTest = false;
10456           }
10457         }
10458       }
10459     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10460       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10461       // It should be transformed during dag combiner except when the condition
10462       // is set by a arithmetics with overflow node.
10463       X86::CondCode CCode =
10464         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10465       CCode = X86::GetOppositeBranchCondition(CCode);
10466       CC = DAG.getConstant(CCode, MVT::i8);
10467       Cond = Cond.getOperand(0).getOperand(1);
10468       addTest = false;
10469     } else if (Cond.getOpcode() == ISD::SETCC &&
10470                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10471       // For FCMP_OEQ, we can emit
10472       // two branches instead of an explicit AND instruction with a
10473       // separate test. However, we only do this if this block doesn't
10474       // have a fall-through edge, because this requires an explicit
10475       // jmp when the condition is false.
10476       if (Op.getNode()->hasOneUse()) {
10477         SDNode *User = *Op.getNode()->use_begin();
10478         // Look for an unconditional branch following this conditional branch.
10479         // We need this because we need to reverse the successors in order
10480         // to implement FCMP_OEQ.
10481         if (User->getOpcode() == ISD::BR) {
10482           SDValue FalseBB = User->getOperand(1);
10483           SDNode *NewBR =
10484             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10485           assert(NewBR == User);
10486           (void)NewBR;
10487           Dest = FalseBB;
10488
10489           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10490                                     Cond.getOperand(0), Cond.getOperand(1));
10491           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10492           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10493           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10494                               Chain, Dest, CC, Cmp);
10495           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10496           Cond = Cmp;
10497           addTest = false;
10498         }
10499       }
10500     } else if (Cond.getOpcode() == ISD::SETCC &&
10501                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10502       // For FCMP_UNE, we can emit
10503       // two branches instead of an explicit AND instruction with a
10504       // separate test. However, we only do this if this block doesn't
10505       // have a fall-through edge, because this requires an explicit
10506       // jmp when the condition is false.
10507       if (Op.getNode()->hasOneUse()) {
10508         SDNode *User = *Op.getNode()->use_begin();
10509         // Look for an unconditional branch following this conditional branch.
10510         // We need this because we need to reverse the successors in order
10511         // to implement FCMP_UNE.
10512         if (User->getOpcode() == ISD::BR) {
10513           SDValue FalseBB = User->getOperand(1);
10514           SDNode *NewBR =
10515             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10516           assert(NewBR == User);
10517           (void)NewBR;
10518
10519           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10520                                     Cond.getOperand(0), Cond.getOperand(1));
10521           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10522           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10523           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10524                               Chain, Dest, CC, Cmp);
10525           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10526           Cond = Cmp;
10527           addTest = false;
10528           Dest = FalseBB;
10529         }
10530       }
10531     }
10532   }
10533
10534   if (addTest) {
10535     // Look pass the truncate if the high bits are known zero.
10536     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10537         Cond = Cond.getOperand(0);
10538
10539     // We know the result of AND is compared against zero. Try to match
10540     // it to BT.
10541     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10542       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10543       if (NewSetCC.getNode()) {
10544         CC = NewSetCC.getOperand(0);
10545         Cond = NewSetCC.getOperand(1);
10546         addTest = false;
10547       }
10548     }
10549   }
10550
10551   if (addTest) {
10552     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10553     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10554   }
10555   Cond = ConvertCmpIfNecessary(Cond, DAG);
10556   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10557                      Chain, Dest, CC, Cond);
10558 }
10559
10560 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10561 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10562 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10563 // that the guard pages used by the OS virtual memory manager are allocated in
10564 // correct sequence.
10565 SDValue
10566 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10567                                            SelectionDAG &DAG) const {
10568   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10569           getTargetMachine().Options.EnableSegmentedStacks) &&
10570          "This should be used only on Windows targets or when segmented stacks "
10571          "are being used");
10572   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10573   SDLoc dl(Op);
10574
10575   // Get the inputs.
10576   SDValue Chain = Op.getOperand(0);
10577   SDValue Size  = Op.getOperand(1);
10578   // FIXME: Ensure alignment here
10579
10580   bool Is64Bit = Subtarget->is64Bit();
10581   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10582
10583   if (getTargetMachine().Options.EnableSegmentedStacks) {
10584     MachineFunction &MF = DAG.getMachineFunction();
10585     MachineRegisterInfo &MRI = MF.getRegInfo();
10586
10587     if (Is64Bit) {
10588       // The 64 bit implementation of segmented stacks needs to clobber both r10
10589       // r11. This makes it impossible to use it along with nested parameters.
10590       const Function *F = MF.getFunction();
10591
10592       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10593            I != E; ++I)
10594         if (I->hasNestAttr())
10595           report_fatal_error("Cannot use segmented stacks with functions that "
10596                              "have nested arguments.");
10597     }
10598
10599     const TargetRegisterClass *AddrRegClass =
10600       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10601     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10602     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10603     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10604                                 DAG.getRegister(Vreg, SPTy));
10605     SDValue Ops1[2] = { Value, Chain };
10606     return DAG.getMergeValues(Ops1, 2, dl);
10607   } else {
10608     SDValue Flag;
10609     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10610
10611     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10612     Flag = Chain.getValue(1);
10613     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10614
10615     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10616     Flag = Chain.getValue(1);
10617
10618     const X86RegisterInfo *RegInfo =
10619       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10620     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10621                                SPTy).getValue(1);
10622
10623     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10624     return DAG.getMergeValues(Ops1, 2, dl);
10625   }
10626 }
10627
10628 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10629   MachineFunction &MF = DAG.getMachineFunction();
10630   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10631
10632   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10633   SDLoc DL(Op);
10634
10635   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10636     // vastart just stores the address of the VarArgsFrameIndex slot into the
10637     // memory location argument.
10638     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10639                                    getPointerTy());
10640     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10641                         MachinePointerInfo(SV), false, false, 0);
10642   }
10643
10644   // __va_list_tag:
10645   //   gp_offset         (0 - 6 * 8)
10646   //   fp_offset         (48 - 48 + 8 * 16)
10647   //   overflow_arg_area (point to parameters coming in memory).
10648   //   reg_save_area
10649   SmallVector<SDValue, 8> MemOps;
10650   SDValue FIN = Op.getOperand(1);
10651   // Store gp_offset
10652   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10653                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10654                                                MVT::i32),
10655                                FIN, MachinePointerInfo(SV), false, false, 0);
10656   MemOps.push_back(Store);
10657
10658   // Store fp_offset
10659   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10660                     FIN, DAG.getIntPtrConstant(4));
10661   Store = DAG.getStore(Op.getOperand(0), DL,
10662                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10663                                        MVT::i32),
10664                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10665   MemOps.push_back(Store);
10666
10667   // Store ptr to overflow_arg_area
10668   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10669                     FIN, DAG.getIntPtrConstant(4));
10670   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10671                                     getPointerTy());
10672   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10673                        MachinePointerInfo(SV, 8),
10674                        false, false, 0);
10675   MemOps.push_back(Store);
10676
10677   // Store ptr to reg_save_area.
10678   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10679                     FIN, DAG.getIntPtrConstant(8));
10680   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10681                                     getPointerTy());
10682   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10683                        MachinePointerInfo(SV, 16), false, false, 0);
10684   MemOps.push_back(Store);
10685   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10686                      &MemOps[0], MemOps.size());
10687 }
10688
10689 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10690   assert(Subtarget->is64Bit() &&
10691          "LowerVAARG only handles 64-bit va_arg!");
10692   assert((Subtarget->isTargetLinux() ||
10693           Subtarget->isTargetDarwin()) &&
10694           "Unhandled target in LowerVAARG");
10695   assert(Op.getNode()->getNumOperands() == 4);
10696   SDValue Chain = Op.getOperand(0);
10697   SDValue SrcPtr = Op.getOperand(1);
10698   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10699   unsigned Align = Op.getConstantOperandVal(3);
10700   SDLoc dl(Op);
10701
10702   EVT ArgVT = Op.getNode()->getValueType(0);
10703   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10704   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10705   uint8_t ArgMode;
10706
10707   // Decide which area this value should be read from.
10708   // TODO: Implement the AMD64 ABI in its entirety. This simple
10709   // selection mechanism works only for the basic types.
10710   if (ArgVT == MVT::f80) {
10711     llvm_unreachable("va_arg for f80 not yet implemented");
10712   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10713     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10714   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10715     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10716   } else {
10717     llvm_unreachable("Unhandled argument type in LowerVAARG");
10718   }
10719
10720   if (ArgMode == 2) {
10721     // Sanity Check: Make sure using fp_offset makes sense.
10722     assert(!getTargetMachine().Options.UseSoftFloat &&
10723            !(DAG.getMachineFunction()
10724                 .getFunction()->getAttributes()
10725                 .hasAttribute(AttributeSet::FunctionIndex,
10726                               Attribute::NoImplicitFloat)) &&
10727            Subtarget->hasSSE1());
10728   }
10729
10730   // Insert VAARG_64 node into the DAG
10731   // VAARG_64 returns two values: Variable Argument Address, Chain
10732   SmallVector<SDValue, 11> InstOps;
10733   InstOps.push_back(Chain);
10734   InstOps.push_back(SrcPtr);
10735   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10736   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10737   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10738   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10739   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10740                                           VTs, &InstOps[0], InstOps.size(),
10741                                           MVT::i64,
10742                                           MachinePointerInfo(SV),
10743                                           /*Align=*/0,
10744                                           /*Volatile=*/false,
10745                                           /*ReadMem=*/true,
10746                                           /*WriteMem=*/true);
10747   Chain = VAARG.getValue(1);
10748
10749   // Load the next argument and return it
10750   return DAG.getLoad(ArgVT, dl,
10751                      Chain,
10752                      VAARG,
10753                      MachinePointerInfo(),
10754                      false, false, false, 0);
10755 }
10756
10757 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10758                            SelectionDAG &DAG) {
10759   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10760   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10761   SDValue Chain = Op.getOperand(0);
10762   SDValue DstPtr = Op.getOperand(1);
10763   SDValue SrcPtr = Op.getOperand(2);
10764   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10765   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10766   SDLoc DL(Op);
10767
10768   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10769                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10770                        false,
10771                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10772 }
10773
10774 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10775 // may or may not be a constant. Takes immediate version of shift as input.
10776 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10777                                    SDValue SrcOp, SDValue ShAmt,
10778                                    SelectionDAG &DAG) {
10779   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10780
10781   if (isa<ConstantSDNode>(ShAmt)) {
10782     // Constant may be a TargetConstant. Use a regular constant.
10783     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10784     switch (Opc) {
10785       default: llvm_unreachable("Unknown target vector shift node");
10786       case X86ISD::VSHLI:
10787       case X86ISD::VSRLI:
10788       case X86ISD::VSRAI:
10789         return DAG.getNode(Opc, dl, VT, SrcOp,
10790                            DAG.getConstant(ShiftAmt, MVT::i32));
10791     }
10792   }
10793
10794   // Change opcode to non-immediate version
10795   switch (Opc) {
10796     default: llvm_unreachable("Unknown target vector shift node");
10797     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10798     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10799     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10800   }
10801
10802   // Need to build a vector containing shift amount
10803   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10804   SDValue ShOps[4];
10805   ShOps[0] = ShAmt;
10806   ShOps[1] = DAG.getConstant(0, MVT::i32);
10807   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10808   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10809
10810   // The return type has to be a 128-bit type with the same element
10811   // type as the input type.
10812   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10813   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10814
10815   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10816   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10817 }
10818
10819 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10820   SDLoc dl(Op);
10821   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10822   switch (IntNo) {
10823   default: return SDValue();    // Don't custom lower most intrinsics.
10824   // Comparison intrinsics.
10825   case Intrinsic::x86_sse_comieq_ss:
10826   case Intrinsic::x86_sse_comilt_ss:
10827   case Intrinsic::x86_sse_comile_ss:
10828   case Intrinsic::x86_sse_comigt_ss:
10829   case Intrinsic::x86_sse_comige_ss:
10830   case Intrinsic::x86_sse_comineq_ss:
10831   case Intrinsic::x86_sse_ucomieq_ss:
10832   case Intrinsic::x86_sse_ucomilt_ss:
10833   case Intrinsic::x86_sse_ucomile_ss:
10834   case Intrinsic::x86_sse_ucomigt_ss:
10835   case Intrinsic::x86_sse_ucomige_ss:
10836   case Intrinsic::x86_sse_ucomineq_ss:
10837   case Intrinsic::x86_sse2_comieq_sd:
10838   case Intrinsic::x86_sse2_comilt_sd:
10839   case Intrinsic::x86_sse2_comile_sd:
10840   case Intrinsic::x86_sse2_comigt_sd:
10841   case Intrinsic::x86_sse2_comige_sd:
10842   case Intrinsic::x86_sse2_comineq_sd:
10843   case Intrinsic::x86_sse2_ucomieq_sd:
10844   case Intrinsic::x86_sse2_ucomilt_sd:
10845   case Intrinsic::x86_sse2_ucomile_sd:
10846   case Intrinsic::x86_sse2_ucomigt_sd:
10847   case Intrinsic::x86_sse2_ucomige_sd:
10848   case Intrinsic::x86_sse2_ucomineq_sd: {
10849     unsigned Opc;
10850     ISD::CondCode CC;
10851     switch (IntNo) {
10852     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10853     case Intrinsic::x86_sse_comieq_ss:
10854     case Intrinsic::x86_sse2_comieq_sd:
10855       Opc = X86ISD::COMI;
10856       CC = ISD::SETEQ;
10857       break;
10858     case Intrinsic::x86_sse_comilt_ss:
10859     case Intrinsic::x86_sse2_comilt_sd:
10860       Opc = X86ISD::COMI;
10861       CC = ISD::SETLT;
10862       break;
10863     case Intrinsic::x86_sse_comile_ss:
10864     case Intrinsic::x86_sse2_comile_sd:
10865       Opc = X86ISD::COMI;
10866       CC = ISD::SETLE;
10867       break;
10868     case Intrinsic::x86_sse_comigt_ss:
10869     case Intrinsic::x86_sse2_comigt_sd:
10870       Opc = X86ISD::COMI;
10871       CC = ISD::SETGT;
10872       break;
10873     case Intrinsic::x86_sse_comige_ss:
10874     case Intrinsic::x86_sse2_comige_sd:
10875       Opc = X86ISD::COMI;
10876       CC = ISD::SETGE;
10877       break;
10878     case Intrinsic::x86_sse_comineq_ss:
10879     case Intrinsic::x86_sse2_comineq_sd:
10880       Opc = X86ISD::COMI;
10881       CC = ISD::SETNE;
10882       break;
10883     case Intrinsic::x86_sse_ucomieq_ss:
10884     case Intrinsic::x86_sse2_ucomieq_sd:
10885       Opc = X86ISD::UCOMI;
10886       CC = ISD::SETEQ;
10887       break;
10888     case Intrinsic::x86_sse_ucomilt_ss:
10889     case Intrinsic::x86_sse2_ucomilt_sd:
10890       Opc = X86ISD::UCOMI;
10891       CC = ISD::SETLT;
10892       break;
10893     case Intrinsic::x86_sse_ucomile_ss:
10894     case Intrinsic::x86_sse2_ucomile_sd:
10895       Opc = X86ISD::UCOMI;
10896       CC = ISD::SETLE;
10897       break;
10898     case Intrinsic::x86_sse_ucomigt_ss:
10899     case Intrinsic::x86_sse2_ucomigt_sd:
10900       Opc = X86ISD::UCOMI;
10901       CC = ISD::SETGT;
10902       break;
10903     case Intrinsic::x86_sse_ucomige_ss:
10904     case Intrinsic::x86_sse2_ucomige_sd:
10905       Opc = X86ISD::UCOMI;
10906       CC = ISD::SETGE;
10907       break;
10908     case Intrinsic::x86_sse_ucomineq_ss:
10909     case Intrinsic::x86_sse2_ucomineq_sd:
10910       Opc = X86ISD::UCOMI;
10911       CC = ISD::SETNE;
10912       break;
10913     }
10914
10915     SDValue LHS = Op.getOperand(1);
10916     SDValue RHS = Op.getOperand(2);
10917     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10918     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10919     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10920     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10921                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10922     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10923   }
10924
10925   // Arithmetic intrinsics.
10926   case Intrinsic::x86_sse2_pmulu_dq:
10927   case Intrinsic::x86_avx2_pmulu_dq:
10928     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10929                        Op.getOperand(1), Op.getOperand(2));
10930
10931   // SSE2/AVX2 sub with unsigned saturation intrinsics
10932   case Intrinsic::x86_sse2_psubus_b:
10933   case Intrinsic::x86_sse2_psubus_w:
10934   case Intrinsic::x86_avx2_psubus_b:
10935   case Intrinsic::x86_avx2_psubus_w:
10936     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10937                        Op.getOperand(1), Op.getOperand(2));
10938
10939   // SSE3/AVX horizontal add/sub intrinsics
10940   case Intrinsic::x86_sse3_hadd_ps:
10941   case Intrinsic::x86_sse3_hadd_pd:
10942   case Intrinsic::x86_avx_hadd_ps_256:
10943   case Intrinsic::x86_avx_hadd_pd_256:
10944   case Intrinsic::x86_sse3_hsub_ps:
10945   case Intrinsic::x86_sse3_hsub_pd:
10946   case Intrinsic::x86_avx_hsub_ps_256:
10947   case Intrinsic::x86_avx_hsub_pd_256:
10948   case Intrinsic::x86_ssse3_phadd_w_128:
10949   case Intrinsic::x86_ssse3_phadd_d_128:
10950   case Intrinsic::x86_avx2_phadd_w:
10951   case Intrinsic::x86_avx2_phadd_d:
10952   case Intrinsic::x86_ssse3_phsub_w_128:
10953   case Intrinsic::x86_ssse3_phsub_d_128:
10954   case Intrinsic::x86_avx2_phsub_w:
10955   case Intrinsic::x86_avx2_phsub_d: {
10956     unsigned Opcode;
10957     switch (IntNo) {
10958     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10959     case Intrinsic::x86_sse3_hadd_ps:
10960     case Intrinsic::x86_sse3_hadd_pd:
10961     case Intrinsic::x86_avx_hadd_ps_256:
10962     case Intrinsic::x86_avx_hadd_pd_256:
10963       Opcode = X86ISD::FHADD;
10964       break;
10965     case Intrinsic::x86_sse3_hsub_ps:
10966     case Intrinsic::x86_sse3_hsub_pd:
10967     case Intrinsic::x86_avx_hsub_ps_256:
10968     case Intrinsic::x86_avx_hsub_pd_256:
10969       Opcode = X86ISD::FHSUB;
10970       break;
10971     case Intrinsic::x86_ssse3_phadd_w_128:
10972     case Intrinsic::x86_ssse3_phadd_d_128:
10973     case Intrinsic::x86_avx2_phadd_w:
10974     case Intrinsic::x86_avx2_phadd_d:
10975       Opcode = X86ISD::HADD;
10976       break;
10977     case Intrinsic::x86_ssse3_phsub_w_128:
10978     case Intrinsic::x86_ssse3_phsub_d_128:
10979     case Intrinsic::x86_avx2_phsub_w:
10980     case Intrinsic::x86_avx2_phsub_d:
10981       Opcode = X86ISD::HSUB;
10982       break;
10983     }
10984     return DAG.getNode(Opcode, dl, Op.getValueType(),
10985                        Op.getOperand(1), Op.getOperand(2));
10986   }
10987
10988   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10989   case Intrinsic::x86_sse2_pmaxu_b:
10990   case Intrinsic::x86_sse41_pmaxuw:
10991   case Intrinsic::x86_sse41_pmaxud:
10992   case Intrinsic::x86_avx2_pmaxu_b:
10993   case Intrinsic::x86_avx2_pmaxu_w:
10994   case Intrinsic::x86_avx2_pmaxu_d:
10995   case Intrinsic::x86_sse2_pminu_b:
10996   case Intrinsic::x86_sse41_pminuw:
10997   case Intrinsic::x86_sse41_pminud:
10998   case Intrinsic::x86_avx2_pminu_b:
10999   case Intrinsic::x86_avx2_pminu_w:
11000   case Intrinsic::x86_avx2_pminu_d:
11001   case Intrinsic::x86_sse41_pmaxsb:
11002   case Intrinsic::x86_sse2_pmaxs_w:
11003   case Intrinsic::x86_sse41_pmaxsd:
11004   case Intrinsic::x86_avx2_pmaxs_b:
11005   case Intrinsic::x86_avx2_pmaxs_w:
11006   case Intrinsic::x86_avx2_pmaxs_d:
11007   case Intrinsic::x86_sse41_pminsb:
11008   case Intrinsic::x86_sse2_pmins_w:
11009   case Intrinsic::x86_sse41_pminsd:
11010   case Intrinsic::x86_avx2_pmins_b:
11011   case Intrinsic::x86_avx2_pmins_w:
11012   case Intrinsic::x86_avx2_pmins_d: {
11013     unsigned Opcode;
11014     switch (IntNo) {
11015     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11016     case Intrinsic::x86_sse2_pmaxu_b:
11017     case Intrinsic::x86_sse41_pmaxuw:
11018     case Intrinsic::x86_sse41_pmaxud:
11019     case Intrinsic::x86_avx2_pmaxu_b:
11020     case Intrinsic::x86_avx2_pmaxu_w:
11021     case Intrinsic::x86_avx2_pmaxu_d:
11022       Opcode = X86ISD::UMAX;
11023       break;
11024     case Intrinsic::x86_sse2_pminu_b:
11025     case Intrinsic::x86_sse41_pminuw:
11026     case Intrinsic::x86_sse41_pminud:
11027     case Intrinsic::x86_avx2_pminu_b:
11028     case Intrinsic::x86_avx2_pminu_w:
11029     case Intrinsic::x86_avx2_pminu_d:
11030       Opcode = X86ISD::UMIN;
11031       break;
11032     case Intrinsic::x86_sse41_pmaxsb:
11033     case Intrinsic::x86_sse2_pmaxs_w:
11034     case Intrinsic::x86_sse41_pmaxsd:
11035     case Intrinsic::x86_avx2_pmaxs_b:
11036     case Intrinsic::x86_avx2_pmaxs_w:
11037     case Intrinsic::x86_avx2_pmaxs_d:
11038       Opcode = X86ISD::SMAX;
11039       break;
11040     case Intrinsic::x86_sse41_pminsb:
11041     case Intrinsic::x86_sse2_pmins_w:
11042     case Intrinsic::x86_sse41_pminsd:
11043     case Intrinsic::x86_avx2_pmins_b:
11044     case Intrinsic::x86_avx2_pmins_w:
11045     case Intrinsic::x86_avx2_pmins_d:
11046       Opcode = X86ISD::SMIN;
11047       break;
11048     }
11049     return DAG.getNode(Opcode, dl, Op.getValueType(),
11050                        Op.getOperand(1), Op.getOperand(2));
11051   }
11052
11053   // SSE/SSE2/AVX floating point max/min intrinsics.
11054   case Intrinsic::x86_sse_max_ps:
11055   case Intrinsic::x86_sse2_max_pd:
11056   case Intrinsic::x86_avx_max_ps_256:
11057   case Intrinsic::x86_avx_max_pd_256:
11058   case Intrinsic::x86_sse_min_ps:
11059   case Intrinsic::x86_sse2_min_pd:
11060   case Intrinsic::x86_avx_min_ps_256:
11061   case Intrinsic::x86_avx_min_pd_256: {
11062     unsigned Opcode;
11063     switch (IntNo) {
11064     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11065     case Intrinsic::x86_sse_max_ps:
11066     case Intrinsic::x86_sse2_max_pd:
11067     case Intrinsic::x86_avx_max_ps_256:
11068     case Intrinsic::x86_avx_max_pd_256:
11069       Opcode = X86ISD::FMAX;
11070       break;
11071     case Intrinsic::x86_sse_min_ps:
11072     case Intrinsic::x86_sse2_min_pd:
11073     case Intrinsic::x86_avx_min_ps_256:
11074     case Intrinsic::x86_avx_min_pd_256:
11075       Opcode = X86ISD::FMIN;
11076       break;
11077     }
11078     return DAG.getNode(Opcode, dl, Op.getValueType(),
11079                        Op.getOperand(1), Op.getOperand(2));
11080   }
11081
11082   // AVX2 variable shift intrinsics
11083   case Intrinsic::x86_avx2_psllv_d:
11084   case Intrinsic::x86_avx2_psllv_q:
11085   case Intrinsic::x86_avx2_psllv_d_256:
11086   case Intrinsic::x86_avx2_psllv_q_256:
11087   case Intrinsic::x86_avx2_psrlv_d:
11088   case Intrinsic::x86_avx2_psrlv_q:
11089   case Intrinsic::x86_avx2_psrlv_d_256:
11090   case Intrinsic::x86_avx2_psrlv_q_256:
11091   case Intrinsic::x86_avx2_psrav_d:
11092   case Intrinsic::x86_avx2_psrav_d_256: {
11093     unsigned Opcode;
11094     switch (IntNo) {
11095     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11096     case Intrinsic::x86_avx2_psllv_d:
11097     case Intrinsic::x86_avx2_psllv_q:
11098     case Intrinsic::x86_avx2_psllv_d_256:
11099     case Intrinsic::x86_avx2_psllv_q_256:
11100       Opcode = ISD::SHL;
11101       break;
11102     case Intrinsic::x86_avx2_psrlv_d:
11103     case Intrinsic::x86_avx2_psrlv_q:
11104     case Intrinsic::x86_avx2_psrlv_d_256:
11105     case Intrinsic::x86_avx2_psrlv_q_256:
11106       Opcode = ISD::SRL;
11107       break;
11108     case Intrinsic::x86_avx2_psrav_d:
11109     case Intrinsic::x86_avx2_psrav_d_256:
11110       Opcode = ISD::SRA;
11111       break;
11112     }
11113     return DAG.getNode(Opcode, dl, Op.getValueType(),
11114                        Op.getOperand(1), Op.getOperand(2));
11115   }
11116
11117   case Intrinsic::x86_ssse3_pshuf_b_128:
11118   case Intrinsic::x86_avx2_pshuf_b:
11119     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11120                        Op.getOperand(1), Op.getOperand(2));
11121
11122   case Intrinsic::x86_ssse3_psign_b_128:
11123   case Intrinsic::x86_ssse3_psign_w_128:
11124   case Intrinsic::x86_ssse3_psign_d_128:
11125   case Intrinsic::x86_avx2_psign_b:
11126   case Intrinsic::x86_avx2_psign_w:
11127   case Intrinsic::x86_avx2_psign_d:
11128     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11129                        Op.getOperand(1), Op.getOperand(2));
11130
11131   case Intrinsic::x86_sse41_insertps:
11132     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11133                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11134
11135   case Intrinsic::x86_avx_vperm2f128_ps_256:
11136   case Intrinsic::x86_avx_vperm2f128_pd_256:
11137   case Intrinsic::x86_avx_vperm2f128_si_256:
11138   case Intrinsic::x86_avx2_vperm2i128:
11139     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11140                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11141
11142   case Intrinsic::x86_avx2_permd:
11143   case Intrinsic::x86_avx2_permps:
11144     // Operands intentionally swapped. Mask is last operand to intrinsic,
11145     // but second operand for node/intruction.
11146     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11147                        Op.getOperand(2), Op.getOperand(1));
11148
11149   case Intrinsic::x86_sse_sqrt_ps:
11150   case Intrinsic::x86_sse2_sqrt_pd:
11151   case Intrinsic::x86_avx_sqrt_ps_256:
11152   case Intrinsic::x86_avx_sqrt_pd_256:
11153     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11154
11155   // ptest and testp intrinsics. The intrinsic these come from are designed to
11156   // return an integer value, not just an instruction so lower it to the ptest
11157   // or testp pattern and a setcc for the result.
11158   case Intrinsic::x86_sse41_ptestz:
11159   case Intrinsic::x86_sse41_ptestc:
11160   case Intrinsic::x86_sse41_ptestnzc:
11161   case Intrinsic::x86_avx_ptestz_256:
11162   case Intrinsic::x86_avx_ptestc_256:
11163   case Intrinsic::x86_avx_ptestnzc_256:
11164   case Intrinsic::x86_avx_vtestz_ps:
11165   case Intrinsic::x86_avx_vtestc_ps:
11166   case Intrinsic::x86_avx_vtestnzc_ps:
11167   case Intrinsic::x86_avx_vtestz_pd:
11168   case Intrinsic::x86_avx_vtestc_pd:
11169   case Intrinsic::x86_avx_vtestnzc_pd:
11170   case Intrinsic::x86_avx_vtestz_ps_256:
11171   case Intrinsic::x86_avx_vtestc_ps_256:
11172   case Intrinsic::x86_avx_vtestnzc_ps_256:
11173   case Intrinsic::x86_avx_vtestz_pd_256:
11174   case Intrinsic::x86_avx_vtestc_pd_256:
11175   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11176     bool IsTestPacked = false;
11177     unsigned X86CC;
11178     switch (IntNo) {
11179     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11180     case Intrinsic::x86_avx_vtestz_ps:
11181     case Intrinsic::x86_avx_vtestz_pd:
11182     case Intrinsic::x86_avx_vtestz_ps_256:
11183     case Intrinsic::x86_avx_vtestz_pd_256:
11184       IsTestPacked = true; // Fallthrough
11185     case Intrinsic::x86_sse41_ptestz:
11186     case Intrinsic::x86_avx_ptestz_256:
11187       // ZF = 1
11188       X86CC = X86::COND_E;
11189       break;
11190     case Intrinsic::x86_avx_vtestc_ps:
11191     case Intrinsic::x86_avx_vtestc_pd:
11192     case Intrinsic::x86_avx_vtestc_ps_256:
11193     case Intrinsic::x86_avx_vtestc_pd_256:
11194       IsTestPacked = true; // Fallthrough
11195     case Intrinsic::x86_sse41_ptestc:
11196     case Intrinsic::x86_avx_ptestc_256:
11197       // CF = 1
11198       X86CC = X86::COND_B;
11199       break;
11200     case Intrinsic::x86_avx_vtestnzc_ps:
11201     case Intrinsic::x86_avx_vtestnzc_pd:
11202     case Intrinsic::x86_avx_vtestnzc_ps_256:
11203     case Intrinsic::x86_avx_vtestnzc_pd_256:
11204       IsTestPacked = true; // Fallthrough
11205     case Intrinsic::x86_sse41_ptestnzc:
11206     case Intrinsic::x86_avx_ptestnzc_256:
11207       // ZF and CF = 0
11208       X86CC = X86::COND_A;
11209       break;
11210     }
11211
11212     SDValue LHS = Op.getOperand(1);
11213     SDValue RHS = Op.getOperand(2);
11214     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11215     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11216     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11217     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11218     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11219   }
11220
11221   // SSE/AVX shift intrinsics
11222   case Intrinsic::x86_sse2_psll_w:
11223   case Intrinsic::x86_sse2_psll_d:
11224   case Intrinsic::x86_sse2_psll_q:
11225   case Intrinsic::x86_avx2_psll_w:
11226   case Intrinsic::x86_avx2_psll_d:
11227   case Intrinsic::x86_avx2_psll_q:
11228   case Intrinsic::x86_sse2_psrl_w:
11229   case Intrinsic::x86_sse2_psrl_d:
11230   case Intrinsic::x86_sse2_psrl_q:
11231   case Intrinsic::x86_avx2_psrl_w:
11232   case Intrinsic::x86_avx2_psrl_d:
11233   case Intrinsic::x86_avx2_psrl_q:
11234   case Intrinsic::x86_sse2_psra_w:
11235   case Intrinsic::x86_sse2_psra_d:
11236   case Intrinsic::x86_avx2_psra_w:
11237   case Intrinsic::x86_avx2_psra_d: {
11238     unsigned Opcode;
11239     switch (IntNo) {
11240     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11241     case Intrinsic::x86_sse2_psll_w:
11242     case Intrinsic::x86_sse2_psll_d:
11243     case Intrinsic::x86_sse2_psll_q:
11244     case Intrinsic::x86_avx2_psll_w:
11245     case Intrinsic::x86_avx2_psll_d:
11246     case Intrinsic::x86_avx2_psll_q:
11247       Opcode = X86ISD::VSHL;
11248       break;
11249     case Intrinsic::x86_sse2_psrl_w:
11250     case Intrinsic::x86_sse2_psrl_d:
11251     case Intrinsic::x86_sse2_psrl_q:
11252     case Intrinsic::x86_avx2_psrl_w:
11253     case Intrinsic::x86_avx2_psrl_d:
11254     case Intrinsic::x86_avx2_psrl_q:
11255       Opcode = X86ISD::VSRL;
11256       break;
11257     case Intrinsic::x86_sse2_psra_w:
11258     case Intrinsic::x86_sse2_psra_d:
11259     case Intrinsic::x86_avx2_psra_w:
11260     case Intrinsic::x86_avx2_psra_d:
11261       Opcode = X86ISD::VSRA;
11262       break;
11263     }
11264     return DAG.getNode(Opcode, dl, Op.getValueType(),
11265                        Op.getOperand(1), Op.getOperand(2));
11266   }
11267
11268   // SSE/AVX immediate shift intrinsics
11269   case Intrinsic::x86_sse2_pslli_w:
11270   case Intrinsic::x86_sse2_pslli_d:
11271   case Intrinsic::x86_sse2_pslli_q:
11272   case Intrinsic::x86_avx2_pslli_w:
11273   case Intrinsic::x86_avx2_pslli_d:
11274   case Intrinsic::x86_avx2_pslli_q:
11275   case Intrinsic::x86_sse2_psrli_w:
11276   case Intrinsic::x86_sse2_psrli_d:
11277   case Intrinsic::x86_sse2_psrli_q:
11278   case Intrinsic::x86_avx2_psrli_w:
11279   case Intrinsic::x86_avx2_psrli_d:
11280   case Intrinsic::x86_avx2_psrli_q:
11281   case Intrinsic::x86_sse2_psrai_w:
11282   case Intrinsic::x86_sse2_psrai_d:
11283   case Intrinsic::x86_avx2_psrai_w:
11284   case Intrinsic::x86_avx2_psrai_d: {
11285     unsigned Opcode;
11286     switch (IntNo) {
11287     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11288     case Intrinsic::x86_sse2_pslli_w:
11289     case Intrinsic::x86_sse2_pslli_d:
11290     case Intrinsic::x86_sse2_pslli_q:
11291     case Intrinsic::x86_avx2_pslli_w:
11292     case Intrinsic::x86_avx2_pslli_d:
11293     case Intrinsic::x86_avx2_pslli_q:
11294       Opcode = X86ISD::VSHLI;
11295       break;
11296     case Intrinsic::x86_sse2_psrli_w:
11297     case Intrinsic::x86_sse2_psrli_d:
11298     case Intrinsic::x86_sse2_psrli_q:
11299     case Intrinsic::x86_avx2_psrli_w:
11300     case Intrinsic::x86_avx2_psrli_d:
11301     case Intrinsic::x86_avx2_psrli_q:
11302       Opcode = X86ISD::VSRLI;
11303       break;
11304     case Intrinsic::x86_sse2_psrai_w:
11305     case Intrinsic::x86_sse2_psrai_d:
11306     case Intrinsic::x86_avx2_psrai_w:
11307     case Intrinsic::x86_avx2_psrai_d:
11308       Opcode = X86ISD::VSRAI;
11309       break;
11310     }
11311     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11312                                Op.getOperand(1), Op.getOperand(2), DAG);
11313   }
11314
11315   case Intrinsic::x86_sse42_pcmpistria128:
11316   case Intrinsic::x86_sse42_pcmpestria128:
11317   case Intrinsic::x86_sse42_pcmpistric128:
11318   case Intrinsic::x86_sse42_pcmpestric128:
11319   case Intrinsic::x86_sse42_pcmpistrio128:
11320   case Intrinsic::x86_sse42_pcmpestrio128:
11321   case Intrinsic::x86_sse42_pcmpistris128:
11322   case Intrinsic::x86_sse42_pcmpestris128:
11323   case Intrinsic::x86_sse42_pcmpistriz128:
11324   case Intrinsic::x86_sse42_pcmpestriz128: {
11325     unsigned Opcode;
11326     unsigned X86CC;
11327     switch (IntNo) {
11328     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11329     case Intrinsic::x86_sse42_pcmpistria128:
11330       Opcode = X86ISD::PCMPISTRI;
11331       X86CC = X86::COND_A;
11332       break;
11333     case Intrinsic::x86_sse42_pcmpestria128:
11334       Opcode = X86ISD::PCMPESTRI;
11335       X86CC = X86::COND_A;
11336       break;
11337     case Intrinsic::x86_sse42_pcmpistric128:
11338       Opcode = X86ISD::PCMPISTRI;
11339       X86CC = X86::COND_B;
11340       break;
11341     case Intrinsic::x86_sse42_pcmpestric128:
11342       Opcode = X86ISD::PCMPESTRI;
11343       X86CC = X86::COND_B;
11344       break;
11345     case Intrinsic::x86_sse42_pcmpistrio128:
11346       Opcode = X86ISD::PCMPISTRI;
11347       X86CC = X86::COND_O;
11348       break;
11349     case Intrinsic::x86_sse42_pcmpestrio128:
11350       Opcode = X86ISD::PCMPESTRI;
11351       X86CC = X86::COND_O;
11352       break;
11353     case Intrinsic::x86_sse42_pcmpistris128:
11354       Opcode = X86ISD::PCMPISTRI;
11355       X86CC = X86::COND_S;
11356       break;
11357     case Intrinsic::x86_sse42_pcmpestris128:
11358       Opcode = X86ISD::PCMPESTRI;
11359       X86CC = X86::COND_S;
11360       break;
11361     case Intrinsic::x86_sse42_pcmpistriz128:
11362       Opcode = X86ISD::PCMPISTRI;
11363       X86CC = X86::COND_E;
11364       break;
11365     case Intrinsic::x86_sse42_pcmpestriz128:
11366       Opcode = X86ISD::PCMPESTRI;
11367       X86CC = X86::COND_E;
11368       break;
11369     }
11370     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11371     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11372     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11373     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11374                                 DAG.getConstant(X86CC, MVT::i8),
11375                                 SDValue(PCMP.getNode(), 1));
11376     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11377   }
11378
11379   case Intrinsic::x86_sse42_pcmpistri128:
11380   case Intrinsic::x86_sse42_pcmpestri128: {
11381     unsigned Opcode;
11382     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11383       Opcode = X86ISD::PCMPISTRI;
11384     else
11385       Opcode = X86ISD::PCMPESTRI;
11386
11387     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11388     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11389     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11390   }
11391   case Intrinsic::x86_fma_vfmadd_ps:
11392   case Intrinsic::x86_fma_vfmadd_pd:
11393   case Intrinsic::x86_fma_vfmsub_ps:
11394   case Intrinsic::x86_fma_vfmsub_pd:
11395   case Intrinsic::x86_fma_vfnmadd_ps:
11396   case Intrinsic::x86_fma_vfnmadd_pd:
11397   case Intrinsic::x86_fma_vfnmsub_ps:
11398   case Intrinsic::x86_fma_vfnmsub_pd:
11399   case Intrinsic::x86_fma_vfmaddsub_ps:
11400   case Intrinsic::x86_fma_vfmaddsub_pd:
11401   case Intrinsic::x86_fma_vfmsubadd_ps:
11402   case Intrinsic::x86_fma_vfmsubadd_pd:
11403   case Intrinsic::x86_fma_vfmadd_ps_256:
11404   case Intrinsic::x86_fma_vfmadd_pd_256:
11405   case Intrinsic::x86_fma_vfmsub_ps_256:
11406   case Intrinsic::x86_fma_vfmsub_pd_256:
11407   case Intrinsic::x86_fma_vfnmadd_ps_256:
11408   case Intrinsic::x86_fma_vfnmadd_pd_256:
11409   case Intrinsic::x86_fma_vfnmsub_ps_256:
11410   case Intrinsic::x86_fma_vfnmsub_pd_256:
11411   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11412   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11413   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11414   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11415     unsigned Opc;
11416     switch (IntNo) {
11417     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11418     case Intrinsic::x86_fma_vfmadd_ps:
11419     case Intrinsic::x86_fma_vfmadd_pd:
11420     case Intrinsic::x86_fma_vfmadd_ps_256:
11421     case Intrinsic::x86_fma_vfmadd_pd_256:
11422       Opc = X86ISD::FMADD;
11423       break;
11424     case Intrinsic::x86_fma_vfmsub_ps:
11425     case Intrinsic::x86_fma_vfmsub_pd:
11426     case Intrinsic::x86_fma_vfmsub_ps_256:
11427     case Intrinsic::x86_fma_vfmsub_pd_256:
11428       Opc = X86ISD::FMSUB;
11429       break;
11430     case Intrinsic::x86_fma_vfnmadd_ps:
11431     case Intrinsic::x86_fma_vfnmadd_pd:
11432     case Intrinsic::x86_fma_vfnmadd_ps_256:
11433     case Intrinsic::x86_fma_vfnmadd_pd_256:
11434       Opc = X86ISD::FNMADD;
11435       break;
11436     case Intrinsic::x86_fma_vfnmsub_ps:
11437     case Intrinsic::x86_fma_vfnmsub_pd:
11438     case Intrinsic::x86_fma_vfnmsub_ps_256:
11439     case Intrinsic::x86_fma_vfnmsub_pd_256:
11440       Opc = X86ISD::FNMSUB;
11441       break;
11442     case Intrinsic::x86_fma_vfmaddsub_ps:
11443     case Intrinsic::x86_fma_vfmaddsub_pd:
11444     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11445     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11446       Opc = X86ISD::FMADDSUB;
11447       break;
11448     case Intrinsic::x86_fma_vfmsubadd_ps:
11449     case Intrinsic::x86_fma_vfmsubadd_pd:
11450     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11451     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11452       Opc = X86ISD::FMSUBADD;
11453       break;
11454     }
11455
11456     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11457                        Op.getOperand(2), Op.getOperand(3));
11458   }
11459   }
11460 }
11461
11462 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11463   SDLoc dl(Op);
11464   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11465   switch (IntNo) {
11466   default: return SDValue();    // Don't custom lower most intrinsics.
11467
11468   // RDRAND/RDSEED intrinsics.
11469   case Intrinsic::x86_rdrand_16:
11470   case Intrinsic::x86_rdrand_32:
11471   case Intrinsic::x86_rdrand_64:
11472   case Intrinsic::x86_rdseed_16:
11473   case Intrinsic::x86_rdseed_32:
11474   case Intrinsic::x86_rdseed_64: {
11475     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11476                        IntNo == Intrinsic::x86_rdseed_32 ||
11477                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11478                                                             X86ISD::RDRAND;
11479     // Emit the node with the right value type.
11480     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11481     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11482
11483     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11484     // Otherwise return the value from Rand, which is always 0, casted to i32.
11485     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11486                       DAG.getConstant(1, Op->getValueType(1)),
11487                       DAG.getConstant(X86::COND_B, MVT::i32),
11488                       SDValue(Result.getNode(), 1) };
11489     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11490                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11491                                   Ops, array_lengthof(Ops));
11492
11493     // Return { result, isValid, chain }.
11494     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11495                        SDValue(Result.getNode(), 2));
11496   }
11497
11498   // XTEST intrinsics.
11499   case Intrinsic::x86_xtest: {
11500     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11501     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11502     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11503                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11504                                 InTrans);
11505     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11506     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11507                        Ret, SDValue(InTrans.getNode(), 1));
11508   }
11509   }
11510 }
11511
11512 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11513                                            SelectionDAG &DAG) const {
11514   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11515   MFI->setReturnAddressIsTaken(true);
11516
11517   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11518   SDLoc dl(Op);
11519   EVT PtrVT = getPointerTy();
11520
11521   if (Depth > 0) {
11522     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11523     const X86RegisterInfo *RegInfo =
11524       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11525     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11526     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11527                        DAG.getNode(ISD::ADD, dl, PtrVT,
11528                                    FrameAddr, Offset),
11529                        MachinePointerInfo(), false, false, false, 0);
11530   }
11531
11532   // Just load the return address.
11533   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11534   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11535                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11536 }
11537
11538 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11539   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11540   MFI->setFrameAddressIsTaken(true);
11541
11542   EVT VT = Op.getValueType();
11543   SDLoc dl(Op);  // FIXME probably not meaningful
11544   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11545   const X86RegisterInfo *RegInfo =
11546     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11547   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11548   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11549           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11550          "Invalid Frame Register!");
11551   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11552   while (Depth--)
11553     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11554                             MachinePointerInfo(),
11555                             false, false, false, 0);
11556   return FrameAddr;
11557 }
11558
11559 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11560                                                      SelectionDAG &DAG) const {
11561   const X86RegisterInfo *RegInfo =
11562     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11563   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11564 }
11565
11566 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11567   SDValue Chain     = Op.getOperand(0);
11568   SDValue Offset    = Op.getOperand(1);
11569   SDValue Handler   = Op.getOperand(2);
11570   SDLoc dl      (Op);
11571
11572   EVT PtrVT = getPointerTy();
11573   const X86RegisterInfo *RegInfo =
11574     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11575   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11576   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11577           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11578          "Invalid Frame Register!");
11579   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11580   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11581
11582   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11583                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11584   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11585   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11586                        false, false, 0);
11587   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11588
11589   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11590                      DAG.getRegister(StoreAddrReg, PtrVT));
11591 }
11592
11593 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11594                                                SelectionDAG &DAG) const {
11595   SDLoc DL(Op);
11596   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11597                      DAG.getVTList(MVT::i32, MVT::Other),
11598                      Op.getOperand(0), Op.getOperand(1));
11599 }
11600
11601 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11602                                                 SelectionDAG &DAG) const {
11603   SDLoc DL(Op);
11604   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11605                      Op.getOperand(0), Op.getOperand(1));
11606 }
11607
11608 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11609   return Op.getOperand(0);
11610 }
11611
11612 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11613                                                 SelectionDAG &DAG) const {
11614   SDValue Root = Op.getOperand(0);
11615   SDValue Trmp = Op.getOperand(1); // trampoline
11616   SDValue FPtr = Op.getOperand(2); // nested function
11617   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11618   SDLoc dl (Op);
11619
11620   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11621   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11622
11623   if (Subtarget->is64Bit()) {
11624     SDValue OutChains[6];
11625
11626     // Large code-model.
11627     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11628     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11629
11630     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11631     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11632
11633     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11634
11635     // Load the pointer to the nested function into R11.
11636     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11637     SDValue Addr = Trmp;
11638     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11639                                 Addr, MachinePointerInfo(TrmpAddr),
11640                                 false, false, 0);
11641
11642     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11643                        DAG.getConstant(2, MVT::i64));
11644     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11645                                 MachinePointerInfo(TrmpAddr, 2),
11646                                 false, false, 2);
11647
11648     // Load the 'nest' parameter value into R10.
11649     // R10 is specified in X86CallingConv.td
11650     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11651     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11652                        DAG.getConstant(10, MVT::i64));
11653     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11654                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11655                                 false, false, 0);
11656
11657     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11658                        DAG.getConstant(12, MVT::i64));
11659     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11660                                 MachinePointerInfo(TrmpAddr, 12),
11661                                 false, false, 2);
11662
11663     // Jump to the nested function.
11664     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11665     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11666                        DAG.getConstant(20, MVT::i64));
11667     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11668                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11669                                 false, false, 0);
11670
11671     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11672     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11673                        DAG.getConstant(22, MVT::i64));
11674     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11675                                 MachinePointerInfo(TrmpAddr, 22),
11676                                 false, false, 0);
11677
11678     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11679   } else {
11680     const Function *Func =
11681       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11682     CallingConv::ID CC = Func->getCallingConv();
11683     unsigned NestReg;
11684
11685     switch (CC) {
11686     default:
11687       llvm_unreachable("Unsupported calling convention");
11688     case CallingConv::C:
11689     case CallingConv::X86_StdCall: {
11690       // Pass 'nest' parameter in ECX.
11691       // Must be kept in sync with X86CallingConv.td
11692       NestReg = X86::ECX;
11693
11694       // Check that ECX wasn't needed by an 'inreg' parameter.
11695       FunctionType *FTy = Func->getFunctionType();
11696       const AttributeSet &Attrs = Func->getAttributes();
11697
11698       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11699         unsigned InRegCount = 0;
11700         unsigned Idx = 1;
11701
11702         for (FunctionType::param_iterator I = FTy->param_begin(),
11703              E = FTy->param_end(); I != E; ++I, ++Idx)
11704           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11705             // FIXME: should only count parameters that are lowered to integers.
11706             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11707
11708         if (InRegCount > 2) {
11709           report_fatal_error("Nest register in use - reduce number of inreg"
11710                              " parameters!");
11711         }
11712       }
11713       break;
11714     }
11715     case CallingConv::X86_FastCall:
11716     case CallingConv::X86_ThisCall:
11717     case CallingConv::Fast:
11718       // Pass 'nest' parameter in EAX.
11719       // Must be kept in sync with X86CallingConv.td
11720       NestReg = X86::EAX;
11721       break;
11722     }
11723
11724     SDValue OutChains[4];
11725     SDValue Addr, Disp;
11726
11727     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11728                        DAG.getConstant(10, MVT::i32));
11729     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11730
11731     // This is storing the opcode for MOV32ri.
11732     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11733     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11734     OutChains[0] = DAG.getStore(Root, dl,
11735                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11736                                 Trmp, MachinePointerInfo(TrmpAddr),
11737                                 false, false, 0);
11738
11739     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11740                        DAG.getConstant(1, MVT::i32));
11741     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11742                                 MachinePointerInfo(TrmpAddr, 1),
11743                                 false, false, 1);
11744
11745     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11746     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11747                        DAG.getConstant(5, MVT::i32));
11748     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11749                                 MachinePointerInfo(TrmpAddr, 5),
11750                                 false, false, 1);
11751
11752     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11753                        DAG.getConstant(6, MVT::i32));
11754     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11755                                 MachinePointerInfo(TrmpAddr, 6),
11756                                 false, false, 1);
11757
11758     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11759   }
11760 }
11761
11762 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11763                                             SelectionDAG &DAG) const {
11764   /*
11765    The rounding mode is in bits 11:10 of FPSR, and has the following
11766    settings:
11767      00 Round to nearest
11768      01 Round to -inf
11769      10 Round to +inf
11770      11 Round to 0
11771
11772   FLT_ROUNDS, on the other hand, expects the following:
11773     -1 Undefined
11774      0 Round to 0
11775      1 Round to nearest
11776      2 Round to +inf
11777      3 Round to -inf
11778
11779   To perform the conversion, we do:
11780     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11781   */
11782
11783   MachineFunction &MF = DAG.getMachineFunction();
11784   const TargetMachine &TM = MF.getTarget();
11785   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11786   unsigned StackAlignment = TFI.getStackAlignment();
11787   EVT VT = Op.getValueType();
11788   SDLoc DL(Op);
11789
11790   // Save FP Control Word to stack slot
11791   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11792   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11793
11794   MachineMemOperand *MMO =
11795    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11796                            MachineMemOperand::MOStore, 2, 2);
11797
11798   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11799   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11800                                           DAG.getVTList(MVT::Other),
11801                                           Ops, array_lengthof(Ops), MVT::i16,
11802                                           MMO);
11803
11804   // Load FP Control Word from stack slot
11805   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11806                             MachinePointerInfo(), false, false, false, 0);
11807
11808   // Transform as necessary
11809   SDValue CWD1 =
11810     DAG.getNode(ISD::SRL, DL, MVT::i16,
11811                 DAG.getNode(ISD::AND, DL, MVT::i16,
11812                             CWD, DAG.getConstant(0x800, MVT::i16)),
11813                 DAG.getConstant(11, MVT::i8));
11814   SDValue CWD2 =
11815     DAG.getNode(ISD::SRL, DL, MVT::i16,
11816                 DAG.getNode(ISD::AND, DL, MVT::i16,
11817                             CWD, DAG.getConstant(0x400, MVT::i16)),
11818                 DAG.getConstant(9, MVT::i8));
11819
11820   SDValue RetVal =
11821     DAG.getNode(ISD::AND, DL, MVT::i16,
11822                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11823                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11824                             DAG.getConstant(1, MVT::i16)),
11825                 DAG.getConstant(3, MVT::i16));
11826
11827   return DAG.getNode((VT.getSizeInBits() < 16 ?
11828                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11829 }
11830
11831 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11832   EVT VT = Op.getValueType();
11833   EVT OpVT = VT;
11834   unsigned NumBits = VT.getSizeInBits();
11835   SDLoc dl(Op);
11836
11837   Op = Op.getOperand(0);
11838   if (VT == MVT::i8) {
11839     // Zero extend to i32 since there is not an i8 bsr.
11840     OpVT = MVT::i32;
11841     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11842   }
11843
11844   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11845   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11846   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11847
11848   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11849   SDValue Ops[] = {
11850     Op,
11851     DAG.getConstant(NumBits+NumBits-1, OpVT),
11852     DAG.getConstant(X86::COND_E, MVT::i8),
11853     Op.getValue(1)
11854   };
11855   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11856
11857   // Finally xor with NumBits-1.
11858   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11859
11860   if (VT == MVT::i8)
11861     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11862   return Op;
11863 }
11864
11865 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11866   EVT VT = Op.getValueType();
11867   EVT OpVT = VT;
11868   unsigned NumBits = VT.getSizeInBits();
11869   SDLoc dl(Op);
11870
11871   Op = Op.getOperand(0);
11872   if (VT == MVT::i8) {
11873     // Zero extend to i32 since there is not an i8 bsr.
11874     OpVT = MVT::i32;
11875     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11876   }
11877
11878   // Issue a bsr (scan bits in reverse).
11879   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11880   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11881
11882   // And xor with NumBits-1.
11883   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11884
11885   if (VT == MVT::i8)
11886     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11887   return Op;
11888 }
11889
11890 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11891   EVT VT = Op.getValueType();
11892   unsigned NumBits = VT.getSizeInBits();
11893   SDLoc dl(Op);
11894   Op = Op.getOperand(0);
11895
11896   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11897   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11898   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11899
11900   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11901   SDValue Ops[] = {
11902     Op,
11903     DAG.getConstant(NumBits, VT),
11904     DAG.getConstant(X86::COND_E, MVT::i8),
11905     Op.getValue(1)
11906   };
11907   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11908 }
11909
11910 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11911 // ones, and then concatenate the result back.
11912 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11913   EVT VT = Op.getValueType();
11914
11915   assert(VT.is256BitVector() && VT.isInteger() &&
11916          "Unsupported value type for operation");
11917
11918   unsigned NumElems = VT.getVectorNumElements();
11919   SDLoc dl(Op);
11920
11921   // Extract the LHS vectors
11922   SDValue LHS = Op.getOperand(0);
11923   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11924   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11925
11926   // Extract the RHS vectors
11927   SDValue RHS = Op.getOperand(1);
11928   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11929   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11930
11931   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11932   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11933
11934   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11935                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11936                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11937 }
11938
11939 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11940   assert(Op.getValueType().is256BitVector() &&
11941          Op.getValueType().isInteger() &&
11942          "Only handle AVX 256-bit vector integer operation");
11943   return Lower256IntArith(Op, DAG);
11944 }
11945
11946 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11947   assert(Op.getValueType().is256BitVector() &&
11948          Op.getValueType().isInteger() &&
11949          "Only handle AVX 256-bit vector integer operation");
11950   return Lower256IntArith(Op, DAG);
11951 }
11952
11953 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11954                         SelectionDAG &DAG) {
11955   SDLoc dl(Op);
11956   EVT VT = Op.getValueType();
11957
11958   // Decompose 256-bit ops into smaller 128-bit ops.
11959   if (VT.is256BitVector() && !Subtarget->hasInt256())
11960     return Lower256IntArith(Op, DAG);
11961
11962   SDValue A = Op.getOperand(0);
11963   SDValue B = Op.getOperand(1);
11964
11965   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11966   if (VT == MVT::v4i32) {
11967     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11968            "Should not custom lower when pmuldq is available!");
11969
11970     // Extract the odd parts.
11971     static const int UnpackMask[] = { 1, -1, 3, -1 };
11972     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11973     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11974
11975     // Multiply the even parts.
11976     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11977     // Now multiply odd parts.
11978     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11979
11980     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11981     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11982
11983     // Merge the two vectors back together with a shuffle. This expands into 2
11984     // shuffles.
11985     static const int ShufMask[] = { 0, 4, 2, 6 };
11986     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11987   }
11988
11989   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11990          "Only know how to lower V2I64/V4I64 multiply");
11991
11992   //  Ahi = psrlqi(a, 32);
11993   //  Bhi = psrlqi(b, 32);
11994   //
11995   //  AloBlo = pmuludq(a, b);
11996   //  AloBhi = pmuludq(a, Bhi);
11997   //  AhiBlo = pmuludq(Ahi, b);
11998
11999   //  AloBhi = psllqi(AloBhi, 32);
12000   //  AhiBlo = psllqi(AhiBlo, 32);
12001   //  return AloBlo + AloBhi + AhiBlo;
12002
12003   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
12004
12005   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
12006   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
12007
12008   // Bit cast to 32-bit vectors for MULUDQ
12009   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
12010   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12011   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12012   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12013   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12014
12015   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12016   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12017   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12018
12019   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
12020   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
12021
12022   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12023   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12024 }
12025
12026 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
12027   EVT VT = Op.getValueType();
12028   EVT EltTy = VT.getVectorElementType();
12029   unsigned NumElts = VT.getVectorNumElements();
12030   SDValue N0 = Op.getOperand(0);
12031   SDLoc dl(Op);
12032
12033   // Lower sdiv X, pow2-const.
12034   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12035   if (!C)
12036     return SDValue();
12037
12038   APInt SplatValue, SplatUndef;
12039   unsigned SplatBitSize;
12040   bool HasAnyUndefs;
12041   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12042                           HasAnyUndefs) ||
12043       EltTy.getSizeInBits() < SplatBitSize)
12044     return SDValue();
12045
12046   if ((SplatValue != 0) &&
12047       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12048     unsigned lg2 = SplatValue.countTrailingZeros();
12049     // Splat the sign bit.
12050     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
12051     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
12052     // Add (N0 < 0) ? abs2 - 1 : 0;
12053     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
12054     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
12055     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12056     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
12057     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
12058
12059     // If we're dividing by a positive value, we're done.  Otherwise, we must
12060     // negate the result.
12061     if (SplatValue.isNonNegative())
12062       return SRA;
12063
12064     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12065     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12066     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12067   }
12068   return SDValue();
12069 }
12070
12071 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12072                                          const X86Subtarget *Subtarget) {
12073   EVT VT = Op.getValueType();
12074   SDLoc dl(Op);
12075   SDValue R = Op.getOperand(0);
12076   SDValue Amt = Op.getOperand(1);
12077
12078   // Optimize shl/srl/sra with constant shift amount.
12079   if (isSplatVector(Amt.getNode())) {
12080     SDValue SclrAmt = Amt->getOperand(0);
12081     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12082       uint64_t ShiftAmt = C->getZExtValue();
12083
12084       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12085           (Subtarget->hasInt256() &&
12086            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
12087         if (Op.getOpcode() == ISD::SHL)
12088           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12089                              DAG.getConstant(ShiftAmt, MVT::i32));
12090         if (Op.getOpcode() == ISD::SRL)
12091           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12092                              DAG.getConstant(ShiftAmt, MVT::i32));
12093         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12094           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12095                              DAG.getConstant(ShiftAmt, MVT::i32));
12096       }
12097
12098       if (VT == MVT::v16i8) {
12099         if (Op.getOpcode() == ISD::SHL) {
12100           // Make a large shift.
12101           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
12102                                     DAG.getConstant(ShiftAmt, MVT::i32));
12103           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12104           // Zero out the rightmost bits.
12105           SmallVector<SDValue, 16> V(16,
12106                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12107                                                      MVT::i8));
12108           return DAG.getNode(ISD::AND, dl, VT, SHL,
12109                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12110         }
12111         if (Op.getOpcode() == ISD::SRL) {
12112           // Make a large shift.
12113           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
12114                                     DAG.getConstant(ShiftAmt, MVT::i32));
12115           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12116           // Zero out the leftmost bits.
12117           SmallVector<SDValue, 16> V(16,
12118                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12119                                                      MVT::i8));
12120           return DAG.getNode(ISD::AND, dl, VT, SRL,
12121                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12122         }
12123         if (Op.getOpcode() == ISD::SRA) {
12124           if (ShiftAmt == 7) {
12125             // R s>> 7  ===  R s< 0
12126             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12127             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12128           }
12129
12130           // R s>> a === ((R u>> a) ^ m) - m
12131           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12132           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12133                                                          MVT::i8));
12134           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12135           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12136           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12137           return Res;
12138         }
12139         llvm_unreachable("Unknown shift opcode.");
12140       }
12141
12142       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12143         if (Op.getOpcode() == ISD::SHL) {
12144           // Make a large shift.
12145           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
12146                                     DAG.getConstant(ShiftAmt, MVT::i32));
12147           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12148           // Zero out the rightmost bits.
12149           SmallVector<SDValue, 32> V(32,
12150                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12151                                                      MVT::i8));
12152           return DAG.getNode(ISD::AND, dl, VT, SHL,
12153                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12154         }
12155         if (Op.getOpcode() == ISD::SRL) {
12156           // Make a large shift.
12157           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
12158                                     DAG.getConstant(ShiftAmt, MVT::i32));
12159           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12160           // Zero out the leftmost bits.
12161           SmallVector<SDValue, 32> V(32,
12162                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12163                                                      MVT::i8));
12164           return DAG.getNode(ISD::AND, dl, VT, SRL,
12165                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12166         }
12167         if (Op.getOpcode() == ISD::SRA) {
12168           if (ShiftAmt == 7) {
12169             // R s>> 7  ===  R s< 0
12170             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12171             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12172           }
12173
12174           // R s>> a === ((R u>> a) ^ m) - m
12175           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12176           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12177                                                          MVT::i8));
12178           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12179           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12180           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12181           return Res;
12182         }
12183         llvm_unreachable("Unknown shift opcode.");
12184       }
12185     }
12186   }
12187
12188   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12189   if (!Subtarget->is64Bit() &&
12190       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12191       Amt.getOpcode() == ISD::BITCAST &&
12192       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12193     Amt = Amt.getOperand(0);
12194     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12195                      VT.getVectorNumElements();
12196     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12197     uint64_t ShiftAmt = 0;
12198     for (unsigned i = 0; i != Ratio; ++i) {
12199       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12200       if (C == 0)
12201         return SDValue();
12202       // 6 == Log2(64)
12203       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12204     }
12205     // Check remaining shift amounts.
12206     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12207       uint64_t ShAmt = 0;
12208       for (unsigned j = 0; j != Ratio; ++j) {
12209         ConstantSDNode *C =
12210           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12211         if (C == 0)
12212           return SDValue();
12213         // 6 == Log2(64)
12214         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12215       }
12216       if (ShAmt != ShiftAmt)
12217         return SDValue();
12218     }
12219     switch (Op.getOpcode()) {
12220     default:
12221       llvm_unreachable("Unknown shift opcode!");
12222     case ISD::SHL:
12223       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12224                          DAG.getConstant(ShiftAmt, MVT::i32));
12225     case ISD::SRL:
12226       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12227                          DAG.getConstant(ShiftAmt, MVT::i32));
12228     case ISD::SRA:
12229       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12230                          DAG.getConstant(ShiftAmt, MVT::i32));
12231     }
12232   }
12233
12234   return SDValue();
12235 }
12236
12237 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12238                                         const X86Subtarget* Subtarget) {
12239   EVT VT = Op.getValueType();
12240   SDLoc dl(Op);
12241   SDValue R = Op.getOperand(0);
12242   SDValue Amt = Op.getOperand(1);
12243
12244   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12245       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12246       (Subtarget->hasInt256() &&
12247        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12248         VT == MVT::v8i32 || VT == MVT::v16i16))) {
12249     SDValue BaseShAmt;
12250     EVT EltVT = VT.getVectorElementType();
12251
12252     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12253       unsigned NumElts = VT.getVectorNumElements();
12254       unsigned i, j;
12255       for (i = 0; i != NumElts; ++i) {
12256         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12257           continue;
12258         break;
12259       }
12260       for (j = i; j != NumElts; ++j) {
12261         SDValue Arg = Amt.getOperand(j);
12262         if (Arg.getOpcode() == ISD::UNDEF) continue;
12263         if (Arg != Amt.getOperand(i))
12264           break;
12265       }
12266       if (i != NumElts && j == NumElts)
12267         BaseShAmt = Amt.getOperand(i);
12268     } else {
12269       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12270         Amt = Amt.getOperand(0);
12271       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12272                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12273         SDValue InVec = Amt.getOperand(0);
12274         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12275           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12276           unsigned i = 0;
12277           for (; i != NumElts; ++i) {
12278             SDValue Arg = InVec.getOperand(i);
12279             if (Arg.getOpcode() == ISD::UNDEF) continue;
12280             BaseShAmt = Arg;
12281             break;
12282           }
12283         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12284            if (ConstantSDNode *C =
12285                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12286              unsigned SplatIdx =
12287                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12288              if (C->getZExtValue() == SplatIdx)
12289                BaseShAmt = InVec.getOperand(1);
12290            }
12291         }
12292         if (BaseShAmt.getNode() == 0)
12293           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12294                                   DAG.getIntPtrConstant(0));
12295       }
12296     }
12297
12298     if (BaseShAmt.getNode()) {
12299       if (EltVT.bitsGT(MVT::i32))
12300         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12301       else if (EltVT.bitsLT(MVT::i32))
12302         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12303
12304       switch (Op.getOpcode()) {
12305       default:
12306         llvm_unreachable("Unknown shift opcode!");
12307       case ISD::SHL:
12308         switch (VT.getSimpleVT().SimpleTy) {
12309         default: return SDValue();
12310         case MVT::v2i64:
12311         case MVT::v4i32:
12312         case MVT::v8i16:
12313         case MVT::v4i64:
12314         case MVT::v8i32:
12315         case MVT::v16i16:
12316           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12317         }
12318       case ISD::SRA:
12319         switch (VT.getSimpleVT().SimpleTy) {
12320         default: return SDValue();
12321         case MVT::v4i32:
12322         case MVT::v8i16:
12323         case MVT::v8i32:
12324         case MVT::v16i16:
12325           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12326         }
12327       case ISD::SRL:
12328         switch (VT.getSimpleVT().SimpleTy) {
12329         default: return SDValue();
12330         case MVT::v2i64:
12331         case MVT::v4i32:
12332         case MVT::v8i16:
12333         case MVT::v4i64:
12334         case MVT::v8i32:
12335         case MVT::v16i16:
12336           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12337         }
12338       }
12339     }
12340   }
12341
12342   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12343   if (!Subtarget->is64Bit() &&
12344       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12345       Amt.getOpcode() == ISD::BITCAST &&
12346       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12347     Amt = Amt.getOperand(0);
12348     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12349                      VT.getVectorNumElements();
12350     std::vector<SDValue> Vals(Ratio);
12351     for (unsigned i = 0; i != Ratio; ++i)
12352       Vals[i] = Amt.getOperand(i);
12353     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12354       for (unsigned j = 0; j != Ratio; ++j)
12355         if (Vals[j] != Amt.getOperand(i + j))
12356           return SDValue();
12357     }
12358     switch (Op.getOpcode()) {
12359     default:
12360       llvm_unreachable("Unknown shift opcode!");
12361     case ISD::SHL:
12362       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12363     case ISD::SRL:
12364       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12365     case ISD::SRA:
12366       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12367     }
12368   }
12369
12370   return SDValue();
12371 }
12372
12373 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
12374
12375   EVT VT = Op.getValueType();
12376   SDLoc dl(Op);
12377   SDValue R = Op.getOperand(0);
12378   SDValue Amt = Op.getOperand(1);
12379   SDValue V;
12380
12381   if (!Subtarget->hasSSE2())
12382     return SDValue();
12383
12384   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12385   if (V.getNode())
12386     return V;
12387
12388   V = LowerScalarVariableShift(Op, DAG, Subtarget);
12389   if (V.getNode())
12390       return V;
12391
12392   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12393   if (Subtarget->hasInt256()) {
12394     if (Op.getOpcode() == ISD::SRL &&
12395         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12396          VT == MVT::v4i64 || VT == MVT::v8i32))
12397       return Op;
12398     if (Op.getOpcode() == ISD::SHL &&
12399         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12400          VT == MVT::v4i64 || VT == MVT::v8i32))
12401       return Op;
12402     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12403       return Op;
12404   }
12405
12406   // Lower SHL with variable shift amount.
12407   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12408     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12409
12410     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12411     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12412     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12413     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12414   }
12415   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12416     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12417
12418     // a = a << 5;
12419     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12420     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12421
12422     // Turn 'a' into a mask suitable for VSELECT
12423     SDValue VSelM = DAG.getConstant(0x80, VT);
12424     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12425     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12426
12427     SDValue CM1 = DAG.getConstant(0x0f, VT);
12428     SDValue CM2 = DAG.getConstant(0x3f, VT);
12429
12430     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12431     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12432     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12433                             DAG.getConstant(4, MVT::i32), DAG);
12434     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12435     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12436
12437     // a += a
12438     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12439     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12440     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12441
12442     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12443     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12444     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12445                             DAG.getConstant(2, MVT::i32), DAG);
12446     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12447     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12448
12449     // a += a
12450     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12451     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12452     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12453
12454     // return VSELECT(r, r+r, a);
12455     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12456                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12457     return R;
12458   }
12459
12460   // Decompose 256-bit shifts into smaller 128-bit shifts.
12461   if (VT.is256BitVector()) {
12462     unsigned NumElems = VT.getVectorNumElements();
12463     MVT EltVT = VT.getVectorElementType().getSimpleVT();
12464     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12465
12466     // Extract the two vectors
12467     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12468     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12469
12470     // Recreate the shift amount vectors
12471     SDValue Amt1, Amt2;
12472     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12473       // Constant shift amount
12474       SmallVector<SDValue, 4> Amt1Csts;
12475       SmallVector<SDValue, 4> Amt2Csts;
12476       for (unsigned i = 0; i != NumElems/2; ++i)
12477         Amt1Csts.push_back(Amt->getOperand(i));
12478       for (unsigned i = NumElems/2; i != NumElems; ++i)
12479         Amt2Csts.push_back(Amt->getOperand(i));
12480
12481       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12482                                  &Amt1Csts[0], NumElems/2);
12483       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12484                                  &Amt2Csts[0], NumElems/2);
12485     } else {
12486       // Variable shift amount
12487       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12488       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12489     }
12490
12491     // Issue new vector shifts for the smaller types
12492     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12493     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12494
12495     // Concatenate the result back
12496     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12497   }
12498
12499   return SDValue();
12500 }
12501
12502 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12503   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12504   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12505   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12506   // has only one use.
12507   SDNode *N = Op.getNode();
12508   SDValue LHS = N->getOperand(0);
12509   SDValue RHS = N->getOperand(1);
12510   unsigned BaseOp = 0;
12511   unsigned Cond = 0;
12512   SDLoc DL(Op);
12513   switch (Op.getOpcode()) {
12514   default: llvm_unreachable("Unknown ovf instruction!");
12515   case ISD::SADDO:
12516     // A subtract of one will be selected as a INC. Note that INC doesn't
12517     // set CF, so we can't do this for UADDO.
12518     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12519       if (C->isOne()) {
12520         BaseOp = X86ISD::INC;
12521         Cond = X86::COND_O;
12522         break;
12523       }
12524     BaseOp = X86ISD::ADD;
12525     Cond = X86::COND_O;
12526     break;
12527   case ISD::UADDO:
12528     BaseOp = X86ISD::ADD;
12529     Cond = X86::COND_B;
12530     break;
12531   case ISD::SSUBO:
12532     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12533     // set CF, so we can't do this for USUBO.
12534     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12535       if (C->isOne()) {
12536         BaseOp = X86ISD::DEC;
12537         Cond = X86::COND_O;
12538         break;
12539       }
12540     BaseOp = X86ISD::SUB;
12541     Cond = X86::COND_O;
12542     break;
12543   case ISD::USUBO:
12544     BaseOp = X86ISD::SUB;
12545     Cond = X86::COND_B;
12546     break;
12547   case ISD::SMULO:
12548     BaseOp = X86ISD::SMUL;
12549     Cond = X86::COND_O;
12550     break;
12551   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12552     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12553                                  MVT::i32);
12554     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12555
12556     SDValue SetCC =
12557       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12558                   DAG.getConstant(X86::COND_O, MVT::i32),
12559                   SDValue(Sum.getNode(), 2));
12560
12561     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12562   }
12563   }
12564
12565   // Also sets EFLAGS.
12566   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12567   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12568
12569   SDValue SetCC =
12570     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12571                 DAG.getConstant(Cond, MVT::i32),
12572                 SDValue(Sum.getNode(), 1));
12573
12574   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12575 }
12576
12577 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12578                                                   SelectionDAG &DAG) const {
12579   SDLoc dl(Op);
12580   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12581   EVT VT = Op.getValueType();
12582
12583   if (!Subtarget->hasSSE2() || !VT.isVector())
12584     return SDValue();
12585
12586   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12587                       ExtraVT.getScalarType().getSizeInBits();
12588   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12589
12590   switch (VT.getSimpleVT().SimpleTy) {
12591     default: return SDValue();
12592     case MVT::v8i32:
12593     case MVT::v16i16:
12594       if (!Subtarget->hasFp256())
12595         return SDValue();
12596       if (!Subtarget->hasInt256()) {
12597         // needs to be split
12598         unsigned NumElems = VT.getVectorNumElements();
12599
12600         // Extract the LHS vectors
12601         SDValue LHS = Op.getOperand(0);
12602         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12603         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12604
12605         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12606         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12607
12608         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12609         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12610         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12611                                    ExtraNumElems/2);
12612         SDValue Extra = DAG.getValueType(ExtraVT);
12613
12614         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12615         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12616
12617         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12618       }
12619       // fall through
12620     case MVT::v4i32:
12621     case MVT::v8i16: {
12622       // (sext (vzext x)) -> (vsext x)
12623       SDValue Op0 = Op.getOperand(0);
12624       SDValue Op00 = Op0.getOperand(0);
12625       SDValue Tmp1;
12626       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12627       if (Op0.getOpcode() == ISD::BITCAST &&
12628           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12629         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12630       if (Tmp1.getNode()) {
12631         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12632         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12633                "This optimization is invalid without a VZEXT.");
12634         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12635       }
12636
12637       // If the above didn't work, then just use Shift-Left + Shift-Right.
12638       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12639       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12640     }
12641   }
12642 }
12643
12644 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12645                                  SelectionDAG &DAG) {
12646   SDLoc dl(Op);
12647   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12648     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12649   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12650     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12651
12652   // The only fence that needs an instruction is a sequentially-consistent
12653   // cross-thread fence.
12654   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12655     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12656     // no-sse2). There isn't any reason to disable it if the target processor
12657     // supports it.
12658     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12659       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12660
12661     SDValue Chain = Op.getOperand(0);
12662     SDValue Zero = DAG.getConstant(0, MVT::i32);
12663     SDValue Ops[] = {
12664       DAG.getRegister(X86::ESP, MVT::i32), // Base
12665       DAG.getTargetConstant(1, MVT::i8),   // Scale
12666       DAG.getRegister(0, MVT::i32),        // Index
12667       DAG.getTargetConstant(0, MVT::i32),  // Disp
12668       DAG.getRegister(0, MVT::i32),        // Segment.
12669       Zero,
12670       Chain
12671     };
12672     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12673     return SDValue(Res, 0);
12674   }
12675
12676   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12677   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12678 }
12679
12680 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12681                              SelectionDAG &DAG) {
12682   EVT T = Op.getValueType();
12683   SDLoc DL(Op);
12684   unsigned Reg = 0;
12685   unsigned size = 0;
12686   switch(T.getSimpleVT().SimpleTy) {
12687   default: llvm_unreachable("Invalid value type!");
12688   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12689   case MVT::i16: Reg = X86::AX;  size = 2; break;
12690   case MVT::i32: Reg = X86::EAX; size = 4; break;
12691   case MVT::i64:
12692     assert(Subtarget->is64Bit() && "Node not type legal!");
12693     Reg = X86::RAX; size = 8;
12694     break;
12695   }
12696   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12697                                     Op.getOperand(2), SDValue());
12698   SDValue Ops[] = { cpIn.getValue(0),
12699                     Op.getOperand(1),
12700                     Op.getOperand(3),
12701                     DAG.getTargetConstant(size, MVT::i8),
12702                     cpIn.getValue(1) };
12703   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12704   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12705   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12706                                            Ops, array_lengthof(Ops), T, MMO);
12707   SDValue cpOut =
12708     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12709   return cpOut;
12710 }
12711
12712 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12713                                      SelectionDAG &DAG) {
12714   assert(Subtarget->is64Bit() && "Result not type legalized?");
12715   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12716   SDValue TheChain = Op.getOperand(0);
12717   SDLoc dl(Op);
12718   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12719   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12720   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12721                                    rax.getValue(2));
12722   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12723                             DAG.getConstant(32, MVT::i8));
12724   SDValue Ops[] = {
12725     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12726     rdx.getValue(1)
12727   };
12728   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12729 }
12730
12731 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12732   EVT SrcVT = Op.getOperand(0).getValueType();
12733   EVT DstVT = Op.getValueType();
12734   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12735          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12736   assert((DstVT == MVT::i64 ||
12737           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12738          "Unexpected custom BITCAST");
12739   // i64 <=> MMX conversions are Legal.
12740   if (SrcVT==MVT::i64 && DstVT.isVector())
12741     return Op;
12742   if (DstVT==MVT::i64 && SrcVT.isVector())
12743     return Op;
12744   // MMX <=> MMX conversions are Legal.
12745   if (SrcVT.isVector() && DstVT.isVector())
12746     return Op;
12747   // All other conversions need to be expanded.
12748   return SDValue();
12749 }
12750
12751 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12752   SDNode *Node = Op.getNode();
12753   SDLoc dl(Node);
12754   EVT T = Node->getValueType(0);
12755   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12756                               DAG.getConstant(0, T), Node->getOperand(2));
12757   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12758                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12759                        Node->getOperand(0),
12760                        Node->getOperand(1), negOp,
12761                        cast<AtomicSDNode>(Node)->getSrcValue(),
12762                        cast<AtomicSDNode>(Node)->getAlignment(),
12763                        cast<AtomicSDNode>(Node)->getOrdering(),
12764                        cast<AtomicSDNode>(Node)->getSynchScope());
12765 }
12766
12767 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12768   SDNode *Node = Op.getNode();
12769   SDLoc dl(Node);
12770   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12771
12772   // Convert seq_cst store -> xchg
12773   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12774   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12775   //        (The only way to get a 16-byte store is cmpxchg16b)
12776   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12777   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12778       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12779     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12780                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12781                                  Node->getOperand(0),
12782                                  Node->getOperand(1), Node->getOperand(2),
12783                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12784                                  cast<AtomicSDNode>(Node)->getOrdering(),
12785                                  cast<AtomicSDNode>(Node)->getSynchScope());
12786     return Swap.getValue(1);
12787   }
12788   // Other atomic stores have a simple pattern.
12789   return Op;
12790 }
12791
12792 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12793   EVT VT = Op.getNode()->getValueType(0);
12794
12795   // Let legalize expand this if it isn't a legal type yet.
12796   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12797     return SDValue();
12798
12799   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12800
12801   unsigned Opc;
12802   bool ExtraOp = false;
12803   switch (Op.getOpcode()) {
12804   default: llvm_unreachable("Invalid code");
12805   case ISD::ADDC: Opc = X86ISD::ADD; break;
12806   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12807   case ISD::SUBC: Opc = X86ISD::SUB; break;
12808   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12809   }
12810
12811   if (!ExtraOp)
12812     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12813                        Op.getOperand(1));
12814   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12815                      Op.getOperand(1), Op.getOperand(2));
12816 }
12817
12818 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12819   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12820
12821   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12822   // which returns the values as { float, float } (in XMM0) or
12823   // { double, double } (which is returned in XMM0, XMM1).
12824   SDLoc dl(Op);
12825   SDValue Arg = Op.getOperand(0);
12826   EVT ArgVT = Arg.getValueType();
12827   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12828
12829   ArgListTy Args;
12830   ArgListEntry Entry;
12831
12832   Entry.Node = Arg;
12833   Entry.Ty = ArgTy;
12834   Entry.isSExt = false;
12835   Entry.isZExt = false;
12836   Args.push_back(Entry);
12837
12838   bool isF64 = ArgVT == MVT::f64;
12839   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12840   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12841   // the results are returned via SRet in memory.
12842   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12843   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12844
12845   Type *RetTy = isF64
12846     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12847     : (Type*)VectorType::get(ArgTy, 4);
12848   TargetLowering::
12849     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12850                          false, false, false, false, 0,
12851                          CallingConv::C, /*isTaillCall=*/false,
12852                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12853                          Callee, Args, DAG, dl);
12854   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12855
12856   if (isF64)
12857     // Returned in xmm0 and xmm1.
12858     return CallResult.first;
12859
12860   // Returned in bits 0:31 and 32:64 xmm0.
12861   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12862                                CallResult.first, DAG.getIntPtrConstant(0));
12863   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12864                                CallResult.first, DAG.getIntPtrConstant(1));
12865   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12866   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12867 }
12868
12869 /// LowerOperation - Provide custom lowering hooks for some operations.
12870 ///
12871 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12872   switch (Op.getOpcode()) {
12873   default: llvm_unreachable("Should not custom lower this!");
12874   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12875   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12876   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12877   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12878   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12879   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12880   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12881   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12882   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12883   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12884   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12885   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12886   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12887   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12888   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12889   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12890   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12891   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12892   case ISD::SHL_PARTS:
12893   case ISD::SRA_PARTS:
12894   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12895   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12896   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12897   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12898   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12899   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12900   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12901   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12902   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12903   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12904   case ISD::FABS:               return LowerFABS(Op, DAG);
12905   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12906   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12907   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12908   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12909   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12910   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12911   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12912   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12913   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12914   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12915   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12916   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12917   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12918   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12919   case ISD::FRAME_TO_ARGS_OFFSET:
12920                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12921   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12922   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12923   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12924   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12925   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12926   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12927   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12928   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12929   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12930   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12931   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12932   case ISD::SRA:
12933   case ISD::SRL:
12934   case ISD::SHL:                return LowerShift(Op, DAG);
12935   case ISD::SADDO:
12936   case ISD::UADDO:
12937   case ISD::SSUBO:
12938   case ISD::USUBO:
12939   case ISD::SMULO:
12940   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12941   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12942   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12943   case ISD::ADDC:
12944   case ISD::ADDE:
12945   case ISD::SUBC:
12946   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12947   case ISD::ADD:                return LowerADD(Op, DAG);
12948   case ISD::SUB:                return LowerSUB(Op, DAG);
12949   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12950   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12951   }
12952 }
12953
12954 static void ReplaceATOMIC_LOAD(SDNode *Node,
12955                                   SmallVectorImpl<SDValue> &Results,
12956                                   SelectionDAG &DAG) {
12957   SDLoc dl(Node);
12958   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12959
12960   // Convert wide load -> cmpxchg8b/cmpxchg16b
12961   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12962   //        (The only way to get a 16-byte load is cmpxchg16b)
12963   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12964   SDValue Zero = DAG.getConstant(0, VT);
12965   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12966                                Node->getOperand(0),
12967                                Node->getOperand(1), Zero, Zero,
12968                                cast<AtomicSDNode>(Node)->getMemOperand(),
12969                                cast<AtomicSDNode>(Node)->getOrdering(),
12970                                cast<AtomicSDNode>(Node)->getSynchScope());
12971   Results.push_back(Swap.getValue(0));
12972   Results.push_back(Swap.getValue(1));
12973 }
12974
12975 static void
12976 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12977                         SelectionDAG &DAG, unsigned NewOp) {
12978   SDLoc dl(Node);
12979   assert (Node->getValueType(0) == MVT::i64 &&
12980           "Only know how to expand i64 atomics");
12981
12982   SDValue Chain = Node->getOperand(0);
12983   SDValue In1 = Node->getOperand(1);
12984   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12985                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12986   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12987                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12988   SDValue Ops[] = { Chain, In1, In2L, In2H };
12989   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12990   SDValue Result =
12991     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12992                             cast<MemSDNode>(Node)->getMemOperand());
12993   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12994   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12995   Results.push_back(Result.getValue(2));
12996 }
12997
12998 /// ReplaceNodeResults - Replace a node with an illegal result type
12999 /// with a new node built out of custom code.
13000 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13001                                            SmallVectorImpl<SDValue>&Results,
13002                                            SelectionDAG &DAG) const {
13003   SDLoc dl(N);
13004   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13005   switch (N->getOpcode()) {
13006   default:
13007     llvm_unreachable("Do not know how to custom type legalize this operation!");
13008   case ISD::SIGN_EXTEND_INREG:
13009   case ISD::ADDC:
13010   case ISD::ADDE:
13011   case ISD::SUBC:
13012   case ISD::SUBE:
13013     // We don't want to expand or promote these.
13014     return;
13015   case ISD::FP_TO_SINT:
13016   case ISD::FP_TO_UINT: {
13017     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13018
13019     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13020       return;
13021
13022     std::pair<SDValue,SDValue> Vals =
13023         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13024     SDValue FIST = Vals.first, StackSlot = Vals.second;
13025     if (FIST.getNode() != 0) {
13026       EVT VT = N->getValueType(0);
13027       // Return a load from the stack slot.
13028       if (StackSlot.getNode() != 0)
13029         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13030                                       MachinePointerInfo(),
13031                                       false, false, false, 0));
13032       else
13033         Results.push_back(FIST);
13034     }
13035     return;
13036   }
13037   case ISD::UINT_TO_FP: {
13038     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13039     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13040         N->getValueType(0) != MVT::v2f32)
13041       return;
13042     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13043                                  N->getOperand(0));
13044     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13045                                      MVT::f64);
13046     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13047     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13048                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13049     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13050     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13051     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13052     return;
13053   }
13054   case ISD::FP_ROUND: {
13055     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13056         return;
13057     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13058     Results.push_back(V);
13059     return;
13060   }
13061   case ISD::READCYCLECOUNTER: {
13062     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13063     SDValue TheChain = N->getOperand(0);
13064     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13065     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13066                                      rd.getValue(1));
13067     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13068                                      eax.getValue(2));
13069     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13070     SDValue Ops[] = { eax, edx };
13071     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13072                                   array_lengthof(Ops)));
13073     Results.push_back(edx.getValue(1));
13074     return;
13075   }
13076   case ISD::ATOMIC_CMP_SWAP: {
13077     EVT T = N->getValueType(0);
13078     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13079     bool Regs64bit = T == MVT::i128;
13080     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13081     SDValue cpInL, cpInH;
13082     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13083                         DAG.getConstant(0, HalfT));
13084     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13085                         DAG.getConstant(1, HalfT));
13086     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13087                              Regs64bit ? X86::RAX : X86::EAX,
13088                              cpInL, SDValue());
13089     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13090                              Regs64bit ? X86::RDX : X86::EDX,
13091                              cpInH, cpInL.getValue(1));
13092     SDValue swapInL, swapInH;
13093     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13094                           DAG.getConstant(0, HalfT));
13095     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13096                           DAG.getConstant(1, HalfT));
13097     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13098                                Regs64bit ? X86::RBX : X86::EBX,
13099                                swapInL, cpInH.getValue(1));
13100     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13101                                Regs64bit ? X86::RCX : X86::ECX,
13102                                swapInH, swapInL.getValue(1));
13103     SDValue Ops[] = { swapInH.getValue(0),
13104                       N->getOperand(1),
13105                       swapInH.getValue(1) };
13106     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13107     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13108     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13109                                   X86ISD::LCMPXCHG8_DAG;
13110     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13111                                              Ops, array_lengthof(Ops), T, MMO);
13112     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13113                                         Regs64bit ? X86::RAX : X86::EAX,
13114                                         HalfT, Result.getValue(1));
13115     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13116                                         Regs64bit ? X86::RDX : X86::EDX,
13117                                         HalfT, cpOutL.getValue(2));
13118     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13119     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13120     Results.push_back(cpOutH.getValue(1));
13121     return;
13122   }
13123   case ISD::ATOMIC_LOAD_ADD:
13124   case ISD::ATOMIC_LOAD_AND:
13125   case ISD::ATOMIC_LOAD_NAND:
13126   case ISD::ATOMIC_LOAD_OR:
13127   case ISD::ATOMIC_LOAD_SUB:
13128   case ISD::ATOMIC_LOAD_XOR:
13129   case ISD::ATOMIC_LOAD_MAX:
13130   case ISD::ATOMIC_LOAD_MIN:
13131   case ISD::ATOMIC_LOAD_UMAX:
13132   case ISD::ATOMIC_LOAD_UMIN:
13133   case ISD::ATOMIC_SWAP: {
13134     unsigned Opc;
13135     switch (N->getOpcode()) {
13136     default: llvm_unreachable("Unexpected opcode");
13137     case ISD::ATOMIC_LOAD_ADD:
13138       Opc = X86ISD::ATOMADD64_DAG;
13139       break;
13140     case ISD::ATOMIC_LOAD_AND:
13141       Opc = X86ISD::ATOMAND64_DAG;
13142       break;
13143     case ISD::ATOMIC_LOAD_NAND:
13144       Opc = X86ISD::ATOMNAND64_DAG;
13145       break;
13146     case ISD::ATOMIC_LOAD_OR:
13147       Opc = X86ISD::ATOMOR64_DAG;
13148       break;
13149     case ISD::ATOMIC_LOAD_SUB:
13150       Opc = X86ISD::ATOMSUB64_DAG;
13151       break;
13152     case ISD::ATOMIC_LOAD_XOR:
13153       Opc = X86ISD::ATOMXOR64_DAG;
13154       break;
13155     case ISD::ATOMIC_LOAD_MAX:
13156       Opc = X86ISD::ATOMMAX64_DAG;
13157       break;
13158     case ISD::ATOMIC_LOAD_MIN:
13159       Opc = X86ISD::ATOMMIN64_DAG;
13160       break;
13161     case ISD::ATOMIC_LOAD_UMAX:
13162       Opc = X86ISD::ATOMUMAX64_DAG;
13163       break;
13164     case ISD::ATOMIC_LOAD_UMIN:
13165       Opc = X86ISD::ATOMUMIN64_DAG;
13166       break;
13167     case ISD::ATOMIC_SWAP:
13168       Opc = X86ISD::ATOMSWAP64_DAG;
13169       break;
13170     }
13171     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13172     return;
13173   }
13174   case ISD::ATOMIC_LOAD:
13175     ReplaceATOMIC_LOAD(N, Results, DAG);
13176   }
13177 }
13178
13179 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13180   switch (Opcode) {
13181   default: return NULL;
13182   case X86ISD::BSF:                return "X86ISD::BSF";
13183   case X86ISD::BSR:                return "X86ISD::BSR";
13184   case X86ISD::SHLD:               return "X86ISD::SHLD";
13185   case X86ISD::SHRD:               return "X86ISD::SHRD";
13186   case X86ISD::FAND:               return "X86ISD::FAND";
13187   case X86ISD::FANDN:              return "X86ISD::FANDN";
13188   case X86ISD::FOR:                return "X86ISD::FOR";
13189   case X86ISD::FXOR:               return "X86ISD::FXOR";
13190   case X86ISD::FSRL:               return "X86ISD::FSRL";
13191   case X86ISD::FILD:               return "X86ISD::FILD";
13192   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13193   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13194   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13195   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13196   case X86ISD::FLD:                return "X86ISD::FLD";
13197   case X86ISD::FST:                return "X86ISD::FST";
13198   case X86ISD::CALL:               return "X86ISD::CALL";
13199   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13200   case X86ISD::BT:                 return "X86ISD::BT";
13201   case X86ISD::CMP:                return "X86ISD::CMP";
13202   case X86ISD::COMI:               return "X86ISD::COMI";
13203   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13204   case X86ISD::SETCC:              return "X86ISD::SETCC";
13205   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13206   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
13207   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
13208   case X86ISD::CMOV:               return "X86ISD::CMOV";
13209   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13210   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13211   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13212   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13213   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13214   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13215   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13216   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13217   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13218   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13219   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13220   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13221   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13222   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13223   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13224   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13225   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13226   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13227   case X86ISD::HADD:               return "X86ISD::HADD";
13228   case X86ISD::HSUB:               return "X86ISD::HSUB";
13229   case X86ISD::FHADD:              return "X86ISD::FHADD";
13230   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13231   case X86ISD::UMAX:               return "X86ISD::UMAX";
13232   case X86ISD::UMIN:               return "X86ISD::UMIN";
13233   case X86ISD::SMAX:               return "X86ISD::SMAX";
13234   case X86ISD::SMIN:               return "X86ISD::SMIN";
13235   case X86ISD::FMAX:               return "X86ISD::FMAX";
13236   case X86ISD::FMIN:               return "X86ISD::FMIN";
13237   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13238   case X86ISD::FMINC:              return "X86ISD::FMINC";
13239   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13240   case X86ISD::FRCP:               return "X86ISD::FRCP";
13241   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13242   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13243   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13244   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13245   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13246   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13247   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13248   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13249   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13250   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13251   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13252   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13253   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13254   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13255   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13256   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13257   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13258   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13259   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13260   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13261   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13262   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13263   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13264   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13265   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13266   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13267   case X86ISD::VSHL:               return "X86ISD::VSHL";
13268   case X86ISD::VSRL:               return "X86ISD::VSRL";
13269   case X86ISD::VSRA:               return "X86ISD::VSRA";
13270   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13271   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13272   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13273   case X86ISD::CMPP:               return "X86ISD::CMPP";
13274   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13275   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13276   case X86ISD::ADD:                return "X86ISD::ADD";
13277   case X86ISD::SUB:                return "X86ISD::SUB";
13278   case X86ISD::ADC:                return "X86ISD::ADC";
13279   case X86ISD::SBB:                return "X86ISD::SBB";
13280   case X86ISD::SMUL:               return "X86ISD::SMUL";
13281   case X86ISD::UMUL:               return "X86ISD::UMUL";
13282   case X86ISD::INC:                return "X86ISD::INC";
13283   case X86ISD::DEC:                return "X86ISD::DEC";
13284   case X86ISD::OR:                 return "X86ISD::OR";
13285   case X86ISD::XOR:                return "X86ISD::XOR";
13286   case X86ISD::AND:                return "X86ISD::AND";
13287   case X86ISD::BLSI:               return "X86ISD::BLSI";
13288   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13289   case X86ISD::BLSR:               return "X86ISD::BLSR";
13290   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13291   case X86ISD::PTEST:              return "X86ISD::PTEST";
13292   case X86ISD::TESTP:              return "X86ISD::TESTP";
13293   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13294   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13295   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13296   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13297   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13298   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13299   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13300   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13301   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13302   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13303   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13304   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13305   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13306   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13307   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13308   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13309   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13310   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13311   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
13312   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13313   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13314   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13315   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
13316   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13317   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13318   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13319   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13320   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13321   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13322   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13323   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13324   case X86ISD::SAHF:               return "X86ISD::SAHF";
13325   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13326   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13327   case X86ISD::FMADD:              return "X86ISD::FMADD";
13328   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13329   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13330   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13331   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13332   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13333   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13334   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13335   case X86ISD::XTEST:              return "X86ISD::XTEST";
13336   }
13337 }
13338
13339 // isLegalAddressingMode - Return true if the addressing mode represented
13340 // by AM is legal for this target, for a load/store of the specified type.
13341 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13342                                               Type *Ty) const {
13343   // X86 supports extremely general addressing modes.
13344   CodeModel::Model M = getTargetMachine().getCodeModel();
13345   Reloc::Model R = getTargetMachine().getRelocationModel();
13346
13347   // X86 allows a sign-extended 32-bit immediate field as a displacement.
13348   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13349     return false;
13350
13351   if (AM.BaseGV) {
13352     unsigned GVFlags =
13353       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13354
13355     // If a reference to this global requires an extra load, we can't fold it.
13356     if (isGlobalStubReference(GVFlags))
13357       return false;
13358
13359     // If BaseGV requires a register for the PIC base, we cannot also have a
13360     // BaseReg specified.
13361     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13362       return false;
13363
13364     // If lower 4G is not available, then we must use rip-relative addressing.
13365     if ((M != CodeModel::Small || R != Reloc::Static) &&
13366         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13367       return false;
13368   }
13369
13370   switch (AM.Scale) {
13371   case 0:
13372   case 1:
13373   case 2:
13374   case 4:
13375   case 8:
13376     // These scales always work.
13377     break;
13378   case 3:
13379   case 5:
13380   case 9:
13381     // These scales are formed with basereg+scalereg.  Only accept if there is
13382     // no basereg yet.
13383     if (AM.HasBaseReg)
13384       return false;
13385     break;
13386   default:  // Other stuff never works.
13387     return false;
13388   }
13389
13390   return true;
13391 }
13392
13393 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13394   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13395     return false;
13396   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13397   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13398   return NumBits1 > NumBits2;
13399 }
13400
13401 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13402   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13403     return false;
13404
13405   if (!isTypeLegal(EVT::getEVT(Ty1)))
13406     return false;
13407
13408   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13409
13410   // Assuming the caller doesn't have a zeroext or signext return parameter,
13411   // truncation all the way down to i1 is valid.
13412   return true;
13413 }
13414
13415 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13416   return isInt<32>(Imm);
13417 }
13418
13419 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13420   // Can also use sub to handle negated immediates.
13421   return isInt<32>(Imm);
13422 }
13423
13424 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13425   if (!VT1.isInteger() || !VT2.isInteger())
13426     return false;
13427   unsigned NumBits1 = VT1.getSizeInBits();
13428   unsigned NumBits2 = VT2.getSizeInBits();
13429   return NumBits1 > NumBits2;
13430 }
13431
13432 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13433   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13434   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13435 }
13436
13437 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13438   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13439   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13440 }
13441
13442 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13443   EVT VT1 = Val.getValueType();
13444   if (isZExtFree(VT1, VT2))
13445     return true;
13446
13447   if (Val.getOpcode() != ISD::LOAD)
13448     return false;
13449
13450   if (!VT1.isSimple() || !VT1.isInteger() ||
13451       !VT2.isSimple() || !VT2.isInteger())
13452     return false;
13453
13454   switch (VT1.getSimpleVT().SimpleTy) {
13455   default: break;
13456   case MVT::i8:
13457   case MVT::i16:
13458   case MVT::i32:
13459     // X86 has 8, 16, and 32-bit zero-extending loads.
13460     return true;
13461   }
13462
13463   return false;
13464 }
13465
13466 bool
13467 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13468   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13469     return false;
13470
13471   VT = VT.getScalarType();
13472
13473   if (!VT.isSimple())
13474     return false;
13475
13476   switch (VT.getSimpleVT().SimpleTy) {
13477   case MVT::f32:
13478   case MVT::f64:
13479     return true;
13480   default:
13481     break;
13482   }
13483
13484   return false;
13485 }
13486
13487 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13488   // i16 instructions are longer (0x66 prefix) and potentially slower.
13489   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13490 }
13491
13492 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13493 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13494 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13495 /// are assumed to be legal.
13496 bool
13497 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13498                                       EVT VT) const {
13499   // Very little shuffling can be done for 64-bit vectors right now.
13500   if (VT.getSizeInBits() == 64)
13501     return false;
13502
13503   // FIXME: pshufb, blends, shifts.
13504   return (VT.getVectorNumElements() == 2 ||
13505           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13506           isMOVLMask(M, VT) ||
13507           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
13508           isPSHUFDMask(M, VT) ||
13509           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
13510           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
13511           isPALIGNRMask(M, VT, Subtarget) ||
13512           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13513           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13514           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13515           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13516 }
13517
13518 bool
13519 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13520                                           EVT VT) const {
13521   unsigned NumElts = VT.getVectorNumElements();
13522   // FIXME: This collection of masks seems suspect.
13523   if (NumElts == 2)
13524     return true;
13525   if (NumElts == 4 && VT.is128BitVector()) {
13526     return (isMOVLMask(Mask, VT)  ||
13527             isCommutedMOVLMask(Mask, VT, true) ||
13528             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13529             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13530   }
13531   return false;
13532 }
13533
13534 //===----------------------------------------------------------------------===//
13535 //                           X86 Scheduler Hooks
13536 //===----------------------------------------------------------------------===//
13537
13538 /// Utility function to emit xbegin specifying the start of an RTM region.
13539 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13540                                      const TargetInstrInfo *TII) {
13541   DebugLoc DL = MI->getDebugLoc();
13542
13543   const BasicBlock *BB = MBB->getBasicBlock();
13544   MachineFunction::iterator I = MBB;
13545   ++I;
13546
13547   // For the v = xbegin(), we generate
13548   //
13549   // thisMBB:
13550   //  xbegin sinkMBB
13551   //
13552   // mainMBB:
13553   //  eax = -1
13554   //
13555   // sinkMBB:
13556   //  v = eax
13557
13558   MachineBasicBlock *thisMBB = MBB;
13559   MachineFunction *MF = MBB->getParent();
13560   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13561   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13562   MF->insert(I, mainMBB);
13563   MF->insert(I, sinkMBB);
13564
13565   // Transfer the remainder of BB and its successor edges to sinkMBB.
13566   sinkMBB->splice(sinkMBB->begin(), MBB,
13567                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13568   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13569
13570   // thisMBB:
13571   //  xbegin sinkMBB
13572   //  # fallthrough to mainMBB
13573   //  # abortion to sinkMBB
13574   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13575   thisMBB->addSuccessor(mainMBB);
13576   thisMBB->addSuccessor(sinkMBB);
13577
13578   // mainMBB:
13579   //  EAX = -1
13580   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13581   mainMBB->addSuccessor(sinkMBB);
13582
13583   // sinkMBB:
13584   // EAX is live into the sinkMBB
13585   sinkMBB->addLiveIn(X86::EAX);
13586   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13587           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13588     .addReg(X86::EAX);
13589
13590   MI->eraseFromParent();
13591   return sinkMBB;
13592 }
13593
13594 // Get CMPXCHG opcode for the specified data type.
13595 static unsigned getCmpXChgOpcode(EVT VT) {
13596   switch (VT.getSimpleVT().SimpleTy) {
13597   case MVT::i8:  return X86::LCMPXCHG8;
13598   case MVT::i16: return X86::LCMPXCHG16;
13599   case MVT::i32: return X86::LCMPXCHG32;
13600   case MVT::i64: return X86::LCMPXCHG64;
13601   default:
13602     break;
13603   }
13604   llvm_unreachable("Invalid operand size!");
13605 }
13606
13607 // Get LOAD opcode for the specified data type.
13608 static unsigned getLoadOpcode(EVT VT) {
13609   switch (VT.getSimpleVT().SimpleTy) {
13610   case MVT::i8:  return X86::MOV8rm;
13611   case MVT::i16: return X86::MOV16rm;
13612   case MVT::i32: return X86::MOV32rm;
13613   case MVT::i64: return X86::MOV64rm;
13614   default:
13615     break;
13616   }
13617   llvm_unreachable("Invalid operand size!");
13618 }
13619
13620 // Get opcode of the non-atomic one from the specified atomic instruction.
13621 static unsigned getNonAtomicOpcode(unsigned Opc) {
13622   switch (Opc) {
13623   case X86::ATOMAND8:  return X86::AND8rr;
13624   case X86::ATOMAND16: return X86::AND16rr;
13625   case X86::ATOMAND32: return X86::AND32rr;
13626   case X86::ATOMAND64: return X86::AND64rr;
13627   case X86::ATOMOR8:   return X86::OR8rr;
13628   case X86::ATOMOR16:  return X86::OR16rr;
13629   case X86::ATOMOR32:  return X86::OR32rr;
13630   case X86::ATOMOR64:  return X86::OR64rr;
13631   case X86::ATOMXOR8:  return X86::XOR8rr;
13632   case X86::ATOMXOR16: return X86::XOR16rr;
13633   case X86::ATOMXOR32: return X86::XOR32rr;
13634   case X86::ATOMXOR64: return X86::XOR64rr;
13635   }
13636   llvm_unreachable("Unhandled atomic-load-op opcode!");
13637 }
13638
13639 // Get opcode of the non-atomic one from the specified atomic instruction with
13640 // extra opcode.
13641 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13642                                                unsigned &ExtraOpc) {
13643   switch (Opc) {
13644   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13645   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13646   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13647   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13648   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13649   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13650   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13651   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13652   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13653   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13654   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13655   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13656   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13657   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13658   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13659   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13660   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13661   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13662   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13663   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13664   }
13665   llvm_unreachable("Unhandled atomic-load-op opcode!");
13666 }
13667
13668 // Get opcode of the non-atomic one from the specified atomic instruction for
13669 // 64-bit data type on 32-bit target.
13670 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13671   switch (Opc) {
13672   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13673   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13674   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13675   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13676   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13677   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13678   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13679   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13680   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13681   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13682   }
13683   llvm_unreachable("Unhandled atomic-load-op opcode!");
13684 }
13685
13686 // Get opcode of the non-atomic one from the specified atomic instruction for
13687 // 64-bit data type on 32-bit target with extra opcode.
13688 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13689                                                    unsigned &HiOpc,
13690                                                    unsigned &ExtraOpc) {
13691   switch (Opc) {
13692   case X86::ATOMNAND6432:
13693     ExtraOpc = X86::NOT32r;
13694     HiOpc = X86::AND32rr;
13695     return X86::AND32rr;
13696   }
13697   llvm_unreachable("Unhandled atomic-load-op opcode!");
13698 }
13699
13700 // Get pseudo CMOV opcode from the specified data type.
13701 static unsigned getPseudoCMOVOpc(EVT VT) {
13702   switch (VT.getSimpleVT().SimpleTy) {
13703   case MVT::i8:  return X86::CMOV_GR8;
13704   case MVT::i16: return X86::CMOV_GR16;
13705   case MVT::i32: return X86::CMOV_GR32;
13706   default:
13707     break;
13708   }
13709   llvm_unreachable("Unknown CMOV opcode!");
13710 }
13711
13712 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13713 // They will be translated into a spin-loop or compare-exchange loop from
13714 //
13715 //    ...
13716 //    dst = atomic-fetch-op MI.addr, MI.val
13717 //    ...
13718 //
13719 // to
13720 //
13721 //    ...
13722 //    t1 = LOAD MI.addr
13723 // loop:
13724 //    t4 = phi(t1, t3 / loop)
13725 //    t2 = OP MI.val, t4
13726 //    EAX = t4
13727 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13728 //    t3 = EAX
13729 //    JNE loop
13730 // sink:
13731 //    dst = t3
13732 //    ...
13733 MachineBasicBlock *
13734 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13735                                        MachineBasicBlock *MBB) const {
13736   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13737   DebugLoc DL = MI->getDebugLoc();
13738
13739   MachineFunction *MF = MBB->getParent();
13740   MachineRegisterInfo &MRI = MF->getRegInfo();
13741
13742   const BasicBlock *BB = MBB->getBasicBlock();
13743   MachineFunction::iterator I = MBB;
13744   ++I;
13745
13746   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13747          "Unexpected number of operands");
13748
13749   assert(MI->hasOneMemOperand() &&
13750          "Expected atomic-load-op to have one memoperand");
13751
13752   // Memory Reference
13753   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13754   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13755
13756   unsigned DstReg, SrcReg;
13757   unsigned MemOpndSlot;
13758
13759   unsigned CurOp = 0;
13760
13761   DstReg = MI->getOperand(CurOp++).getReg();
13762   MemOpndSlot = CurOp;
13763   CurOp += X86::AddrNumOperands;
13764   SrcReg = MI->getOperand(CurOp++).getReg();
13765
13766   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13767   MVT::SimpleValueType VT = *RC->vt_begin();
13768   unsigned t1 = MRI.createVirtualRegister(RC);
13769   unsigned t2 = MRI.createVirtualRegister(RC);
13770   unsigned t3 = MRI.createVirtualRegister(RC);
13771   unsigned t4 = MRI.createVirtualRegister(RC);
13772   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13773
13774   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13775   unsigned LOADOpc = getLoadOpcode(VT);
13776
13777   // For the atomic load-arith operator, we generate
13778   //
13779   //  thisMBB:
13780   //    t1 = LOAD [MI.addr]
13781   //  mainMBB:
13782   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13783   //    t1 = OP MI.val, EAX
13784   //    EAX = t4
13785   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13786   //    t3 = EAX
13787   //    JNE mainMBB
13788   //  sinkMBB:
13789   //    dst = t3
13790
13791   MachineBasicBlock *thisMBB = MBB;
13792   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13793   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13794   MF->insert(I, mainMBB);
13795   MF->insert(I, sinkMBB);
13796
13797   MachineInstrBuilder MIB;
13798
13799   // Transfer the remainder of BB and its successor edges to sinkMBB.
13800   sinkMBB->splice(sinkMBB->begin(), MBB,
13801                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13802   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13803
13804   // thisMBB:
13805   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13806   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13807     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13808     if (NewMO.isReg())
13809       NewMO.setIsKill(false);
13810     MIB.addOperand(NewMO);
13811   }
13812   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13813     unsigned flags = (*MMOI)->getFlags();
13814     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13815     MachineMemOperand *MMO =
13816       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13817                                (*MMOI)->getSize(),
13818                                (*MMOI)->getBaseAlignment(),
13819                                (*MMOI)->getTBAAInfo(),
13820                                (*MMOI)->getRanges());
13821     MIB.addMemOperand(MMO);
13822   }
13823
13824   thisMBB->addSuccessor(mainMBB);
13825
13826   // mainMBB:
13827   MachineBasicBlock *origMainMBB = mainMBB;
13828
13829   // Add a PHI.
13830   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13831                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13832
13833   unsigned Opc = MI->getOpcode();
13834   switch (Opc) {
13835   default:
13836     llvm_unreachable("Unhandled atomic-load-op opcode!");
13837   case X86::ATOMAND8:
13838   case X86::ATOMAND16:
13839   case X86::ATOMAND32:
13840   case X86::ATOMAND64:
13841   case X86::ATOMOR8:
13842   case X86::ATOMOR16:
13843   case X86::ATOMOR32:
13844   case X86::ATOMOR64:
13845   case X86::ATOMXOR8:
13846   case X86::ATOMXOR16:
13847   case X86::ATOMXOR32:
13848   case X86::ATOMXOR64: {
13849     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13850     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13851       .addReg(t4);
13852     break;
13853   }
13854   case X86::ATOMNAND8:
13855   case X86::ATOMNAND16:
13856   case X86::ATOMNAND32:
13857   case X86::ATOMNAND64: {
13858     unsigned Tmp = MRI.createVirtualRegister(RC);
13859     unsigned NOTOpc;
13860     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13861     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13862       .addReg(t4);
13863     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13864     break;
13865   }
13866   case X86::ATOMMAX8:
13867   case X86::ATOMMAX16:
13868   case X86::ATOMMAX32:
13869   case X86::ATOMMAX64:
13870   case X86::ATOMMIN8:
13871   case X86::ATOMMIN16:
13872   case X86::ATOMMIN32:
13873   case X86::ATOMMIN64:
13874   case X86::ATOMUMAX8:
13875   case X86::ATOMUMAX16:
13876   case X86::ATOMUMAX32:
13877   case X86::ATOMUMAX64:
13878   case X86::ATOMUMIN8:
13879   case X86::ATOMUMIN16:
13880   case X86::ATOMUMIN32:
13881   case X86::ATOMUMIN64: {
13882     unsigned CMPOpc;
13883     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13884
13885     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13886       .addReg(SrcReg)
13887       .addReg(t4);
13888
13889     if (Subtarget->hasCMov()) {
13890       if (VT != MVT::i8) {
13891         // Native support
13892         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13893           .addReg(SrcReg)
13894           .addReg(t4);
13895       } else {
13896         // Promote i8 to i32 to use CMOV32
13897         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13898         const TargetRegisterClass *RC32 =
13899           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13900         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13901         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13902         unsigned Tmp = MRI.createVirtualRegister(RC32);
13903
13904         unsigned Undef = MRI.createVirtualRegister(RC32);
13905         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13906
13907         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13908           .addReg(Undef)
13909           .addReg(SrcReg)
13910           .addImm(X86::sub_8bit);
13911         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13912           .addReg(Undef)
13913           .addReg(t4)
13914           .addImm(X86::sub_8bit);
13915
13916         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13917           .addReg(SrcReg32)
13918           .addReg(AccReg32);
13919
13920         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13921           .addReg(Tmp, 0, X86::sub_8bit);
13922       }
13923     } else {
13924       // Use pseudo select and lower them.
13925       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13926              "Invalid atomic-load-op transformation!");
13927       unsigned SelOpc = getPseudoCMOVOpc(VT);
13928       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13929       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13930       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13931               .addReg(SrcReg).addReg(t4)
13932               .addImm(CC);
13933       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13934       // Replace the original PHI node as mainMBB is changed after CMOV
13935       // lowering.
13936       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13937         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13938       Phi->eraseFromParent();
13939     }
13940     break;
13941   }
13942   }
13943
13944   // Copy PhyReg back from virtual register.
13945   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13946     .addReg(t4);
13947
13948   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13949   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13950     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13951     if (NewMO.isReg())
13952       NewMO.setIsKill(false);
13953     MIB.addOperand(NewMO);
13954   }
13955   MIB.addReg(t2);
13956   MIB.setMemRefs(MMOBegin, MMOEnd);
13957
13958   // Copy PhyReg back to virtual register.
13959   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13960     .addReg(PhyReg);
13961
13962   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13963
13964   mainMBB->addSuccessor(origMainMBB);
13965   mainMBB->addSuccessor(sinkMBB);
13966
13967   // sinkMBB:
13968   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13969           TII->get(TargetOpcode::COPY), DstReg)
13970     .addReg(t3);
13971
13972   MI->eraseFromParent();
13973   return sinkMBB;
13974 }
13975
13976 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13977 // instructions. They will be translated into a spin-loop or compare-exchange
13978 // loop from
13979 //
13980 //    ...
13981 //    dst = atomic-fetch-op MI.addr, MI.val
13982 //    ...
13983 //
13984 // to
13985 //
13986 //    ...
13987 //    t1L = LOAD [MI.addr + 0]
13988 //    t1H = LOAD [MI.addr + 4]
13989 // loop:
13990 //    t4L = phi(t1L, t3L / loop)
13991 //    t4H = phi(t1H, t3H / loop)
13992 //    t2L = OP MI.val.lo, t4L
13993 //    t2H = OP MI.val.hi, t4H
13994 //    EAX = t4L
13995 //    EDX = t4H
13996 //    EBX = t2L
13997 //    ECX = t2H
13998 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13999 //    t3L = EAX
14000 //    t3H = EDX
14001 //    JNE loop
14002 // sink:
14003 //    dstL = t3L
14004 //    dstH = t3H
14005 //    ...
14006 MachineBasicBlock *
14007 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14008                                            MachineBasicBlock *MBB) const {
14009   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14010   DebugLoc DL = MI->getDebugLoc();
14011
14012   MachineFunction *MF = MBB->getParent();
14013   MachineRegisterInfo &MRI = MF->getRegInfo();
14014
14015   const BasicBlock *BB = MBB->getBasicBlock();
14016   MachineFunction::iterator I = MBB;
14017   ++I;
14018
14019   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14020          "Unexpected number of operands");
14021
14022   assert(MI->hasOneMemOperand() &&
14023          "Expected atomic-load-op32 to have one memoperand");
14024
14025   // Memory Reference
14026   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14027   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14028
14029   unsigned DstLoReg, DstHiReg;
14030   unsigned SrcLoReg, SrcHiReg;
14031   unsigned MemOpndSlot;
14032
14033   unsigned CurOp = 0;
14034
14035   DstLoReg = MI->getOperand(CurOp++).getReg();
14036   DstHiReg = MI->getOperand(CurOp++).getReg();
14037   MemOpndSlot = CurOp;
14038   CurOp += X86::AddrNumOperands;
14039   SrcLoReg = MI->getOperand(CurOp++).getReg();
14040   SrcHiReg = MI->getOperand(CurOp++).getReg();
14041
14042   const TargetRegisterClass *RC = &X86::GR32RegClass;
14043   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14044
14045   unsigned t1L = MRI.createVirtualRegister(RC);
14046   unsigned t1H = MRI.createVirtualRegister(RC);
14047   unsigned t2L = MRI.createVirtualRegister(RC);
14048   unsigned t2H = MRI.createVirtualRegister(RC);
14049   unsigned t3L = MRI.createVirtualRegister(RC);
14050   unsigned t3H = MRI.createVirtualRegister(RC);
14051   unsigned t4L = MRI.createVirtualRegister(RC);
14052   unsigned t4H = MRI.createVirtualRegister(RC);
14053
14054   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14055   unsigned LOADOpc = X86::MOV32rm;
14056
14057   // For the atomic load-arith operator, we generate
14058   //
14059   //  thisMBB:
14060   //    t1L = LOAD [MI.addr + 0]
14061   //    t1H = LOAD [MI.addr + 4]
14062   //  mainMBB:
14063   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14064   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14065   //    t2L = OP MI.val.lo, t4L
14066   //    t2H = OP MI.val.hi, t4H
14067   //    EBX = t2L
14068   //    ECX = t2H
14069   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14070   //    t3L = EAX
14071   //    t3H = EDX
14072   //    JNE loop
14073   //  sinkMBB:
14074   //    dstL = t3L
14075   //    dstH = t3H
14076
14077   MachineBasicBlock *thisMBB = MBB;
14078   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14079   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14080   MF->insert(I, mainMBB);
14081   MF->insert(I, sinkMBB);
14082
14083   MachineInstrBuilder MIB;
14084
14085   // Transfer the remainder of BB and its successor edges to sinkMBB.
14086   sinkMBB->splice(sinkMBB->begin(), MBB,
14087                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14088   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14089
14090   // thisMBB:
14091   // Lo
14092   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14093   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14094     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14095     if (NewMO.isReg())
14096       NewMO.setIsKill(false);
14097     MIB.addOperand(NewMO);
14098   }
14099   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14100     unsigned flags = (*MMOI)->getFlags();
14101     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14102     MachineMemOperand *MMO =
14103       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14104                                (*MMOI)->getSize(),
14105                                (*MMOI)->getBaseAlignment(),
14106                                (*MMOI)->getTBAAInfo(),
14107                                (*MMOI)->getRanges());
14108     MIB.addMemOperand(MMO);
14109   };
14110   MachineInstr *LowMI = MIB;
14111
14112   // Hi
14113   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14114   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14115     if (i == X86::AddrDisp) {
14116       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14117     } else {
14118       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14119       if (NewMO.isReg())
14120         NewMO.setIsKill(false);
14121       MIB.addOperand(NewMO);
14122     }
14123   }
14124   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14125
14126   thisMBB->addSuccessor(mainMBB);
14127
14128   // mainMBB:
14129   MachineBasicBlock *origMainMBB = mainMBB;
14130
14131   // Add PHIs.
14132   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14133                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14134   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14135                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14136
14137   unsigned Opc = MI->getOpcode();
14138   switch (Opc) {
14139   default:
14140     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14141   case X86::ATOMAND6432:
14142   case X86::ATOMOR6432:
14143   case X86::ATOMXOR6432:
14144   case X86::ATOMADD6432:
14145   case X86::ATOMSUB6432: {
14146     unsigned HiOpc;
14147     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14148     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14149       .addReg(SrcLoReg);
14150     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14151       .addReg(SrcHiReg);
14152     break;
14153   }
14154   case X86::ATOMNAND6432: {
14155     unsigned HiOpc, NOTOpc;
14156     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14157     unsigned TmpL = MRI.createVirtualRegister(RC);
14158     unsigned TmpH = MRI.createVirtualRegister(RC);
14159     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14160       .addReg(t4L);
14161     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14162       .addReg(t4H);
14163     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14164     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14165     break;
14166   }
14167   case X86::ATOMMAX6432:
14168   case X86::ATOMMIN6432:
14169   case X86::ATOMUMAX6432:
14170   case X86::ATOMUMIN6432: {
14171     unsigned HiOpc;
14172     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14173     unsigned cL = MRI.createVirtualRegister(RC8);
14174     unsigned cH = MRI.createVirtualRegister(RC8);
14175     unsigned cL32 = MRI.createVirtualRegister(RC);
14176     unsigned cH32 = MRI.createVirtualRegister(RC);
14177     unsigned cc = MRI.createVirtualRegister(RC);
14178     // cl := cmp src_lo, lo
14179     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14180       .addReg(SrcLoReg).addReg(t4L);
14181     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14182     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14183     // ch := cmp src_hi, hi
14184     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14185       .addReg(SrcHiReg).addReg(t4H);
14186     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14187     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14188     // cc := if (src_hi == hi) ? cl : ch;
14189     if (Subtarget->hasCMov()) {
14190       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14191         .addReg(cH32).addReg(cL32);
14192     } else {
14193       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14194               .addReg(cH32).addReg(cL32)
14195               .addImm(X86::COND_E);
14196       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14197     }
14198     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14199     if (Subtarget->hasCMov()) {
14200       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14201         .addReg(SrcLoReg).addReg(t4L);
14202       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14203         .addReg(SrcHiReg).addReg(t4H);
14204     } else {
14205       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14206               .addReg(SrcLoReg).addReg(t4L)
14207               .addImm(X86::COND_NE);
14208       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14209       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14210       // 2nd CMOV lowering.
14211       mainMBB->addLiveIn(X86::EFLAGS);
14212       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14213               .addReg(SrcHiReg).addReg(t4H)
14214               .addImm(X86::COND_NE);
14215       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14216       // Replace the original PHI node as mainMBB is changed after CMOV
14217       // lowering.
14218       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14219         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14220       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14221         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14222       PhiL->eraseFromParent();
14223       PhiH->eraseFromParent();
14224     }
14225     break;
14226   }
14227   case X86::ATOMSWAP6432: {
14228     unsigned HiOpc;
14229     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14230     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14231     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14232     break;
14233   }
14234   }
14235
14236   // Copy EDX:EAX back from HiReg:LoReg
14237   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14238   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14239   // Copy ECX:EBX from t1H:t1L
14240   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14241   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14242
14243   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14244   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14245     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14246     if (NewMO.isReg())
14247       NewMO.setIsKill(false);
14248     MIB.addOperand(NewMO);
14249   }
14250   MIB.setMemRefs(MMOBegin, MMOEnd);
14251
14252   // Copy EDX:EAX back to t3H:t3L
14253   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14254   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14255
14256   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14257
14258   mainMBB->addSuccessor(origMainMBB);
14259   mainMBB->addSuccessor(sinkMBB);
14260
14261   // sinkMBB:
14262   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14263           TII->get(TargetOpcode::COPY), DstLoReg)
14264     .addReg(t3L);
14265   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14266           TII->get(TargetOpcode::COPY), DstHiReg)
14267     .addReg(t3H);
14268
14269   MI->eraseFromParent();
14270   return sinkMBB;
14271 }
14272
14273 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14274 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14275 // in the .td file.
14276 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14277                                        const TargetInstrInfo *TII) {
14278   unsigned Opc;
14279   switch (MI->getOpcode()) {
14280   default: llvm_unreachable("illegal opcode!");
14281   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14282   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14283   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14284   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14285   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14286   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14287   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14288   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14289   }
14290
14291   DebugLoc dl = MI->getDebugLoc();
14292   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14293
14294   unsigned NumArgs = MI->getNumOperands();
14295   for (unsigned i = 1; i < NumArgs; ++i) {
14296     MachineOperand &Op = MI->getOperand(i);
14297     if (!(Op.isReg() && Op.isImplicit()))
14298       MIB.addOperand(Op);
14299   }
14300   if (MI->hasOneMemOperand())
14301     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14302
14303   BuildMI(*BB, MI, dl,
14304     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14305     .addReg(X86::XMM0);
14306
14307   MI->eraseFromParent();
14308   return BB;
14309 }
14310
14311 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14312 // defs in an instruction pattern
14313 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14314                                        const TargetInstrInfo *TII) {
14315   unsigned Opc;
14316   switch (MI->getOpcode()) {
14317   default: llvm_unreachable("illegal opcode!");
14318   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14319   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14320   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14321   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14322   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14323   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14324   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14325   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14326   }
14327
14328   DebugLoc dl = MI->getDebugLoc();
14329   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14330
14331   unsigned NumArgs = MI->getNumOperands(); // remove the results
14332   for (unsigned i = 1; i < NumArgs; ++i) {
14333     MachineOperand &Op = MI->getOperand(i);
14334     if (!(Op.isReg() && Op.isImplicit()))
14335       MIB.addOperand(Op);
14336   }
14337   if (MI->hasOneMemOperand())
14338     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14339
14340   BuildMI(*BB, MI, dl,
14341     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14342     .addReg(X86::ECX);
14343
14344   MI->eraseFromParent();
14345   return BB;
14346 }
14347
14348 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14349                                        const TargetInstrInfo *TII,
14350                                        const X86Subtarget* Subtarget) {
14351   DebugLoc dl = MI->getDebugLoc();
14352
14353   // Address into RAX/EAX, other two args into ECX, EDX.
14354   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14355   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14356   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14357   for (int i = 0; i < X86::AddrNumOperands; ++i)
14358     MIB.addOperand(MI->getOperand(i));
14359
14360   unsigned ValOps = X86::AddrNumOperands;
14361   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14362     .addReg(MI->getOperand(ValOps).getReg());
14363   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14364     .addReg(MI->getOperand(ValOps+1).getReg());
14365
14366   // The instruction doesn't actually take any operands though.
14367   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14368
14369   MI->eraseFromParent(); // The pseudo is gone now.
14370   return BB;
14371 }
14372
14373 MachineBasicBlock *
14374 X86TargetLowering::EmitVAARG64WithCustomInserter(
14375                    MachineInstr *MI,
14376                    MachineBasicBlock *MBB) const {
14377   // Emit va_arg instruction on X86-64.
14378
14379   // Operands to this pseudo-instruction:
14380   // 0  ) Output        : destination address (reg)
14381   // 1-5) Input         : va_list address (addr, i64mem)
14382   // 6  ) ArgSize       : Size (in bytes) of vararg type
14383   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14384   // 8  ) Align         : Alignment of type
14385   // 9  ) EFLAGS (implicit-def)
14386
14387   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14388   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14389
14390   unsigned DestReg = MI->getOperand(0).getReg();
14391   MachineOperand &Base = MI->getOperand(1);
14392   MachineOperand &Scale = MI->getOperand(2);
14393   MachineOperand &Index = MI->getOperand(3);
14394   MachineOperand &Disp = MI->getOperand(4);
14395   MachineOperand &Segment = MI->getOperand(5);
14396   unsigned ArgSize = MI->getOperand(6).getImm();
14397   unsigned ArgMode = MI->getOperand(7).getImm();
14398   unsigned Align = MI->getOperand(8).getImm();
14399
14400   // Memory Reference
14401   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14402   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14403   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14404
14405   // Machine Information
14406   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14407   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14408   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14409   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14410   DebugLoc DL = MI->getDebugLoc();
14411
14412   // struct va_list {
14413   //   i32   gp_offset
14414   //   i32   fp_offset
14415   //   i64   overflow_area (address)
14416   //   i64   reg_save_area (address)
14417   // }
14418   // sizeof(va_list) = 24
14419   // alignment(va_list) = 8
14420
14421   unsigned TotalNumIntRegs = 6;
14422   unsigned TotalNumXMMRegs = 8;
14423   bool UseGPOffset = (ArgMode == 1);
14424   bool UseFPOffset = (ArgMode == 2);
14425   unsigned MaxOffset = TotalNumIntRegs * 8 +
14426                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14427
14428   /* Align ArgSize to a multiple of 8 */
14429   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14430   bool NeedsAlign = (Align > 8);
14431
14432   MachineBasicBlock *thisMBB = MBB;
14433   MachineBasicBlock *overflowMBB;
14434   MachineBasicBlock *offsetMBB;
14435   MachineBasicBlock *endMBB;
14436
14437   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
14438   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
14439   unsigned OffsetReg = 0;
14440
14441   if (!UseGPOffset && !UseFPOffset) {
14442     // If we only pull from the overflow region, we don't create a branch.
14443     // We don't need to alter control flow.
14444     OffsetDestReg = 0; // unused
14445     OverflowDestReg = DestReg;
14446
14447     offsetMBB = NULL;
14448     overflowMBB = thisMBB;
14449     endMBB = thisMBB;
14450   } else {
14451     // First emit code to check if gp_offset (or fp_offset) is below the bound.
14452     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14453     // If not, pull from overflow_area. (branch to overflowMBB)
14454     //
14455     //       thisMBB
14456     //         |     .
14457     //         |        .
14458     //     offsetMBB   overflowMBB
14459     //         |        .
14460     //         |     .
14461     //        endMBB
14462
14463     // Registers for the PHI in endMBB
14464     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14465     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14466
14467     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14468     MachineFunction *MF = MBB->getParent();
14469     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14470     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14471     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14472
14473     MachineFunction::iterator MBBIter = MBB;
14474     ++MBBIter;
14475
14476     // Insert the new basic blocks
14477     MF->insert(MBBIter, offsetMBB);
14478     MF->insert(MBBIter, overflowMBB);
14479     MF->insert(MBBIter, endMBB);
14480
14481     // Transfer the remainder of MBB and its successor edges to endMBB.
14482     endMBB->splice(endMBB->begin(), thisMBB,
14483                     llvm::next(MachineBasicBlock::iterator(MI)),
14484                     thisMBB->end());
14485     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14486
14487     // Make offsetMBB and overflowMBB successors of thisMBB
14488     thisMBB->addSuccessor(offsetMBB);
14489     thisMBB->addSuccessor(overflowMBB);
14490
14491     // endMBB is a successor of both offsetMBB and overflowMBB
14492     offsetMBB->addSuccessor(endMBB);
14493     overflowMBB->addSuccessor(endMBB);
14494
14495     // Load the offset value into a register
14496     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14497     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14498       .addOperand(Base)
14499       .addOperand(Scale)
14500       .addOperand(Index)
14501       .addDisp(Disp, UseFPOffset ? 4 : 0)
14502       .addOperand(Segment)
14503       .setMemRefs(MMOBegin, MMOEnd);
14504
14505     // Check if there is enough room left to pull this argument.
14506     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14507       .addReg(OffsetReg)
14508       .addImm(MaxOffset + 8 - ArgSizeA8);
14509
14510     // Branch to "overflowMBB" if offset >= max
14511     // Fall through to "offsetMBB" otherwise
14512     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14513       .addMBB(overflowMBB);
14514   }
14515
14516   // In offsetMBB, emit code to use the reg_save_area.
14517   if (offsetMBB) {
14518     assert(OffsetReg != 0);
14519
14520     // Read the reg_save_area address.
14521     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14522     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14523       .addOperand(Base)
14524       .addOperand(Scale)
14525       .addOperand(Index)
14526       .addDisp(Disp, 16)
14527       .addOperand(Segment)
14528       .setMemRefs(MMOBegin, MMOEnd);
14529
14530     // Zero-extend the offset
14531     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14532       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14533         .addImm(0)
14534         .addReg(OffsetReg)
14535         .addImm(X86::sub_32bit);
14536
14537     // Add the offset to the reg_save_area to get the final address.
14538     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14539       .addReg(OffsetReg64)
14540       .addReg(RegSaveReg);
14541
14542     // Compute the offset for the next argument
14543     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14544     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14545       .addReg(OffsetReg)
14546       .addImm(UseFPOffset ? 16 : 8);
14547
14548     // Store it back into the va_list.
14549     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14550       .addOperand(Base)
14551       .addOperand(Scale)
14552       .addOperand(Index)
14553       .addDisp(Disp, UseFPOffset ? 4 : 0)
14554       .addOperand(Segment)
14555       .addReg(NextOffsetReg)
14556       .setMemRefs(MMOBegin, MMOEnd);
14557
14558     // Jump to endMBB
14559     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14560       .addMBB(endMBB);
14561   }
14562
14563   //
14564   // Emit code to use overflow area
14565   //
14566
14567   // Load the overflow_area address into a register.
14568   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14569   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14570     .addOperand(Base)
14571     .addOperand(Scale)
14572     .addOperand(Index)
14573     .addDisp(Disp, 8)
14574     .addOperand(Segment)
14575     .setMemRefs(MMOBegin, MMOEnd);
14576
14577   // If we need to align it, do so. Otherwise, just copy the address
14578   // to OverflowDestReg.
14579   if (NeedsAlign) {
14580     // Align the overflow address
14581     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14582     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14583
14584     // aligned_addr = (addr + (align-1)) & ~(align-1)
14585     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14586       .addReg(OverflowAddrReg)
14587       .addImm(Align-1);
14588
14589     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14590       .addReg(TmpReg)
14591       .addImm(~(uint64_t)(Align-1));
14592   } else {
14593     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14594       .addReg(OverflowAddrReg);
14595   }
14596
14597   // Compute the next overflow address after this argument.
14598   // (the overflow address should be kept 8-byte aligned)
14599   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14600   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14601     .addReg(OverflowDestReg)
14602     .addImm(ArgSizeA8);
14603
14604   // Store the new overflow address.
14605   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14606     .addOperand(Base)
14607     .addOperand(Scale)
14608     .addOperand(Index)
14609     .addDisp(Disp, 8)
14610     .addOperand(Segment)
14611     .addReg(NextAddrReg)
14612     .setMemRefs(MMOBegin, MMOEnd);
14613
14614   // If we branched, emit the PHI to the front of endMBB.
14615   if (offsetMBB) {
14616     BuildMI(*endMBB, endMBB->begin(), DL,
14617             TII->get(X86::PHI), DestReg)
14618       .addReg(OffsetDestReg).addMBB(offsetMBB)
14619       .addReg(OverflowDestReg).addMBB(overflowMBB);
14620   }
14621
14622   // Erase the pseudo instruction
14623   MI->eraseFromParent();
14624
14625   return endMBB;
14626 }
14627
14628 MachineBasicBlock *
14629 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14630                                                  MachineInstr *MI,
14631                                                  MachineBasicBlock *MBB) const {
14632   // Emit code to save XMM registers to the stack. The ABI says that the
14633   // number of registers to save is given in %al, so it's theoretically
14634   // possible to do an indirect jump trick to avoid saving all of them,
14635   // however this code takes a simpler approach and just executes all
14636   // of the stores if %al is non-zero. It's less code, and it's probably
14637   // easier on the hardware branch predictor, and stores aren't all that
14638   // expensive anyway.
14639
14640   // Create the new basic blocks. One block contains all the XMM stores,
14641   // and one block is the final destination regardless of whether any
14642   // stores were performed.
14643   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14644   MachineFunction *F = MBB->getParent();
14645   MachineFunction::iterator MBBIter = MBB;
14646   ++MBBIter;
14647   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14648   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14649   F->insert(MBBIter, XMMSaveMBB);
14650   F->insert(MBBIter, EndMBB);
14651
14652   // Transfer the remainder of MBB and its successor edges to EndMBB.
14653   EndMBB->splice(EndMBB->begin(), MBB,
14654                  llvm::next(MachineBasicBlock::iterator(MI)),
14655                  MBB->end());
14656   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14657
14658   // The original block will now fall through to the XMM save block.
14659   MBB->addSuccessor(XMMSaveMBB);
14660   // The XMMSaveMBB will fall through to the end block.
14661   XMMSaveMBB->addSuccessor(EndMBB);
14662
14663   // Now add the instructions.
14664   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14665   DebugLoc DL = MI->getDebugLoc();
14666
14667   unsigned CountReg = MI->getOperand(0).getReg();
14668   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14669   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14670
14671   if (!Subtarget->isTargetWin64()) {
14672     // If %al is 0, branch around the XMM save block.
14673     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14674     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14675     MBB->addSuccessor(EndMBB);
14676   }
14677
14678   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14679   // In the XMM save block, save all the XMM argument registers.
14680   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14681     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14682     MachineMemOperand *MMO =
14683       F->getMachineMemOperand(
14684           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14685         MachineMemOperand::MOStore,
14686         /*Size=*/16, /*Align=*/16);
14687     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14688       .addFrameIndex(RegSaveFrameIndex)
14689       .addImm(/*Scale=*/1)
14690       .addReg(/*IndexReg=*/0)
14691       .addImm(/*Disp=*/Offset)
14692       .addReg(/*Segment=*/0)
14693       .addReg(MI->getOperand(i).getReg())
14694       .addMemOperand(MMO);
14695   }
14696
14697   MI->eraseFromParent();   // The pseudo instruction is gone now.
14698
14699   return EndMBB;
14700 }
14701
14702 // The EFLAGS operand of SelectItr might be missing a kill marker
14703 // because there were multiple uses of EFLAGS, and ISel didn't know
14704 // which to mark. Figure out whether SelectItr should have had a
14705 // kill marker, and set it if it should. Returns the correct kill
14706 // marker value.
14707 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14708                                      MachineBasicBlock* BB,
14709                                      const TargetRegisterInfo* TRI) {
14710   // Scan forward through BB for a use/def of EFLAGS.
14711   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14712   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14713     const MachineInstr& mi = *miI;
14714     if (mi.readsRegister(X86::EFLAGS))
14715       return false;
14716     if (mi.definesRegister(X86::EFLAGS))
14717       break; // Should have kill-flag - update below.
14718   }
14719
14720   // If we hit the end of the block, check whether EFLAGS is live into a
14721   // successor.
14722   if (miI == BB->end()) {
14723     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14724                                           sEnd = BB->succ_end();
14725          sItr != sEnd; ++sItr) {
14726       MachineBasicBlock* succ = *sItr;
14727       if (succ->isLiveIn(X86::EFLAGS))
14728         return false;
14729     }
14730   }
14731
14732   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14733   // out. SelectMI should have a kill flag on EFLAGS.
14734   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14735   return true;
14736 }
14737
14738 MachineBasicBlock *
14739 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14740                                      MachineBasicBlock *BB) const {
14741   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14742   DebugLoc DL = MI->getDebugLoc();
14743
14744   // To "insert" a SELECT_CC instruction, we actually have to insert the
14745   // diamond control-flow pattern.  The incoming instruction knows the
14746   // destination vreg to set, the condition code register to branch on, the
14747   // true/false values to select between, and a branch opcode to use.
14748   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14749   MachineFunction::iterator It = BB;
14750   ++It;
14751
14752   //  thisMBB:
14753   //  ...
14754   //   TrueVal = ...
14755   //   cmpTY ccX, r1, r2
14756   //   bCC copy1MBB
14757   //   fallthrough --> copy0MBB
14758   MachineBasicBlock *thisMBB = BB;
14759   MachineFunction *F = BB->getParent();
14760   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14761   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14762   F->insert(It, copy0MBB);
14763   F->insert(It, sinkMBB);
14764
14765   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14766   // live into the sink and copy blocks.
14767   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14768   if (!MI->killsRegister(X86::EFLAGS) &&
14769       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14770     copy0MBB->addLiveIn(X86::EFLAGS);
14771     sinkMBB->addLiveIn(X86::EFLAGS);
14772   }
14773
14774   // Transfer the remainder of BB and its successor edges to sinkMBB.
14775   sinkMBB->splice(sinkMBB->begin(), BB,
14776                   llvm::next(MachineBasicBlock::iterator(MI)),
14777                   BB->end());
14778   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14779
14780   // Add the true and fallthrough blocks as its successors.
14781   BB->addSuccessor(copy0MBB);
14782   BB->addSuccessor(sinkMBB);
14783
14784   // Create the conditional branch instruction.
14785   unsigned Opc =
14786     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14787   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14788
14789   //  copy0MBB:
14790   //   %FalseValue = ...
14791   //   # fallthrough to sinkMBB
14792   copy0MBB->addSuccessor(sinkMBB);
14793
14794   //  sinkMBB:
14795   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14796   //  ...
14797   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14798           TII->get(X86::PHI), MI->getOperand(0).getReg())
14799     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14800     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14801
14802   MI->eraseFromParent();   // The pseudo instruction is gone now.
14803   return sinkMBB;
14804 }
14805
14806 MachineBasicBlock *
14807 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14808                                         bool Is64Bit) const {
14809   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14810   DebugLoc DL = MI->getDebugLoc();
14811   MachineFunction *MF = BB->getParent();
14812   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14813
14814   assert(getTargetMachine().Options.EnableSegmentedStacks);
14815
14816   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14817   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14818
14819   // BB:
14820   //  ... [Till the alloca]
14821   // If stacklet is not large enough, jump to mallocMBB
14822   //
14823   // bumpMBB:
14824   //  Allocate by subtracting from RSP
14825   //  Jump to continueMBB
14826   //
14827   // mallocMBB:
14828   //  Allocate by call to runtime
14829   //
14830   // continueMBB:
14831   //  ...
14832   //  [rest of original BB]
14833   //
14834
14835   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14836   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14837   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14838
14839   MachineRegisterInfo &MRI = MF->getRegInfo();
14840   const TargetRegisterClass *AddrRegClass =
14841     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14842
14843   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14844     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14845     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14846     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14847     sizeVReg = MI->getOperand(1).getReg(),
14848     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14849
14850   MachineFunction::iterator MBBIter = BB;
14851   ++MBBIter;
14852
14853   MF->insert(MBBIter, bumpMBB);
14854   MF->insert(MBBIter, mallocMBB);
14855   MF->insert(MBBIter, continueMBB);
14856
14857   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14858                       (MachineBasicBlock::iterator(MI)), BB->end());
14859   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14860
14861   // Add code to the main basic block to check if the stack limit has been hit,
14862   // and if so, jump to mallocMBB otherwise to bumpMBB.
14863   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14864   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14865     .addReg(tmpSPVReg).addReg(sizeVReg);
14866   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14867     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14868     .addReg(SPLimitVReg);
14869   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14870
14871   // bumpMBB simply decreases the stack pointer, since we know the current
14872   // stacklet has enough space.
14873   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14874     .addReg(SPLimitVReg);
14875   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14876     .addReg(SPLimitVReg);
14877   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14878
14879   // Calls into a routine in libgcc to allocate more space from the heap.
14880   const uint32_t *RegMask =
14881     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14882   if (Is64Bit) {
14883     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14884       .addReg(sizeVReg);
14885     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14886       .addExternalSymbol("__morestack_allocate_stack_space")
14887       .addRegMask(RegMask)
14888       .addReg(X86::RDI, RegState::Implicit)
14889       .addReg(X86::RAX, RegState::ImplicitDefine);
14890   } else {
14891     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14892       .addImm(12);
14893     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14894     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14895       .addExternalSymbol("__morestack_allocate_stack_space")
14896       .addRegMask(RegMask)
14897       .addReg(X86::EAX, RegState::ImplicitDefine);
14898   }
14899
14900   if (!Is64Bit)
14901     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14902       .addImm(16);
14903
14904   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14905     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14906   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14907
14908   // Set up the CFG correctly.
14909   BB->addSuccessor(bumpMBB);
14910   BB->addSuccessor(mallocMBB);
14911   mallocMBB->addSuccessor(continueMBB);
14912   bumpMBB->addSuccessor(continueMBB);
14913
14914   // Take care of the PHI nodes.
14915   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14916           MI->getOperand(0).getReg())
14917     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14918     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14919
14920   // Delete the original pseudo instruction.
14921   MI->eraseFromParent();
14922
14923   // And we're done.
14924   return continueMBB;
14925 }
14926
14927 MachineBasicBlock *
14928 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14929                                           MachineBasicBlock *BB) const {
14930   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14931   DebugLoc DL = MI->getDebugLoc();
14932
14933   assert(!Subtarget->isTargetEnvMacho());
14934
14935   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14936   // non-trivial part is impdef of ESP.
14937
14938   if (Subtarget->isTargetWin64()) {
14939     if (Subtarget->isTargetCygMing()) {
14940       // ___chkstk(Mingw64):
14941       // Clobbers R10, R11, RAX and EFLAGS.
14942       // Updates RSP.
14943       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14944         .addExternalSymbol("___chkstk")
14945         .addReg(X86::RAX, RegState::Implicit)
14946         .addReg(X86::RSP, RegState::Implicit)
14947         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14948         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14949         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14950     } else {
14951       // __chkstk(MSVCRT): does not update stack pointer.
14952       // Clobbers R10, R11 and EFLAGS.
14953       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14954         .addExternalSymbol("__chkstk")
14955         .addReg(X86::RAX, RegState::Implicit)
14956         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14957       // RAX has the offset to be subtracted from RSP.
14958       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14959         .addReg(X86::RSP)
14960         .addReg(X86::RAX);
14961     }
14962   } else {
14963     const char *StackProbeSymbol =
14964       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14965
14966     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14967       .addExternalSymbol(StackProbeSymbol)
14968       .addReg(X86::EAX, RegState::Implicit)
14969       .addReg(X86::ESP, RegState::Implicit)
14970       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14971       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14972       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14973   }
14974
14975   MI->eraseFromParent();   // The pseudo instruction is gone now.
14976   return BB;
14977 }
14978
14979 MachineBasicBlock *
14980 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14981                                       MachineBasicBlock *BB) const {
14982   // This is pretty easy.  We're taking the value that we received from
14983   // our load from the relocation, sticking it in either RDI (x86-64)
14984   // or EAX and doing an indirect call.  The return value will then
14985   // be in the normal return register.
14986   const X86InstrInfo *TII
14987     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14988   DebugLoc DL = MI->getDebugLoc();
14989   MachineFunction *F = BB->getParent();
14990
14991   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14992   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14993
14994   // Get a register mask for the lowered call.
14995   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14996   // proper register mask.
14997   const uint32_t *RegMask =
14998     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14999   if (Subtarget->is64Bit()) {
15000     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15001                                       TII->get(X86::MOV64rm), X86::RDI)
15002     .addReg(X86::RIP)
15003     .addImm(0).addReg(0)
15004     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15005                       MI->getOperand(3).getTargetFlags())
15006     .addReg(0);
15007     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15008     addDirectMem(MIB, X86::RDI);
15009     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15010   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15011     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15012                                       TII->get(X86::MOV32rm), X86::EAX)
15013     .addReg(0)
15014     .addImm(0).addReg(0)
15015     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15016                       MI->getOperand(3).getTargetFlags())
15017     .addReg(0);
15018     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15019     addDirectMem(MIB, X86::EAX);
15020     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15021   } else {
15022     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15023                                       TII->get(X86::MOV32rm), X86::EAX)
15024     .addReg(TII->getGlobalBaseReg(F))
15025     .addImm(0).addReg(0)
15026     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15027                       MI->getOperand(3).getTargetFlags())
15028     .addReg(0);
15029     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15030     addDirectMem(MIB, X86::EAX);
15031     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15032   }
15033
15034   MI->eraseFromParent(); // The pseudo instruction is gone now.
15035   return BB;
15036 }
15037
15038 MachineBasicBlock *
15039 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15040                                     MachineBasicBlock *MBB) const {
15041   DebugLoc DL = MI->getDebugLoc();
15042   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15043
15044   MachineFunction *MF = MBB->getParent();
15045   MachineRegisterInfo &MRI = MF->getRegInfo();
15046
15047   const BasicBlock *BB = MBB->getBasicBlock();
15048   MachineFunction::iterator I = MBB;
15049   ++I;
15050
15051   // Memory Reference
15052   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15053   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15054
15055   unsigned DstReg;
15056   unsigned MemOpndSlot = 0;
15057
15058   unsigned CurOp = 0;
15059
15060   DstReg = MI->getOperand(CurOp++).getReg();
15061   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15062   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15063   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15064   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15065
15066   MemOpndSlot = CurOp;
15067
15068   MVT PVT = getPointerTy();
15069   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15070          "Invalid Pointer Size!");
15071
15072   // For v = setjmp(buf), we generate
15073   //
15074   // thisMBB:
15075   //  buf[LabelOffset] = restoreMBB
15076   //  SjLjSetup restoreMBB
15077   //
15078   // mainMBB:
15079   //  v_main = 0
15080   //
15081   // sinkMBB:
15082   //  v = phi(main, restore)
15083   //
15084   // restoreMBB:
15085   //  v_restore = 1
15086
15087   MachineBasicBlock *thisMBB = MBB;
15088   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15089   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15090   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15091   MF->insert(I, mainMBB);
15092   MF->insert(I, sinkMBB);
15093   MF->push_back(restoreMBB);
15094
15095   MachineInstrBuilder MIB;
15096
15097   // Transfer the remainder of BB and its successor edges to sinkMBB.
15098   sinkMBB->splice(sinkMBB->begin(), MBB,
15099                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15100   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15101
15102   // thisMBB:
15103   unsigned PtrStoreOpc = 0;
15104   unsigned LabelReg = 0;
15105   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15106   Reloc::Model RM = getTargetMachine().getRelocationModel();
15107   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15108                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15109
15110   // Prepare IP either in reg or imm.
15111   if (!UseImmLabel) {
15112     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15113     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15114     LabelReg = MRI.createVirtualRegister(PtrRC);
15115     if (Subtarget->is64Bit()) {
15116       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15117               .addReg(X86::RIP)
15118               .addImm(0)
15119               .addReg(0)
15120               .addMBB(restoreMBB)
15121               .addReg(0);
15122     } else {
15123       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15124       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15125               .addReg(XII->getGlobalBaseReg(MF))
15126               .addImm(0)
15127               .addReg(0)
15128               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15129               .addReg(0);
15130     }
15131   } else
15132     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15133   // Store IP
15134   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15135   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15136     if (i == X86::AddrDisp)
15137       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15138     else
15139       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15140   }
15141   if (!UseImmLabel)
15142     MIB.addReg(LabelReg);
15143   else
15144     MIB.addMBB(restoreMBB);
15145   MIB.setMemRefs(MMOBegin, MMOEnd);
15146   // Setup
15147   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15148           .addMBB(restoreMBB);
15149
15150   const X86RegisterInfo *RegInfo =
15151     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15152   MIB.addRegMask(RegInfo->getNoPreservedMask());
15153   thisMBB->addSuccessor(mainMBB);
15154   thisMBB->addSuccessor(restoreMBB);
15155
15156   // mainMBB:
15157   //  EAX = 0
15158   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15159   mainMBB->addSuccessor(sinkMBB);
15160
15161   // sinkMBB:
15162   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15163           TII->get(X86::PHI), DstReg)
15164     .addReg(mainDstReg).addMBB(mainMBB)
15165     .addReg(restoreDstReg).addMBB(restoreMBB);
15166
15167   // restoreMBB:
15168   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15169   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15170   restoreMBB->addSuccessor(sinkMBB);
15171
15172   MI->eraseFromParent();
15173   return sinkMBB;
15174 }
15175
15176 MachineBasicBlock *
15177 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15178                                      MachineBasicBlock *MBB) const {
15179   DebugLoc DL = MI->getDebugLoc();
15180   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15181
15182   MachineFunction *MF = MBB->getParent();
15183   MachineRegisterInfo &MRI = MF->getRegInfo();
15184
15185   // Memory Reference
15186   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15187   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15188
15189   MVT PVT = getPointerTy();
15190   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15191          "Invalid Pointer Size!");
15192
15193   const TargetRegisterClass *RC =
15194     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15195   unsigned Tmp = MRI.createVirtualRegister(RC);
15196   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15197   const X86RegisterInfo *RegInfo =
15198     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15199   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15200   unsigned SP = RegInfo->getStackRegister();
15201
15202   MachineInstrBuilder MIB;
15203
15204   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15205   const int64_t SPOffset = 2 * PVT.getStoreSize();
15206
15207   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15208   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15209
15210   // Reload FP
15211   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15212   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15213     MIB.addOperand(MI->getOperand(i));
15214   MIB.setMemRefs(MMOBegin, MMOEnd);
15215   // Reload IP
15216   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15217   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15218     if (i == X86::AddrDisp)
15219       MIB.addDisp(MI->getOperand(i), LabelOffset);
15220     else
15221       MIB.addOperand(MI->getOperand(i));
15222   }
15223   MIB.setMemRefs(MMOBegin, MMOEnd);
15224   // Reload SP
15225   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15226   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15227     if (i == X86::AddrDisp)
15228       MIB.addDisp(MI->getOperand(i), SPOffset);
15229     else
15230       MIB.addOperand(MI->getOperand(i));
15231   }
15232   MIB.setMemRefs(MMOBegin, MMOEnd);
15233   // Jump
15234   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15235
15236   MI->eraseFromParent();
15237   return MBB;
15238 }
15239
15240 MachineBasicBlock *
15241 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15242                                                MachineBasicBlock *BB) const {
15243   switch (MI->getOpcode()) {
15244   default: llvm_unreachable("Unexpected instr type to insert");
15245   case X86::TAILJMPd64:
15246   case X86::TAILJMPr64:
15247   case X86::TAILJMPm64:
15248     llvm_unreachable("TAILJMP64 would not be touched here.");
15249   case X86::TCRETURNdi64:
15250   case X86::TCRETURNri64:
15251   case X86::TCRETURNmi64:
15252     return BB;
15253   case X86::WIN_ALLOCA:
15254     return EmitLoweredWinAlloca(MI, BB);
15255   case X86::SEG_ALLOCA_32:
15256     return EmitLoweredSegAlloca(MI, BB, false);
15257   case X86::SEG_ALLOCA_64:
15258     return EmitLoweredSegAlloca(MI, BB, true);
15259   case X86::TLSCall_32:
15260   case X86::TLSCall_64:
15261     return EmitLoweredTLSCall(MI, BB);
15262   case X86::CMOV_GR8:
15263   case X86::CMOV_FR32:
15264   case X86::CMOV_FR64:
15265   case X86::CMOV_V4F32:
15266   case X86::CMOV_V2F64:
15267   case X86::CMOV_V2I64:
15268   case X86::CMOV_V8F32:
15269   case X86::CMOV_V4F64:
15270   case X86::CMOV_V4I64:
15271   case X86::CMOV_GR16:
15272   case X86::CMOV_GR32:
15273   case X86::CMOV_RFP32:
15274   case X86::CMOV_RFP64:
15275   case X86::CMOV_RFP80:
15276     return EmitLoweredSelect(MI, BB);
15277
15278   case X86::FP32_TO_INT16_IN_MEM:
15279   case X86::FP32_TO_INT32_IN_MEM:
15280   case X86::FP32_TO_INT64_IN_MEM:
15281   case X86::FP64_TO_INT16_IN_MEM:
15282   case X86::FP64_TO_INT32_IN_MEM:
15283   case X86::FP64_TO_INT64_IN_MEM:
15284   case X86::FP80_TO_INT16_IN_MEM:
15285   case X86::FP80_TO_INT32_IN_MEM:
15286   case X86::FP80_TO_INT64_IN_MEM: {
15287     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15288     DebugLoc DL = MI->getDebugLoc();
15289
15290     // Change the floating point control register to use "round towards zero"
15291     // mode when truncating to an integer value.
15292     MachineFunction *F = BB->getParent();
15293     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15294     addFrameReference(BuildMI(*BB, MI, DL,
15295                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15296
15297     // Load the old value of the high byte of the control word...
15298     unsigned OldCW =
15299       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15300     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15301                       CWFrameIdx);
15302
15303     // Set the high part to be round to zero...
15304     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15305       .addImm(0xC7F);
15306
15307     // Reload the modified control word now...
15308     addFrameReference(BuildMI(*BB, MI, DL,
15309                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15310
15311     // Restore the memory image of control word to original value
15312     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15313       .addReg(OldCW);
15314
15315     // Get the X86 opcode to use.
15316     unsigned Opc;
15317     switch (MI->getOpcode()) {
15318     default: llvm_unreachable("illegal opcode!");
15319     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15320     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15321     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15322     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15323     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15324     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15325     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15326     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15327     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15328     }
15329
15330     X86AddressMode AM;
15331     MachineOperand &Op = MI->getOperand(0);
15332     if (Op.isReg()) {
15333       AM.BaseType = X86AddressMode::RegBase;
15334       AM.Base.Reg = Op.getReg();
15335     } else {
15336       AM.BaseType = X86AddressMode::FrameIndexBase;
15337       AM.Base.FrameIndex = Op.getIndex();
15338     }
15339     Op = MI->getOperand(1);
15340     if (Op.isImm())
15341       AM.Scale = Op.getImm();
15342     Op = MI->getOperand(2);
15343     if (Op.isImm())
15344       AM.IndexReg = Op.getImm();
15345     Op = MI->getOperand(3);
15346     if (Op.isGlobal()) {
15347       AM.GV = Op.getGlobal();
15348     } else {
15349       AM.Disp = Op.getImm();
15350     }
15351     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15352                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15353
15354     // Reload the original control word now.
15355     addFrameReference(BuildMI(*BB, MI, DL,
15356                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15357
15358     MI->eraseFromParent();   // The pseudo instruction is gone now.
15359     return BB;
15360   }
15361     // String/text processing lowering.
15362   case X86::PCMPISTRM128REG:
15363   case X86::VPCMPISTRM128REG:
15364   case X86::PCMPISTRM128MEM:
15365   case X86::VPCMPISTRM128MEM:
15366   case X86::PCMPESTRM128REG:
15367   case X86::VPCMPESTRM128REG:
15368   case X86::PCMPESTRM128MEM:
15369   case X86::VPCMPESTRM128MEM:
15370     assert(Subtarget->hasSSE42() &&
15371            "Target must have SSE4.2 or AVX features enabled");
15372     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15373
15374   // String/text processing lowering.
15375   case X86::PCMPISTRIREG:
15376   case X86::VPCMPISTRIREG:
15377   case X86::PCMPISTRIMEM:
15378   case X86::VPCMPISTRIMEM:
15379   case X86::PCMPESTRIREG:
15380   case X86::VPCMPESTRIREG:
15381   case X86::PCMPESTRIMEM:
15382   case X86::VPCMPESTRIMEM:
15383     assert(Subtarget->hasSSE42() &&
15384            "Target must have SSE4.2 or AVX features enabled");
15385     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15386
15387   // Thread synchronization.
15388   case X86::MONITOR:
15389     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15390
15391   // xbegin
15392   case X86::XBEGIN:
15393     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15394
15395   // Atomic Lowering.
15396   case X86::ATOMAND8:
15397   case X86::ATOMAND16:
15398   case X86::ATOMAND32:
15399   case X86::ATOMAND64:
15400     // Fall through
15401   case X86::ATOMOR8:
15402   case X86::ATOMOR16:
15403   case X86::ATOMOR32:
15404   case X86::ATOMOR64:
15405     // Fall through
15406   case X86::ATOMXOR16:
15407   case X86::ATOMXOR8:
15408   case X86::ATOMXOR32:
15409   case X86::ATOMXOR64:
15410     // Fall through
15411   case X86::ATOMNAND8:
15412   case X86::ATOMNAND16:
15413   case X86::ATOMNAND32:
15414   case X86::ATOMNAND64:
15415     // Fall through
15416   case X86::ATOMMAX8:
15417   case X86::ATOMMAX16:
15418   case X86::ATOMMAX32:
15419   case X86::ATOMMAX64:
15420     // Fall through
15421   case X86::ATOMMIN8:
15422   case X86::ATOMMIN16:
15423   case X86::ATOMMIN32:
15424   case X86::ATOMMIN64:
15425     // Fall through
15426   case X86::ATOMUMAX8:
15427   case X86::ATOMUMAX16:
15428   case X86::ATOMUMAX32:
15429   case X86::ATOMUMAX64:
15430     // Fall through
15431   case X86::ATOMUMIN8:
15432   case X86::ATOMUMIN16:
15433   case X86::ATOMUMIN32:
15434   case X86::ATOMUMIN64:
15435     return EmitAtomicLoadArith(MI, BB);
15436
15437   // This group does 64-bit operations on a 32-bit host.
15438   case X86::ATOMAND6432:
15439   case X86::ATOMOR6432:
15440   case X86::ATOMXOR6432:
15441   case X86::ATOMNAND6432:
15442   case X86::ATOMADD6432:
15443   case X86::ATOMSUB6432:
15444   case X86::ATOMMAX6432:
15445   case X86::ATOMMIN6432:
15446   case X86::ATOMUMAX6432:
15447   case X86::ATOMUMIN6432:
15448   case X86::ATOMSWAP6432:
15449     return EmitAtomicLoadArith6432(MI, BB);
15450
15451   case X86::VASTART_SAVE_XMM_REGS:
15452     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15453
15454   case X86::VAARG_64:
15455     return EmitVAARG64WithCustomInserter(MI, BB);
15456
15457   case X86::EH_SjLj_SetJmp32:
15458   case X86::EH_SjLj_SetJmp64:
15459     return emitEHSjLjSetJmp(MI, BB);
15460
15461   case X86::EH_SjLj_LongJmp32:
15462   case X86::EH_SjLj_LongJmp64:
15463     return emitEHSjLjLongJmp(MI, BB);
15464   }
15465 }
15466
15467 //===----------------------------------------------------------------------===//
15468 //                           X86 Optimization Hooks
15469 //===----------------------------------------------------------------------===//
15470
15471 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15472                                                        APInt &KnownZero,
15473                                                        APInt &KnownOne,
15474                                                        const SelectionDAG &DAG,
15475                                                        unsigned Depth) const {
15476   unsigned BitWidth = KnownZero.getBitWidth();
15477   unsigned Opc = Op.getOpcode();
15478   assert((Opc >= ISD::BUILTIN_OP_END ||
15479           Opc == ISD::INTRINSIC_WO_CHAIN ||
15480           Opc == ISD::INTRINSIC_W_CHAIN ||
15481           Opc == ISD::INTRINSIC_VOID) &&
15482          "Should use MaskedValueIsZero if you don't know whether Op"
15483          " is a target node!");
15484
15485   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
15486   switch (Opc) {
15487   default: break;
15488   case X86ISD::ADD:
15489   case X86ISD::SUB:
15490   case X86ISD::ADC:
15491   case X86ISD::SBB:
15492   case X86ISD::SMUL:
15493   case X86ISD::UMUL:
15494   case X86ISD::INC:
15495   case X86ISD::DEC:
15496   case X86ISD::OR:
15497   case X86ISD::XOR:
15498   case X86ISD::AND:
15499     // These nodes' second result is a boolean.
15500     if (Op.getResNo() == 0)
15501       break;
15502     // Fallthrough
15503   case X86ISD::SETCC:
15504     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15505     break;
15506   case ISD::INTRINSIC_WO_CHAIN: {
15507     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15508     unsigned NumLoBits = 0;
15509     switch (IntId) {
15510     default: break;
15511     case Intrinsic::x86_sse_movmsk_ps:
15512     case Intrinsic::x86_avx_movmsk_ps_256:
15513     case Intrinsic::x86_sse2_movmsk_pd:
15514     case Intrinsic::x86_avx_movmsk_pd_256:
15515     case Intrinsic::x86_mmx_pmovmskb:
15516     case Intrinsic::x86_sse2_pmovmskb_128:
15517     case Intrinsic::x86_avx2_pmovmskb: {
15518       // High bits of movmskp{s|d}, pmovmskb are known zero.
15519       switch (IntId) {
15520         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15521         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15522         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15523         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15524         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15525         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15526         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15527         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15528       }
15529       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15530       break;
15531     }
15532     }
15533     break;
15534   }
15535   }
15536 }
15537
15538 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15539                                                          unsigned Depth) const {
15540   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15541   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15542     return Op.getValueType().getScalarType().getSizeInBits();
15543
15544   // Fallback case.
15545   return 1;
15546 }
15547
15548 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15549 /// node is a GlobalAddress + offset.
15550 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15551                                        const GlobalValue* &GA,
15552                                        int64_t &Offset) const {
15553   if (N->getOpcode() == X86ISD::Wrapper) {
15554     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15555       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15556       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15557       return true;
15558     }
15559   }
15560   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15561 }
15562
15563 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15564 /// same as extracting the high 128-bit part of 256-bit vector and then
15565 /// inserting the result into the low part of a new 256-bit vector
15566 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15567   EVT VT = SVOp->getValueType(0);
15568   unsigned NumElems = VT.getVectorNumElements();
15569
15570   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15571   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15572     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15573         SVOp->getMaskElt(j) >= 0)
15574       return false;
15575
15576   return true;
15577 }
15578
15579 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15580 /// same as extracting the low 128-bit part of 256-bit vector and then
15581 /// inserting the result into the high part of a new 256-bit vector
15582 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15583   EVT VT = SVOp->getValueType(0);
15584   unsigned NumElems = VT.getVectorNumElements();
15585
15586   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15587   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15588     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15589         SVOp->getMaskElt(j) >= 0)
15590       return false;
15591
15592   return true;
15593 }
15594
15595 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15596 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15597                                         TargetLowering::DAGCombinerInfo &DCI,
15598                                         const X86Subtarget* Subtarget) {
15599   SDLoc dl(N);
15600   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15601   SDValue V1 = SVOp->getOperand(0);
15602   SDValue V2 = SVOp->getOperand(1);
15603   EVT VT = SVOp->getValueType(0);
15604   unsigned NumElems = VT.getVectorNumElements();
15605
15606   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15607       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15608     //
15609     //                   0,0,0,...
15610     //                      |
15611     //    V      UNDEF    BUILD_VECTOR    UNDEF
15612     //     \      /           \           /
15613     //  CONCAT_VECTOR         CONCAT_VECTOR
15614     //         \                  /
15615     //          \                /
15616     //          RESULT: V + zero extended
15617     //
15618     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15619         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15620         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15621       return SDValue();
15622
15623     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15624       return SDValue();
15625
15626     // To match the shuffle mask, the first half of the mask should
15627     // be exactly the first vector, and all the rest a splat with the
15628     // first element of the second one.
15629     for (unsigned i = 0; i != NumElems/2; ++i)
15630       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15631           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15632         return SDValue();
15633
15634     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15635     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15636       if (Ld->hasNUsesOfValue(1, 0)) {
15637         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15638         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15639         SDValue ResNode =
15640           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15641                                   array_lengthof(Ops),
15642                                   Ld->getMemoryVT(),
15643                                   Ld->getPointerInfo(),
15644                                   Ld->getAlignment(),
15645                                   false/*isVolatile*/, true/*ReadMem*/,
15646                                   false/*WriteMem*/);
15647
15648         // Make sure the newly-created LOAD is in the same position as Ld in
15649         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15650         // and update uses of Ld's output chain to use the TokenFactor.
15651         if (Ld->hasAnyUseOfValue(1)) {
15652           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15653                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15654           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15655           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15656                                  SDValue(ResNode.getNode(), 1));
15657         }
15658
15659         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15660       }
15661     }
15662
15663     // Emit a zeroed vector and insert the desired subvector on its
15664     // first half.
15665     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15666     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15667     return DCI.CombineTo(N, InsV);
15668   }
15669
15670   //===--------------------------------------------------------------------===//
15671   // Combine some shuffles into subvector extracts and inserts:
15672   //
15673
15674   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15675   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15676     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15677     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15678     return DCI.CombineTo(N, InsV);
15679   }
15680
15681   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15682   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15683     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15684     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15685     return DCI.CombineTo(N, InsV);
15686   }
15687
15688   return SDValue();
15689 }
15690
15691 /// PerformShuffleCombine - Performs several different shuffle combines.
15692 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15693                                      TargetLowering::DAGCombinerInfo &DCI,
15694                                      const X86Subtarget *Subtarget) {
15695   SDLoc dl(N);
15696   EVT VT = N->getValueType(0);
15697
15698   // Don't create instructions with illegal types after legalize types has run.
15699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15700   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15701     return SDValue();
15702
15703   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15704   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15705       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15706     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15707
15708   // Only handle 128 wide vector from here on.
15709   if (!VT.is128BitVector())
15710     return SDValue();
15711
15712   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15713   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15714   // consecutive, non-overlapping, and in the right order.
15715   SmallVector<SDValue, 16> Elts;
15716   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15717     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15718
15719   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15720 }
15721
15722 /// PerformTruncateCombine - Converts truncate operation to
15723 /// a sequence of vector shuffle operations.
15724 /// It is possible when we truncate 256-bit vector to 128-bit vector
15725 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15726                                       TargetLowering::DAGCombinerInfo &DCI,
15727                                       const X86Subtarget *Subtarget)  {
15728   return SDValue();
15729 }
15730
15731 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15732 /// specific shuffle of a load can be folded into a single element load.
15733 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15734 /// shuffles have been customed lowered so we need to handle those here.
15735 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15736                                          TargetLowering::DAGCombinerInfo &DCI) {
15737   if (DCI.isBeforeLegalizeOps())
15738     return SDValue();
15739
15740   SDValue InVec = N->getOperand(0);
15741   SDValue EltNo = N->getOperand(1);
15742
15743   if (!isa<ConstantSDNode>(EltNo))
15744     return SDValue();
15745
15746   EVT VT = InVec.getValueType();
15747
15748   bool HasShuffleIntoBitcast = false;
15749   if (InVec.getOpcode() == ISD::BITCAST) {
15750     // Don't duplicate a load with other uses.
15751     if (!InVec.hasOneUse())
15752       return SDValue();
15753     EVT BCVT = InVec.getOperand(0).getValueType();
15754     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15755       return SDValue();
15756     InVec = InVec.getOperand(0);
15757     HasShuffleIntoBitcast = true;
15758   }
15759
15760   if (!isTargetShuffle(InVec.getOpcode()))
15761     return SDValue();
15762
15763   // Don't duplicate a load with other uses.
15764   if (!InVec.hasOneUse())
15765     return SDValue();
15766
15767   SmallVector<int, 16> ShuffleMask;
15768   bool UnaryShuffle;
15769   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15770                             UnaryShuffle))
15771     return SDValue();
15772
15773   // Select the input vector, guarding against out of range extract vector.
15774   unsigned NumElems = VT.getVectorNumElements();
15775   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15776   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15777   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15778                                          : InVec.getOperand(1);
15779
15780   // If inputs to shuffle are the same for both ops, then allow 2 uses
15781   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15782
15783   if (LdNode.getOpcode() == ISD::BITCAST) {
15784     // Don't duplicate a load with other uses.
15785     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15786       return SDValue();
15787
15788     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15789     LdNode = LdNode.getOperand(0);
15790   }
15791
15792   if (!ISD::isNormalLoad(LdNode.getNode()))
15793     return SDValue();
15794
15795   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15796
15797   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15798     return SDValue();
15799
15800   if (HasShuffleIntoBitcast) {
15801     // If there's a bitcast before the shuffle, check if the load type and
15802     // alignment is valid.
15803     unsigned Align = LN0->getAlignment();
15804     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15805     unsigned NewAlign = TLI.getDataLayout()->
15806       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15807
15808     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15809       return SDValue();
15810   }
15811
15812   // All checks match so transform back to vector_shuffle so that DAG combiner
15813   // can finish the job
15814   SDLoc dl(N);
15815
15816   // Create shuffle node taking into account the case that its a unary shuffle
15817   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15818   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15819                                  InVec.getOperand(0), Shuffle,
15820                                  &ShuffleMask[0]);
15821   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15822   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15823                      EltNo);
15824 }
15825
15826 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15827 /// generation and convert it from being a bunch of shuffles and extracts
15828 /// to a simple store and scalar loads to extract the elements.
15829 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15830                                          TargetLowering::DAGCombinerInfo &DCI) {
15831   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15832   if (NewOp.getNode())
15833     return NewOp;
15834
15835   SDValue InputVector = N->getOperand(0);
15836   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15837   // from mmx to v2i32 has a single usage.
15838   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15839       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15840       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15841     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15842                        N->getValueType(0),
15843                        InputVector.getNode()->getOperand(0));
15844
15845   // Only operate on vectors of 4 elements, where the alternative shuffling
15846   // gets to be more expensive.
15847   if (InputVector.getValueType() != MVT::v4i32)
15848     return SDValue();
15849
15850   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15851   // single use which is a sign-extend or zero-extend, and all elements are
15852   // used.
15853   SmallVector<SDNode *, 4> Uses;
15854   unsigned ExtractedElements = 0;
15855   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15856        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15857     if (UI.getUse().getResNo() != InputVector.getResNo())
15858       return SDValue();
15859
15860     SDNode *Extract = *UI;
15861     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15862       return SDValue();
15863
15864     if (Extract->getValueType(0) != MVT::i32)
15865       return SDValue();
15866     if (!Extract->hasOneUse())
15867       return SDValue();
15868     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15869         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15870       return SDValue();
15871     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15872       return SDValue();
15873
15874     // Record which element was extracted.
15875     ExtractedElements |=
15876       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15877
15878     Uses.push_back(Extract);
15879   }
15880
15881   // If not all the elements were used, this may not be worthwhile.
15882   if (ExtractedElements != 15)
15883     return SDValue();
15884
15885   // Ok, we've now decided to do the transformation.
15886   SDLoc dl(InputVector);
15887
15888   // Store the value to a temporary stack slot.
15889   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15890   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15891                             MachinePointerInfo(), false, false, 0);
15892
15893   // Replace each use (extract) with a load of the appropriate element.
15894   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15895        UE = Uses.end(); UI != UE; ++UI) {
15896     SDNode *Extract = *UI;
15897
15898     // cOMpute the element's address.
15899     SDValue Idx = Extract->getOperand(1);
15900     unsigned EltSize =
15901         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15902     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15903     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15904     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15905
15906     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15907                                      StackPtr, OffsetVal);
15908
15909     // Load the scalar.
15910     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15911                                      ScalarAddr, MachinePointerInfo(),
15912                                      false, false, false, 0);
15913
15914     // Replace the exact with the load.
15915     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15916   }
15917
15918   // The replacement was made in place; don't return anything.
15919   return SDValue();
15920 }
15921
15922 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15923 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15924                                    SDValue RHS, SelectionDAG &DAG,
15925                                    const X86Subtarget *Subtarget) {
15926   if (!VT.isVector())
15927     return 0;
15928
15929   switch (VT.getSimpleVT().SimpleTy) {
15930   default: return 0;
15931   case MVT::v32i8:
15932   case MVT::v16i16:
15933   case MVT::v8i32:
15934     if (!Subtarget->hasAVX2())
15935       return 0;
15936   case MVT::v16i8:
15937   case MVT::v8i16:
15938   case MVT::v4i32:
15939     if (!Subtarget->hasSSE2())
15940       return 0;
15941   }
15942
15943   // SSE2 has only a small subset of the operations.
15944   bool hasUnsigned = Subtarget->hasSSE41() ||
15945                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15946   bool hasSigned = Subtarget->hasSSE41() ||
15947                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15948
15949   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15950
15951   // Check for x CC y ? x : y.
15952   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15953       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15954     switch (CC) {
15955     default: break;
15956     case ISD::SETULT:
15957     case ISD::SETULE:
15958       return hasUnsigned ? X86ISD::UMIN : 0;
15959     case ISD::SETUGT:
15960     case ISD::SETUGE:
15961       return hasUnsigned ? X86ISD::UMAX : 0;
15962     case ISD::SETLT:
15963     case ISD::SETLE:
15964       return hasSigned ? X86ISD::SMIN : 0;
15965     case ISD::SETGT:
15966     case ISD::SETGE:
15967       return hasSigned ? X86ISD::SMAX : 0;
15968     }
15969   // Check for x CC y ? y : x -- a min/max with reversed arms.
15970   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15971              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15972     switch (CC) {
15973     default: break;
15974     case ISD::SETULT:
15975     case ISD::SETULE:
15976       return hasUnsigned ? X86ISD::UMAX : 0;
15977     case ISD::SETUGT:
15978     case ISD::SETUGE:
15979       return hasUnsigned ? X86ISD::UMIN : 0;
15980     case ISD::SETLT:
15981     case ISD::SETLE:
15982       return hasSigned ? X86ISD::SMAX : 0;
15983     case ISD::SETGT:
15984     case ISD::SETGE:
15985       return hasSigned ? X86ISD::SMIN : 0;
15986     }
15987   }
15988
15989   return 0;
15990 }
15991
15992 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15993 /// nodes.
15994 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15995                                     TargetLowering::DAGCombinerInfo &DCI,
15996                                     const X86Subtarget *Subtarget) {
15997   SDLoc DL(N);
15998   SDValue Cond = N->getOperand(0);
15999   // Get the LHS/RHS of the select.
16000   SDValue LHS = N->getOperand(1);
16001   SDValue RHS = N->getOperand(2);
16002   EVT VT = LHS.getValueType();
16003
16004   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16005   // instructions match the semantics of the common C idiom x<y?x:y but not
16006   // x<=y?x:y, because of how they handle negative zero (which can be
16007   // ignored in unsafe-math mode).
16008   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16009       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16010       (Subtarget->hasSSE2() ||
16011        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16012     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16013
16014     unsigned Opcode = 0;
16015     // Check for x CC y ? x : y.
16016     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16017         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16018       switch (CC) {
16019       default: break;
16020       case ISD::SETULT:
16021         // Converting this to a min would handle NaNs incorrectly, and swapping
16022         // the operands would cause it to handle comparisons between positive
16023         // and negative zero incorrectly.
16024         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16025           if (!DAG.getTarget().Options.UnsafeFPMath &&
16026               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16027             break;
16028           std::swap(LHS, RHS);
16029         }
16030         Opcode = X86ISD::FMIN;
16031         break;
16032       case ISD::SETOLE:
16033         // Converting this to a min would handle comparisons between positive
16034         // and negative zero incorrectly.
16035         if (!DAG.getTarget().Options.UnsafeFPMath &&
16036             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16037           break;
16038         Opcode = X86ISD::FMIN;
16039         break;
16040       case ISD::SETULE:
16041         // Converting this to a min would handle both negative zeros and NaNs
16042         // incorrectly, but we can swap the operands to fix both.
16043         std::swap(LHS, RHS);
16044       case ISD::SETOLT:
16045       case ISD::SETLT:
16046       case ISD::SETLE:
16047         Opcode = X86ISD::FMIN;
16048         break;
16049
16050       case ISD::SETOGE:
16051         // Converting this to a max would handle comparisons between positive
16052         // and negative zero incorrectly.
16053         if (!DAG.getTarget().Options.UnsafeFPMath &&
16054             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16055           break;
16056         Opcode = X86ISD::FMAX;
16057         break;
16058       case ISD::SETUGT:
16059         // Converting this to a max would handle NaNs incorrectly, and swapping
16060         // the operands would cause it to handle comparisons between positive
16061         // and negative zero incorrectly.
16062         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16063           if (!DAG.getTarget().Options.UnsafeFPMath &&
16064               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16065             break;
16066           std::swap(LHS, RHS);
16067         }
16068         Opcode = X86ISD::FMAX;
16069         break;
16070       case ISD::SETUGE:
16071         // Converting this to a max would handle both negative zeros and NaNs
16072         // incorrectly, but we can swap the operands to fix both.
16073         std::swap(LHS, RHS);
16074       case ISD::SETOGT:
16075       case ISD::SETGT:
16076       case ISD::SETGE:
16077         Opcode = X86ISD::FMAX;
16078         break;
16079       }
16080     // Check for x CC y ? y : x -- a min/max with reversed arms.
16081     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16082                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16083       switch (CC) {
16084       default: break;
16085       case ISD::SETOGE:
16086         // Converting this to a min would handle comparisons between positive
16087         // and negative zero incorrectly, and swapping the operands would
16088         // cause it to handle NaNs incorrectly.
16089         if (!DAG.getTarget().Options.UnsafeFPMath &&
16090             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16091           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16092             break;
16093           std::swap(LHS, RHS);
16094         }
16095         Opcode = X86ISD::FMIN;
16096         break;
16097       case ISD::SETUGT:
16098         // Converting this to a min would handle NaNs incorrectly.
16099         if (!DAG.getTarget().Options.UnsafeFPMath &&
16100             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16101           break;
16102         Opcode = X86ISD::FMIN;
16103         break;
16104       case ISD::SETUGE:
16105         // Converting this to a min would handle both negative zeros and NaNs
16106         // incorrectly, but we can swap the operands to fix both.
16107         std::swap(LHS, RHS);
16108       case ISD::SETOGT:
16109       case ISD::SETGT:
16110       case ISD::SETGE:
16111         Opcode = X86ISD::FMIN;
16112         break;
16113
16114       case ISD::SETULT:
16115         // Converting this to a max would handle NaNs incorrectly.
16116         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16117           break;
16118         Opcode = X86ISD::FMAX;
16119         break;
16120       case ISD::SETOLE:
16121         // Converting this to a max would handle comparisons between positive
16122         // and negative zero incorrectly, and swapping the operands would
16123         // cause it to handle NaNs incorrectly.
16124         if (!DAG.getTarget().Options.UnsafeFPMath &&
16125             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16126           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16127             break;
16128           std::swap(LHS, RHS);
16129         }
16130         Opcode = X86ISD::FMAX;
16131         break;
16132       case ISD::SETULE:
16133         // Converting this to a max would handle both negative zeros and NaNs
16134         // incorrectly, but we can swap the operands to fix both.
16135         std::swap(LHS, RHS);
16136       case ISD::SETOLT:
16137       case ISD::SETLT:
16138       case ISD::SETLE:
16139         Opcode = X86ISD::FMAX;
16140         break;
16141       }
16142     }
16143
16144     if (Opcode)
16145       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16146   }
16147
16148   // If this is a select between two integer constants, try to do some
16149   // optimizations.
16150   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16151     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16152       // Don't do this for crazy integer types.
16153       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16154         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16155         // so that TrueC (the true value) is larger than FalseC.
16156         bool NeedsCondInvert = false;
16157
16158         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16159             // Efficiently invertible.
16160             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16161              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16162               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16163           NeedsCondInvert = true;
16164           std::swap(TrueC, FalseC);
16165         }
16166
16167         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16168         if (FalseC->getAPIntValue() == 0 &&
16169             TrueC->getAPIntValue().isPowerOf2()) {
16170           if (NeedsCondInvert) // Invert the condition if needed.
16171             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16172                                DAG.getConstant(1, Cond.getValueType()));
16173
16174           // Zero extend the condition if needed.
16175           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16176
16177           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16178           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16179                              DAG.getConstant(ShAmt, MVT::i8));
16180         }
16181
16182         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16183         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16184           if (NeedsCondInvert) // Invert the condition if needed.
16185             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16186                                DAG.getConstant(1, Cond.getValueType()));
16187
16188           // Zero extend the condition if needed.
16189           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16190                              FalseC->getValueType(0), Cond);
16191           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16192                              SDValue(FalseC, 0));
16193         }
16194
16195         // Optimize cases that will turn into an LEA instruction.  This requires
16196         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16197         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16198           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16199           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16200
16201           bool isFastMultiplier = false;
16202           if (Diff < 10) {
16203             switch ((unsigned char)Diff) {
16204               default: break;
16205               case 1:  // result = add base, cond
16206               case 2:  // result = lea base(    , cond*2)
16207               case 3:  // result = lea base(cond, cond*2)
16208               case 4:  // result = lea base(    , cond*4)
16209               case 5:  // result = lea base(cond, cond*4)
16210               case 8:  // result = lea base(    , cond*8)
16211               case 9:  // result = lea base(cond, cond*8)
16212                 isFastMultiplier = true;
16213                 break;
16214             }
16215           }
16216
16217           if (isFastMultiplier) {
16218             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16219             if (NeedsCondInvert) // Invert the condition if needed.
16220               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16221                                  DAG.getConstant(1, Cond.getValueType()));
16222
16223             // Zero extend the condition if needed.
16224             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16225                                Cond);
16226             // Scale the condition by the difference.
16227             if (Diff != 1)
16228               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16229                                  DAG.getConstant(Diff, Cond.getValueType()));
16230
16231             // Add the base if non-zero.
16232             if (FalseC->getAPIntValue() != 0)
16233               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16234                                  SDValue(FalseC, 0));
16235             return Cond;
16236           }
16237         }
16238       }
16239   }
16240
16241   // Canonicalize max and min:
16242   // (x > y) ? x : y -> (x >= y) ? x : y
16243   // (x < y) ? x : y -> (x <= y) ? x : y
16244   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16245   // the need for an extra compare
16246   // against zero. e.g.
16247   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16248   // subl   %esi, %edi
16249   // testl  %edi, %edi
16250   // movl   $0, %eax
16251   // cmovgl %edi, %eax
16252   // =>
16253   // xorl   %eax, %eax
16254   // subl   %esi, $edi
16255   // cmovsl %eax, %edi
16256   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16257       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16258       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16259     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16260     switch (CC) {
16261     default: break;
16262     case ISD::SETLT:
16263     case ISD::SETGT: {
16264       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16265       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16266                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16267       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16268     }
16269     }
16270   }
16271
16272   // Match VSELECTs into subs with unsigned saturation.
16273   if (!DCI.isBeforeLegalize() &&
16274       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16275       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16276       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16277        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16278     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16279
16280     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16281     // left side invert the predicate to simplify logic below.
16282     SDValue Other;
16283     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16284       Other = RHS;
16285       CC = ISD::getSetCCInverse(CC, true);
16286     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16287       Other = LHS;
16288     }
16289
16290     if (Other.getNode() && Other->getNumOperands() == 2 &&
16291         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16292       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16293       SDValue CondRHS = Cond->getOperand(1);
16294
16295       // Look for a general sub with unsigned saturation first.
16296       // x >= y ? x-y : 0 --> subus x, y
16297       // x >  y ? x-y : 0 --> subus x, y
16298       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16299           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16300         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16301
16302       // If the RHS is a constant we have to reverse the const canonicalization.
16303       // x > C-1 ? x+-C : 0 --> subus x, C
16304       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16305           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16306         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16307         if (CondRHS.getConstantOperandVal(0) == -A-1)
16308           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16309                              DAG.getConstant(-A, VT));
16310       }
16311
16312       // Another special case: If C was a sign bit, the sub has been
16313       // canonicalized into a xor.
16314       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16315       //        it's safe to decanonicalize the xor?
16316       // x s< 0 ? x^C : 0 --> subus x, C
16317       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16318           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16319           isSplatVector(OpRHS.getNode())) {
16320         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16321         if (A.isSignBit())
16322           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16323       }
16324     }
16325   }
16326
16327   // Try to match a min/max vector operation.
16328   if (!DCI.isBeforeLegalize() &&
16329       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16330     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16331       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16332
16333   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16334   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16335       Cond.getOpcode() == ISD::SETCC) {
16336
16337     assert(Cond.getValueType().isVector() &&
16338            "vector select expects a vector selector!");
16339
16340     EVT IntVT = Cond.getValueType();
16341     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16342     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16343
16344     if (!TValIsAllOnes && !FValIsAllZeros) {
16345       // Try invert the condition if true value is not all 1s and false value
16346       // is not all 0s.
16347       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16348       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16349
16350       if (TValIsAllZeros || FValIsAllOnes) {
16351         SDValue CC = Cond.getOperand(2);
16352         ISD::CondCode NewCC =
16353           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16354                                Cond.getOperand(0).getValueType().isInteger());
16355         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16356         std::swap(LHS, RHS);
16357         TValIsAllOnes = FValIsAllOnes;
16358         FValIsAllZeros = TValIsAllZeros;
16359       }
16360     }
16361
16362     if (TValIsAllOnes || FValIsAllZeros) {
16363       SDValue Ret;
16364
16365       if (TValIsAllOnes && FValIsAllZeros)
16366         Ret = Cond;
16367       else if (TValIsAllOnes)
16368         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16369                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16370       else if (FValIsAllZeros)
16371         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16372                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16373
16374       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16375     }
16376   }
16377
16378   // If we know that this node is legal then we know that it is going to be
16379   // matched by one of the SSE/AVX BLEND instructions. These instructions only
16380   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16381   // to simplify previous instructions.
16382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16383   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16384       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16385     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16386
16387     // Don't optimize vector selects that map to mask-registers.
16388     if (BitWidth == 1)
16389       return SDValue();
16390
16391     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16392     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16393
16394     APInt KnownZero, KnownOne;
16395     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16396                                           DCI.isBeforeLegalizeOps());
16397     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16398         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16399       DCI.CommitTargetLoweringOpt(TLO);
16400   }
16401
16402   return SDValue();
16403 }
16404
16405 // Check whether a boolean test is testing a boolean value generated by
16406 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16407 // code.
16408 //
16409 // Simplify the following patterns:
16410 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16411 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16412 // to (Op EFLAGS Cond)
16413 //
16414 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16415 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16416 // to (Op EFLAGS !Cond)
16417 //
16418 // where Op could be BRCOND or CMOV.
16419 //
16420 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16421   // Quit if not CMP and SUB with its value result used.
16422   if (Cmp.getOpcode() != X86ISD::CMP &&
16423       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16424       return SDValue();
16425
16426   // Quit if not used as a boolean value.
16427   if (CC != X86::COND_E && CC != X86::COND_NE)
16428     return SDValue();
16429
16430   // Check CMP operands. One of them should be 0 or 1 and the other should be
16431   // an SetCC or extended from it.
16432   SDValue Op1 = Cmp.getOperand(0);
16433   SDValue Op2 = Cmp.getOperand(1);
16434
16435   SDValue SetCC;
16436   const ConstantSDNode* C = 0;
16437   bool needOppositeCond = (CC == X86::COND_E);
16438   bool checkAgainstTrue = false; // Is it a comparison against 1?
16439
16440   if ((C = dyn_cast<ConstantSDNode>(Op1)))
16441     SetCC = Op2;
16442   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16443     SetCC = Op1;
16444   else // Quit if all operands are not constants.
16445     return SDValue();
16446
16447   if (C->getZExtValue() == 1) {
16448     needOppositeCond = !needOppositeCond;
16449     checkAgainstTrue = true;
16450   } else if (C->getZExtValue() != 0)
16451     // Quit if the constant is neither 0 or 1.
16452     return SDValue();
16453
16454   bool truncatedToBoolWithAnd = false;
16455   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16456   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16457          SetCC.getOpcode() == ISD::TRUNCATE ||
16458          SetCC.getOpcode() == ISD::AND) {
16459     if (SetCC.getOpcode() == ISD::AND) {
16460       int OpIdx = -1;
16461       ConstantSDNode *CS;
16462       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16463           CS->getZExtValue() == 1)
16464         OpIdx = 1;
16465       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16466           CS->getZExtValue() == 1)
16467         OpIdx = 0;
16468       if (OpIdx == -1)
16469         break;
16470       SetCC = SetCC.getOperand(OpIdx);
16471       truncatedToBoolWithAnd = true;
16472     } else
16473       SetCC = SetCC.getOperand(0);
16474   }
16475
16476   switch (SetCC.getOpcode()) {
16477   case X86ISD::SETCC_CARRY:
16478     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16479     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16480     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16481     // truncated to i1 using 'and'.
16482     if (checkAgainstTrue && !truncatedToBoolWithAnd)
16483       break;
16484     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16485            "Invalid use of SETCC_CARRY!");
16486     // FALL THROUGH
16487   case X86ISD::SETCC:
16488     // Set the condition code or opposite one if necessary.
16489     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16490     if (needOppositeCond)
16491       CC = X86::GetOppositeBranchCondition(CC);
16492     return SetCC.getOperand(1);
16493   case X86ISD::CMOV: {
16494     // Check whether false/true value has canonical one, i.e. 0 or 1.
16495     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16496     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16497     // Quit if true value is not a constant.
16498     if (!TVal)
16499       return SDValue();
16500     // Quit if false value is not a constant.
16501     if (!FVal) {
16502       SDValue Op = SetCC.getOperand(0);
16503       // Skip 'zext' or 'trunc' node.
16504       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16505           Op.getOpcode() == ISD::TRUNCATE)
16506         Op = Op.getOperand(0);
16507       // A special case for rdrand/rdseed, where 0 is set if false cond is
16508       // found.
16509       if ((Op.getOpcode() != X86ISD::RDRAND &&
16510            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16511         return SDValue();
16512     }
16513     // Quit if false value is not the constant 0 or 1.
16514     bool FValIsFalse = true;
16515     if (FVal && FVal->getZExtValue() != 0) {
16516       if (FVal->getZExtValue() != 1)
16517         return SDValue();
16518       // If FVal is 1, opposite cond is needed.
16519       needOppositeCond = !needOppositeCond;
16520       FValIsFalse = false;
16521     }
16522     // Quit if TVal is not the constant opposite of FVal.
16523     if (FValIsFalse && TVal->getZExtValue() != 1)
16524       return SDValue();
16525     if (!FValIsFalse && TVal->getZExtValue() != 0)
16526       return SDValue();
16527     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16528     if (needOppositeCond)
16529       CC = X86::GetOppositeBranchCondition(CC);
16530     return SetCC.getOperand(3);
16531   }
16532   }
16533
16534   return SDValue();
16535 }
16536
16537 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16538 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16539                                   TargetLowering::DAGCombinerInfo &DCI,
16540                                   const X86Subtarget *Subtarget) {
16541   SDLoc DL(N);
16542
16543   // If the flag operand isn't dead, don't touch this CMOV.
16544   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16545     return SDValue();
16546
16547   SDValue FalseOp = N->getOperand(0);
16548   SDValue TrueOp = N->getOperand(1);
16549   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16550   SDValue Cond = N->getOperand(3);
16551
16552   if (CC == X86::COND_E || CC == X86::COND_NE) {
16553     switch (Cond.getOpcode()) {
16554     default: break;
16555     case X86ISD::BSR:
16556     case X86ISD::BSF:
16557       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16558       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16559         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16560     }
16561   }
16562
16563   SDValue Flags;
16564
16565   Flags = checkBoolTestSetCCCombine(Cond, CC);
16566   if (Flags.getNode() &&
16567       // Extra check as FCMOV only supports a subset of X86 cond.
16568       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16569     SDValue Ops[] = { FalseOp, TrueOp,
16570                       DAG.getConstant(CC, MVT::i8), Flags };
16571     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16572                        Ops, array_lengthof(Ops));
16573   }
16574
16575   // If this is a select between two integer constants, try to do some
16576   // optimizations.  Note that the operands are ordered the opposite of SELECT
16577   // operands.
16578   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16579     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16580       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16581       // larger than FalseC (the false value).
16582       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16583         CC = X86::GetOppositeBranchCondition(CC);
16584         std::swap(TrueC, FalseC);
16585         std::swap(TrueOp, FalseOp);
16586       }
16587
16588       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16589       // This is efficient for any integer data type (including i8/i16) and
16590       // shift amount.
16591       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16592         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16593                            DAG.getConstant(CC, MVT::i8), Cond);
16594
16595         // Zero extend the condition if needed.
16596         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16597
16598         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16599         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16600                            DAG.getConstant(ShAmt, MVT::i8));
16601         if (N->getNumValues() == 2)  // Dead flag value?
16602           return DCI.CombineTo(N, Cond, SDValue());
16603         return Cond;
16604       }
16605
16606       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16607       // for any integer data type, including i8/i16.
16608       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16609         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16610                            DAG.getConstant(CC, MVT::i8), Cond);
16611
16612         // Zero extend the condition if needed.
16613         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16614                            FalseC->getValueType(0), Cond);
16615         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16616                            SDValue(FalseC, 0));
16617
16618         if (N->getNumValues() == 2)  // Dead flag value?
16619           return DCI.CombineTo(N, Cond, SDValue());
16620         return Cond;
16621       }
16622
16623       // Optimize cases that will turn into an LEA instruction.  This requires
16624       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16625       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16626         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16627         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16628
16629         bool isFastMultiplier = false;
16630         if (Diff < 10) {
16631           switch ((unsigned char)Diff) {
16632           default: break;
16633           case 1:  // result = add base, cond
16634           case 2:  // result = lea base(    , cond*2)
16635           case 3:  // result = lea base(cond, cond*2)
16636           case 4:  // result = lea base(    , cond*4)
16637           case 5:  // result = lea base(cond, cond*4)
16638           case 8:  // result = lea base(    , cond*8)
16639           case 9:  // result = lea base(cond, cond*8)
16640             isFastMultiplier = true;
16641             break;
16642           }
16643         }
16644
16645         if (isFastMultiplier) {
16646           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16647           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16648                              DAG.getConstant(CC, MVT::i8), Cond);
16649           // Zero extend the condition if needed.
16650           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16651                              Cond);
16652           // Scale the condition by the difference.
16653           if (Diff != 1)
16654             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16655                                DAG.getConstant(Diff, Cond.getValueType()));
16656
16657           // Add the base if non-zero.
16658           if (FalseC->getAPIntValue() != 0)
16659             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16660                                SDValue(FalseC, 0));
16661           if (N->getNumValues() == 2)  // Dead flag value?
16662             return DCI.CombineTo(N, Cond, SDValue());
16663           return Cond;
16664         }
16665       }
16666     }
16667   }
16668
16669   // Handle these cases:
16670   //   (select (x != c), e, c) -> select (x != c), e, x),
16671   //   (select (x == c), c, e) -> select (x == c), x, e)
16672   // where the c is an integer constant, and the "select" is the combination
16673   // of CMOV and CMP.
16674   //
16675   // The rationale for this change is that the conditional-move from a constant
16676   // needs two instructions, however, conditional-move from a register needs
16677   // only one instruction.
16678   //
16679   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16680   //  some instruction-combining opportunities. This opt needs to be
16681   //  postponed as late as possible.
16682   //
16683   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16684     // the DCI.xxxx conditions are provided to postpone the optimization as
16685     // late as possible.
16686
16687     ConstantSDNode *CmpAgainst = 0;
16688     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16689         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16690         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16691
16692       if (CC == X86::COND_NE &&
16693           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16694         CC = X86::GetOppositeBranchCondition(CC);
16695         std::swap(TrueOp, FalseOp);
16696       }
16697
16698       if (CC == X86::COND_E &&
16699           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16700         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16701                           DAG.getConstant(CC, MVT::i8), Cond };
16702         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16703                            array_lengthof(Ops));
16704       }
16705     }
16706   }
16707
16708   return SDValue();
16709 }
16710
16711 /// PerformMulCombine - Optimize a single multiply with constant into two
16712 /// in order to implement it with two cheaper instructions, e.g.
16713 /// LEA + SHL, LEA + LEA.
16714 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16715                                  TargetLowering::DAGCombinerInfo &DCI) {
16716   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16717     return SDValue();
16718
16719   EVT VT = N->getValueType(0);
16720   if (VT != MVT::i64)
16721     return SDValue();
16722
16723   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16724   if (!C)
16725     return SDValue();
16726   uint64_t MulAmt = C->getZExtValue();
16727   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16728     return SDValue();
16729
16730   uint64_t MulAmt1 = 0;
16731   uint64_t MulAmt2 = 0;
16732   if ((MulAmt % 9) == 0) {
16733     MulAmt1 = 9;
16734     MulAmt2 = MulAmt / 9;
16735   } else if ((MulAmt % 5) == 0) {
16736     MulAmt1 = 5;
16737     MulAmt2 = MulAmt / 5;
16738   } else if ((MulAmt % 3) == 0) {
16739     MulAmt1 = 3;
16740     MulAmt2 = MulAmt / 3;
16741   }
16742   if (MulAmt2 &&
16743       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16744     SDLoc DL(N);
16745
16746     if (isPowerOf2_64(MulAmt2) &&
16747         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16748       // If second multiplifer is pow2, issue it first. We want the multiply by
16749       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16750       // is an add.
16751       std::swap(MulAmt1, MulAmt2);
16752
16753     SDValue NewMul;
16754     if (isPowerOf2_64(MulAmt1))
16755       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16756                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16757     else
16758       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16759                            DAG.getConstant(MulAmt1, VT));
16760
16761     if (isPowerOf2_64(MulAmt2))
16762       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16763                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16764     else
16765       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16766                            DAG.getConstant(MulAmt2, VT));
16767
16768     // Do not add new nodes to DAG combiner worklist.
16769     DCI.CombineTo(N, NewMul, false);
16770   }
16771   return SDValue();
16772 }
16773
16774 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16775   SDValue N0 = N->getOperand(0);
16776   SDValue N1 = N->getOperand(1);
16777   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16778   EVT VT = N0.getValueType();
16779
16780   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16781   // since the result of setcc_c is all zero's or all ones.
16782   if (VT.isInteger() && !VT.isVector() &&
16783       N1C && N0.getOpcode() == ISD::AND &&
16784       N0.getOperand(1).getOpcode() == ISD::Constant) {
16785     SDValue N00 = N0.getOperand(0);
16786     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16787         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16788           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16789          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16790       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16791       APInt ShAmt = N1C->getAPIntValue();
16792       Mask = Mask.shl(ShAmt);
16793       if (Mask != 0)
16794         return DAG.getNode(ISD::AND, SDLoc(N), VT,
16795                            N00, DAG.getConstant(Mask, VT));
16796     }
16797   }
16798
16799   // Hardware support for vector shifts is sparse which makes us scalarize the
16800   // vector operations in many cases. Also, on sandybridge ADD is faster than
16801   // shl.
16802   // (shl V, 1) -> add V,V
16803   if (isSplatVector(N1.getNode())) {
16804     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16805     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16806     // We shift all of the values by one. In many cases we do not have
16807     // hardware support for this operation. This is better expressed as an ADD
16808     // of two values.
16809     if (N1C && (1 == N1C->getZExtValue())) {
16810       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16811     }
16812   }
16813
16814   return SDValue();
16815 }
16816
16817 /// \brief Returns a vector of 0s if the node in input is a vector logical
16818 /// shift by a constant amount which is known to be bigger than or equal 
16819 /// to the vector element size in bits.
16820 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16821                                       const X86Subtarget *Subtarget) {
16822   EVT VT = N->getValueType(0);
16823
16824   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16825       (!Subtarget->hasInt256() ||
16826        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16827     return SDValue();
16828
16829   SDValue Amt = N->getOperand(1);
16830   SDLoc DL(N);
16831   if (isSplatVector(Amt.getNode())) {
16832     SDValue SclrAmt = Amt->getOperand(0);
16833     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16834       APInt ShiftAmt = C->getAPIntValue();
16835       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16836
16837       // SSE2/AVX2 logical shifts always return a vector of 0s
16838       // if the shift amount is bigger than or equal to 
16839       // the element size. The constant shift amount will be
16840       // encoded as a 8-bit immediate.
16841       if (ShiftAmt.trunc(8).uge(MaxAmount))
16842         return getZeroVector(VT, Subtarget, DAG, DL);
16843     }
16844   }
16845
16846   return SDValue();
16847 }
16848
16849 /// PerformShiftCombine - Combine shifts.
16850 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16851                                    TargetLowering::DAGCombinerInfo &DCI,
16852                                    const X86Subtarget *Subtarget) {
16853   if (N->getOpcode() == ISD::SHL) {
16854     SDValue V = PerformSHLCombine(N, DAG);
16855     if (V.getNode()) return V;
16856   }
16857
16858   if (N->getOpcode() != ISD::SRA) {
16859     // Try to fold this logical shift into a zero vector.
16860     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16861     if (V.getNode()) return V;
16862   }
16863
16864   return SDValue();
16865 }
16866
16867 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16868 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16869 // and friends.  Likewise for OR -> CMPNEQSS.
16870 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16871                             TargetLowering::DAGCombinerInfo &DCI,
16872                             const X86Subtarget *Subtarget) {
16873   unsigned opcode;
16874
16875   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16876   // we're requiring SSE2 for both.
16877   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16878     SDValue N0 = N->getOperand(0);
16879     SDValue N1 = N->getOperand(1);
16880     SDValue CMP0 = N0->getOperand(1);
16881     SDValue CMP1 = N1->getOperand(1);
16882     SDLoc DL(N);
16883
16884     // The SETCCs should both refer to the same CMP.
16885     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16886       return SDValue();
16887
16888     SDValue CMP00 = CMP0->getOperand(0);
16889     SDValue CMP01 = CMP0->getOperand(1);
16890     EVT     VT    = CMP00.getValueType();
16891
16892     if (VT == MVT::f32 || VT == MVT::f64) {
16893       bool ExpectingFlags = false;
16894       // Check for any users that want flags:
16895       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16896            !ExpectingFlags && UI != UE; ++UI)
16897         switch (UI->getOpcode()) {
16898         default:
16899         case ISD::BR_CC:
16900         case ISD::BRCOND:
16901         case ISD::SELECT:
16902           ExpectingFlags = true;
16903           break;
16904         case ISD::CopyToReg:
16905         case ISD::SIGN_EXTEND:
16906         case ISD::ZERO_EXTEND:
16907         case ISD::ANY_EXTEND:
16908           break;
16909         }
16910
16911       if (!ExpectingFlags) {
16912         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16913         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16914
16915         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16916           X86::CondCode tmp = cc0;
16917           cc0 = cc1;
16918           cc1 = tmp;
16919         }
16920
16921         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16922             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16923           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16924           X86ISD::NodeType NTOperator = is64BitFP ?
16925             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16926           // FIXME: need symbolic constants for these magic numbers.
16927           // See X86ATTInstPrinter.cpp:printSSECC().
16928           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16929           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16930                                               DAG.getConstant(x86cc, MVT::i8));
16931           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16932                                               OnesOrZeroesF);
16933           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16934                                       DAG.getConstant(1, MVT::i32));
16935           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16936           return OneBitOfTruth;
16937         }
16938       }
16939     }
16940   }
16941   return SDValue();
16942 }
16943
16944 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16945 /// so it can be folded inside ANDNP.
16946 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16947   EVT VT = N->getValueType(0);
16948
16949   // Match direct AllOnes for 128 and 256-bit vectors
16950   if (ISD::isBuildVectorAllOnes(N))
16951     return true;
16952
16953   // Look through a bit convert.
16954   if (N->getOpcode() == ISD::BITCAST)
16955     N = N->getOperand(0).getNode();
16956
16957   // Sometimes the operand may come from a insert_subvector building a 256-bit
16958   // allones vector
16959   if (VT.is256BitVector() &&
16960       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16961     SDValue V1 = N->getOperand(0);
16962     SDValue V2 = N->getOperand(1);
16963
16964     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16965         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16966         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16967         ISD::isBuildVectorAllOnes(V2.getNode()))
16968       return true;
16969   }
16970
16971   return false;
16972 }
16973
16974 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16975 // register. In most cases we actually compare or select YMM-sized registers
16976 // and mixing the two types creates horrible code. This method optimizes
16977 // some of the transition sequences.
16978 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16979                                  TargetLowering::DAGCombinerInfo &DCI,
16980                                  const X86Subtarget *Subtarget) {
16981   EVT VT = N->getValueType(0);
16982   if (!VT.is256BitVector())
16983     return SDValue();
16984
16985   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16986           N->getOpcode() == ISD::ZERO_EXTEND ||
16987           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16988
16989   SDValue Narrow = N->getOperand(0);
16990   EVT NarrowVT = Narrow->getValueType(0);
16991   if (!NarrowVT.is128BitVector())
16992     return SDValue();
16993
16994   if (Narrow->getOpcode() != ISD::XOR &&
16995       Narrow->getOpcode() != ISD::AND &&
16996       Narrow->getOpcode() != ISD::OR)
16997     return SDValue();
16998
16999   SDValue N0  = Narrow->getOperand(0);
17000   SDValue N1  = Narrow->getOperand(1);
17001   SDLoc DL(Narrow);
17002
17003   // The Left side has to be a trunc.
17004   if (N0.getOpcode() != ISD::TRUNCATE)
17005     return SDValue();
17006
17007   // The type of the truncated inputs.
17008   EVT WideVT = N0->getOperand(0)->getValueType(0);
17009   if (WideVT != VT)
17010     return SDValue();
17011
17012   // The right side has to be a 'trunc' or a constant vector.
17013   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17014   bool RHSConst = (isSplatVector(N1.getNode()) &&
17015                    isa<ConstantSDNode>(N1->getOperand(0)));
17016   if (!RHSTrunc && !RHSConst)
17017     return SDValue();
17018
17019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17020
17021   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17022     return SDValue();
17023
17024   // Set N0 and N1 to hold the inputs to the new wide operation.
17025   N0 = N0->getOperand(0);
17026   if (RHSConst) {
17027     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17028                      N1->getOperand(0));
17029     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17030     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17031   } else if (RHSTrunc) {
17032     N1 = N1->getOperand(0);
17033   }
17034
17035   // Generate the wide operation.
17036   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17037   unsigned Opcode = N->getOpcode();
17038   switch (Opcode) {
17039   case ISD::ANY_EXTEND:
17040     return Op;
17041   case ISD::ZERO_EXTEND: {
17042     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17043     APInt Mask = APInt::getAllOnesValue(InBits);
17044     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17045     return DAG.getNode(ISD::AND, DL, VT,
17046                        Op, DAG.getConstant(Mask, VT));
17047   }
17048   case ISD::SIGN_EXTEND:
17049     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17050                        Op, DAG.getValueType(NarrowVT));
17051   default:
17052     llvm_unreachable("Unexpected opcode");
17053   }
17054 }
17055
17056 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17057                                  TargetLowering::DAGCombinerInfo &DCI,
17058                                  const X86Subtarget *Subtarget) {
17059   EVT VT = N->getValueType(0);
17060   if (DCI.isBeforeLegalizeOps())
17061     return SDValue();
17062
17063   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17064   if (R.getNode())
17065     return R;
17066
17067   // Create BLSI, and BLSR instructions
17068   // BLSI is X & (-X)
17069   // BLSR is X & (X-1)
17070   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
17071     SDValue N0 = N->getOperand(0);
17072     SDValue N1 = N->getOperand(1);
17073     SDLoc DL(N);
17074
17075     // Check LHS for neg
17076     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17077         isZero(N0.getOperand(0)))
17078       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17079
17080     // Check RHS for neg
17081     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17082         isZero(N1.getOperand(0)))
17083       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17084
17085     // Check LHS for X-1
17086     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17087         isAllOnes(N0.getOperand(1)))
17088       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17089
17090     // Check RHS for X-1
17091     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17092         isAllOnes(N1.getOperand(1)))
17093       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17094
17095     return SDValue();
17096   }
17097
17098   // Want to form ANDNP nodes:
17099   // 1) In the hopes of then easily combining them with OR and AND nodes
17100   //    to form PBLEND/PSIGN.
17101   // 2) To match ANDN packed intrinsics
17102   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17103     return SDValue();
17104
17105   SDValue N0 = N->getOperand(0);
17106   SDValue N1 = N->getOperand(1);
17107   SDLoc DL(N);
17108
17109   // Check LHS for vnot
17110   if (N0.getOpcode() == ISD::XOR &&
17111       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17112       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17113     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17114
17115   // Check RHS for vnot
17116   if (N1.getOpcode() == ISD::XOR &&
17117       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17118       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17119     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17120
17121   return SDValue();
17122 }
17123
17124 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17125                                 TargetLowering::DAGCombinerInfo &DCI,
17126                                 const X86Subtarget *Subtarget) {
17127   EVT VT = N->getValueType(0);
17128   if (DCI.isBeforeLegalizeOps())
17129     return SDValue();
17130
17131   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17132   if (R.getNode())
17133     return R;
17134
17135   SDValue N0 = N->getOperand(0);
17136   SDValue N1 = N->getOperand(1);
17137
17138   // look for psign/blend
17139   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17140     if (!Subtarget->hasSSSE3() ||
17141         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17142       return SDValue();
17143
17144     // Canonicalize pandn to RHS
17145     if (N0.getOpcode() == X86ISD::ANDNP)
17146       std::swap(N0, N1);
17147     // or (and (m, y), (pandn m, x))
17148     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17149       SDValue Mask = N1.getOperand(0);
17150       SDValue X    = N1.getOperand(1);
17151       SDValue Y;
17152       if (N0.getOperand(0) == Mask)
17153         Y = N0.getOperand(1);
17154       if (N0.getOperand(1) == Mask)
17155         Y = N0.getOperand(0);
17156
17157       // Check to see if the mask appeared in both the AND and ANDNP and
17158       if (!Y.getNode())
17159         return SDValue();
17160
17161       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17162       // Look through mask bitcast.
17163       if (Mask.getOpcode() == ISD::BITCAST)
17164         Mask = Mask.getOperand(0);
17165       if (X.getOpcode() == ISD::BITCAST)
17166         X = X.getOperand(0);
17167       if (Y.getOpcode() == ISD::BITCAST)
17168         Y = Y.getOperand(0);
17169
17170       EVT MaskVT = Mask.getValueType();
17171
17172       // Validate that the Mask operand is a vector sra node.
17173       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17174       // there is no psrai.b
17175       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17176       unsigned SraAmt = ~0;
17177       if (Mask.getOpcode() == ISD::SRA) {
17178         SDValue Amt = Mask.getOperand(1);
17179         if (isSplatVector(Amt.getNode())) {
17180           SDValue SclrAmt = Amt->getOperand(0);
17181           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17182             SraAmt = C->getZExtValue();
17183         }
17184       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17185         SDValue SraC = Mask.getOperand(1);
17186         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
17187       }
17188       if ((SraAmt + 1) != EltBits)
17189         return SDValue();
17190
17191       SDLoc DL(N);
17192
17193       // Now we know we at least have a plendvb with the mask val.  See if
17194       // we can form a psignb/w/d.
17195       // psign = x.type == y.type == mask.type && y = sub(0, x);
17196       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17197           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17198           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17199         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17200                "Unsupported VT for PSIGN");
17201         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17202         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17203       }
17204       // PBLENDVB only available on SSE 4.1
17205       if (!Subtarget->hasSSE41())
17206         return SDValue();
17207
17208       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17209
17210       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17211       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17212       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17213       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17214       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17215     }
17216   }
17217
17218   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17219     return SDValue();
17220
17221   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17222   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17223     std::swap(N0, N1);
17224   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17225     return SDValue();
17226   if (!N0.hasOneUse() || !N1.hasOneUse())
17227     return SDValue();
17228
17229   SDValue ShAmt0 = N0.getOperand(1);
17230   if (ShAmt0.getValueType() != MVT::i8)
17231     return SDValue();
17232   SDValue ShAmt1 = N1.getOperand(1);
17233   if (ShAmt1.getValueType() != MVT::i8)
17234     return SDValue();
17235   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17236     ShAmt0 = ShAmt0.getOperand(0);
17237   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17238     ShAmt1 = ShAmt1.getOperand(0);
17239
17240   SDLoc DL(N);
17241   unsigned Opc = X86ISD::SHLD;
17242   SDValue Op0 = N0.getOperand(0);
17243   SDValue Op1 = N1.getOperand(0);
17244   if (ShAmt0.getOpcode() == ISD::SUB) {
17245     Opc = X86ISD::SHRD;
17246     std::swap(Op0, Op1);
17247     std::swap(ShAmt0, ShAmt1);
17248   }
17249
17250   unsigned Bits = VT.getSizeInBits();
17251   if (ShAmt1.getOpcode() == ISD::SUB) {
17252     SDValue Sum = ShAmt1.getOperand(0);
17253     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17254       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17255       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17256         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17257       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17258         return DAG.getNode(Opc, DL, VT,
17259                            Op0, Op1,
17260                            DAG.getNode(ISD::TRUNCATE, DL,
17261                                        MVT::i8, ShAmt0));
17262     }
17263   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17264     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17265     if (ShAmt0C &&
17266         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17267       return DAG.getNode(Opc, DL, VT,
17268                          N0.getOperand(0), N1.getOperand(0),
17269                          DAG.getNode(ISD::TRUNCATE, DL,
17270                                        MVT::i8, ShAmt0));
17271   }
17272
17273   return SDValue();
17274 }
17275
17276 // Generate NEG and CMOV for integer abs.
17277 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17278   EVT VT = N->getValueType(0);
17279
17280   // Since X86 does not have CMOV for 8-bit integer, we don't convert
17281   // 8-bit integer abs to NEG and CMOV.
17282   if (VT.isInteger() && VT.getSizeInBits() == 8)
17283     return SDValue();
17284
17285   SDValue N0 = N->getOperand(0);
17286   SDValue N1 = N->getOperand(1);
17287   SDLoc DL(N);
17288
17289   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17290   // and change it to SUB and CMOV.
17291   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17292       N0.getOpcode() == ISD::ADD &&
17293       N0.getOperand(1) == N1 &&
17294       N1.getOpcode() == ISD::SRA &&
17295       N1.getOperand(0) == N0.getOperand(0))
17296     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17297       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17298         // Generate SUB & CMOV.
17299         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17300                                   DAG.getConstant(0, VT), N0.getOperand(0));
17301
17302         SDValue Ops[] = { N0.getOperand(0), Neg,
17303                           DAG.getConstant(X86::COND_GE, MVT::i8),
17304                           SDValue(Neg.getNode(), 1) };
17305         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17306                            Ops, array_lengthof(Ops));
17307       }
17308   return SDValue();
17309 }
17310
17311 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17312 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17313                                  TargetLowering::DAGCombinerInfo &DCI,
17314                                  const X86Subtarget *Subtarget) {
17315   EVT VT = N->getValueType(0);
17316   if (DCI.isBeforeLegalizeOps())
17317     return SDValue();
17318
17319   if (Subtarget->hasCMov()) {
17320     SDValue RV = performIntegerAbsCombine(N, DAG);
17321     if (RV.getNode())
17322       return RV;
17323   }
17324
17325   // Try forming BMI if it is available.
17326   if (!Subtarget->hasBMI())
17327     return SDValue();
17328
17329   if (VT != MVT::i32 && VT != MVT::i64)
17330     return SDValue();
17331
17332   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17333
17334   // Create BLSMSK instructions by finding X ^ (X-1)
17335   SDValue N0 = N->getOperand(0);
17336   SDValue N1 = N->getOperand(1);
17337   SDLoc DL(N);
17338
17339   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17340       isAllOnes(N0.getOperand(1)))
17341     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17342
17343   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17344       isAllOnes(N1.getOperand(1)))
17345     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17346
17347   return SDValue();
17348 }
17349
17350 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17351 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17352                                   TargetLowering::DAGCombinerInfo &DCI,
17353                                   const X86Subtarget *Subtarget) {
17354   LoadSDNode *Ld = cast<LoadSDNode>(N);
17355   EVT RegVT = Ld->getValueType(0);
17356   EVT MemVT = Ld->getMemoryVT();
17357   SDLoc dl(Ld);
17358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17359   unsigned RegSz = RegVT.getSizeInBits();
17360
17361   // On Sandybridge unaligned 256bit loads are inefficient.
17362   ISD::LoadExtType Ext = Ld->getExtensionType();
17363   unsigned Alignment = Ld->getAlignment();
17364   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17365   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17366       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17367     unsigned NumElems = RegVT.getVectorNumElements();
17368     if (NumElems < 2)
17369       return SDValue();
17370
17371     SDValue Ptr = Ld->getBasePtr();
17372     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17373
17374     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17375                                   NumElems/2);
17376     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17377                                 Ld->getPointerInfo(), Ld->isVolatile(),
17378                                 Ld->isNonTemporal(), Ld->isInvariant(),
17379                                 Alignment);
17380     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17381     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17382                                 Ld->getPointerInfo(), Ld->isVolatile(),
17383                                 Ld->isNonTemporal(), Ld->isInvariant(),
17384                                 std::min(16U, Alignment));
17385     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17386                              Load1.getValue(1),
17387                              Load2.getValue(1));
17388
17389     SDValue NewVec = DAG.getUNDEF(RegVT);
17390     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17391     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17392     return DCI.CombineTo(N, NewVec, TF, true);
17393   }
17394
17395   // If this is a vector EXT Load then attempt to optimize it using a
17396   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17397   // expansion is still better than scalar code.
17398   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17399   // emit a shuffle and a arithmetic shift.
17400   // TODO: It is possible to support ZExt by zeroing the undef values
17401   // during the shuffle phase or after the shuffle.
17402   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17403       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17404     assert(MemVT != RegVT && "Cannot extend to the same type");
17405     assert(MemVT.isVector() && "Must load a vector from memory");
17406
17407     unsigned NumElems = RegVT.getVectorNumElements();
17408     unsigned MemSz = MemVT.getSizeInBits();
17409     assert(RegSz > MemSz && "Register size must be greater than the mem size");
17410
17411     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17412       return SDValue();
17413
17414     // All sizes must be a power of two.
17415     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17416       return SDValue();
17417
17418     // Attempt to load the original value using scalar loads.
17419     // Find the largest scalar type that divides the total loaded size.
17420     MVT SclrLoadTy = MVT::i8;
17421     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17422          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17423       MVT Tp = (MVT::SimpleValueType)tp;
17424       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17425         SclrLoadTy = Tp;
17426       }
17427     }
17428
17429     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17430     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17431         (64 <= MemSz))
17432       SclrLoadTy = MVT::f64;
17433
17434     // Calculate the number of scalar loads that we need to perform
17435     // in order to load our vector from memory.
17436     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17437     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17438       return SDValue();
17439
17440     unsigned loadRegZize = RegSz;
17441     if (Ext == ISD::SEXTLOAD && RegSz == 256)
17442       loadRegZize /= 2;
17443
17444     // Represent our vector as a sequence of elements which are the
17445     // largest scalar that we can load.
17446     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17447       loadRegZize/SclrLoadTy.getSizeInBits());
17448
17449     // Represent the data using the same element type that is stored in
17450     // memory. In practice, we ''widen'' MemVT.
17451     EVT WideVecVT =
17452           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17453                        loadRegZize/MemVT.getScalarType().getSizeInBits());
17454
17455     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17456       "Invalid vector type");
17457
17458     // We can't shuffle using an illegal type.
17459     if (!TLI.isTypeLegal(WideVecVT))
17460       return SDValue();
17461
17462     SmallVector<SDValue, 8> Chains;
17463     SDValue Ptr = Ld->getBasePtr();
17464     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17465                                         TLI.getPointerTy());
17466     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17467
17468     for (unsigned i = 0; i < NumLoads; ++i) {
17469       // Perform a single load.
17470       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17471                                        Ptr, Ld->getPointerInfo(),
17472                                        Ld->isVolatile(), Ld->isNonTemporal(),
17473                                        Ld->isInvariant(), Ld->getAlignment());
17474       Chains.push_back(ScalarLoad.getValue(1));
17475       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17476       // another round of DAGCombining.
17477       if (i == 0)
17478         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17479       else
17480         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17481                           ScalarLoad, DAG.getIntPtrConstant(i));
17482
17483       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17484     }
17485
17486     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17487                                Chains.size());
17488
17489     // Bitcast the loaded value to a vector of the original element type, in
17490     // the size of the target vector type.
17491     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17492     unsigned SizeRatio = RegSz/MemSz;
17493
17494     if (Ext == ISD::SEXTLOAD) {
17495       // If we have SSE4.1 we can directly emit a VSEXT node.
17496       if (Subtarget->hasSSE41()) {
17497         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17498         return DCI.CombineTo(N, Sext, TF, true);
17499       }
17500
17501       // Otherwise we'll shuffle the small elements in the high bits of the
17502       // larger type and perform an arithmetic shift. If the shift is not legal
17503       // it's better to scalarize.
17504       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17505         return SDValue();
17506
17507       // Redistribute the loaded elements into the different locations.
17508       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17509       for (unsigned i = 0; i != NumElems; ++i)
17510         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17511
17512       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17513                                            DAG.getUNDEF(WideVecVT),
17514                                            &ShuffleVec[0]);
17515
17516       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17517
17518       // Build the arithmetic shift.
17519       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17520                      MemVT.getVectorElementType().getSizeInBits();
17521       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17522                           DAG.getConstant(Amt, RegVT));
17523
17524       return DCI.CombineTo(N, Shuff, TF, true);
17525     }
17526
17527     // Redistribute the loaded elements into the different locations.
17528     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17529     for (unsigned i = 0; i != NumElems; ++i)
17530       ShuffleVec[i*SizeRatio] = i;
17531
17532     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17533                                          DAG.getUNDEF(WideVecVT),
17534                                          &ShuffleVec[0]);
17535
17536     // Bitcast to the requested type.
17537     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17538     // Replace the original load with the new sequence
17539     // and return the new chain.
17540     return DCI.CombineTo(N, Shuff, TF, true);
17541   }
17542
17543   return SDValue();
17544 }
17545
17546 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17547 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17548                                    const X86Subtarget *Subtarget) {
17549   StoreSDNode *St = cast<StoreSDNode>(N);
17550   EVT VT = St->getValue().getValueType();
17551   EVT StVT = St->getMemoryVT();
17552   SDLoc dl(St);
17553   SDValue StoredVal = St->getOperand(1);
17554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17555
17556   // If we are saving a concatenation of two XMM registers, perform two stores.
17557   // On Sandy Bridge, 256-bit memory operations are executed by two
17558   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17559   // memory  operation.
17560   unsigned Alignment = St->getAlignment();
17561   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17562   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17563       StVT == VT && !IsAligned) {
17564     unsigned NumElems = VT.getVectorNumElements();
17565     if (NumElems < 2)
17566       return SDValue();
17567
17568     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17569     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17570
17571     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17572     SDValue Ptr0 = St->getBasePtr();
17573     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17574
17575     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17576                                 St->getPointerInfo(), St->isVolatile(),
17577                                 St->isNonTemporal(), Alignment);
17578     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17579                                 St->getPointerInfo(), St->isVolatile(),
17580                                 St->isNonTemporal(),
17581                                 std::min(16U, Alignment));
17582     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17583   }
17584
17585   // Optimize trunc store (of multiple scalars) to shuffle and store.
17586   // First, pack all of the elements in one place. Next, store to memory
17587   // in fewer chunks.
17588   if (St->isTruncatingStore() && VT.isVector()) {
17589     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17590     unsigned NumElems = VT.getVectorNumElements();
17591     assert(StVT != VT && "Cannot truncate to the same type");
17592     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17593     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17594
17595     // From, To sizes and ElemCount must be pow of two
17596     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17597     // We are going to use the original vector elt for storing.
17598     // Accumulated smaller vector elements must be a multiple of the store size.
17599     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17600
17601     unsigned SizeRatio  = FromSz / ToSz;
17602
17603     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17604
17605     // Create a type on which we perform the shuffle
17606     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17607             StVT.getScalarType(), NumElems*SizeRatio);
17608
17609     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17610
17611     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17612     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17613     for (unsigned i = 0; i != NumElems; ++i)
17614       ShuffleVec[i] = i * SizeRatio;
17615
17616     // Can't shuffle using an illegal type.
17617     if (!TLI.isTypeLegal(WideVecVT))
17618       return SDValue();
17619
17620     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17621                                          DAG.getUNDEF(WideVecVT),
17622                                          &ShuffleVec[0]);
17623     // At this point all of the data is stored at the bottom of the
17624     // register. We now need to save it to mem.
17625
17626     // Find the largest store unit
17627     MVT StoreType = MVT::i8;
17628     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17629          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17630       MVT Tp = (MVT::SimpleValueType)tp;
17631       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17632         StoreType = Tp;
17633     }
17634
17635     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17636     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17637         (64 <= NumElems * ToSz))
17638       StoreType = MVT::f64;
17639
17640     // Bitcast the original vector into a vector of store-size units
17641     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17642             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17643     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17644     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17645     SmallVector<SDValue, 8> Chains;
17646     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17647                                         TLI.getPointerTy());
17648     SDValue Ptr = St->getBasePtr();
17649
17650     // Perform one or more big stores into memory.
17651     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17652       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17653                                    StoreType, ShuffWide,
17654                                    DAG.getIntPtrConstant(i));
17655       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17656                                 St->getPointerInfo(), St->isVolatile(),
17657                                 St->isNonTemporal(), St->getAlignment());
17658       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17659       Chains.push_back(Ch);
17660     }
17661
17662     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17663                                Chains.size());
17664   }
17665
17666   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17667   // the FP state in cases where an emms may be missing.
17668   // A preferable solution to the general problem is to figure out the right
17669   // places to insert EMMS.  This qualifies as a quick hack.
17670
17671   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17672   if (VT.getSizeInBits() != 64)
17673     return SDValue();
17674
17675   const Function *F = DAG.getMachineFunction().getFunction();
17676   bool NoImplicitFloatOps = F->getAttributes().
17677     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17678   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17679                      && Subtarget->hasSSE2();
17680   if ((VT.isVector() ||
17681        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17682       isa<LoadSDNode>(St->getValue()) &&
17683       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17684       St->getChain().hasOneUse() && !St->isVolatile()) {
17685     SDNode* LdVal = St->getValue().getNode();
17686     LoadSDNode *Ld = 0;
17687     int TokenFactorIndex = -1;
17688     SmallVector<SDValue, 8> Ops;
17689     SDNode* ChainVal = St->getChain().getNode();
17690     // Must be a store of a load.  We currently handle two cases:  the load
17691     // is a direct child, and it's under an intervening TokenFactor.  It is
17692     // possible to dig deeper under nested TokenFactors.
17693     if (ChainVal == LdVal)
17694       Ld = cast<LoadSDNode>(St->getChain());
17695     else if (St->getValue().hasOneUse() &&
17696              ChainVal->getOpcode() == ISD::TokenFactor) {
17697       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17698         if (ChainVal->getOperand(i).getNode() == LdVal) {
17699           TokenFactorIndex = i;
17700           Ld = cast<LoadSDNode>(St->getValue());
17701         } else
17702           Ops.push_back(ChainVal->getOperand(i));
17703       }
17704     }
17705
17706     if (!Ld || !ISD::isNormalLoad(Ld))
17707       return SDValue();
17708
17709     // If this is not the MMX case, i.e. we are just turning i64 load/store
17710     // into f64 load/store, avoid the transformation if there are multiple
17711     // uses of the loaded value.
17712     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17713       return SDValue();
17714
17715     SDLoc LdDL(Ld);
17716     SDLoc StDL(N);
17717     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17718     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17719     // pair instead.
17720     if (Subtarget->is64Bit() || F64IsLegal) {
17721       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17722       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17723                                   Ld->getPointerInfo(), Ld->isVolatile(),
17724                                   Ld->isNonTemporal(), Ld->isInvariant(),
17725                                   Ld->getAlignment());
17726       SDValue NewChain = NewLd.getValue(1);
17727       if (TokenFactorIndex != -1) {
17728         Ops.push_back(NewChain);
17729         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17730                                Ops.size());
17731       }
17732       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17733                           St->getPointerInfo(),
17734                           St->isVolatile(), St->isNonTemporal(),
17735                           St->getAlignment());
17736     }
17737
17738     // Otherwise, lower to two pairs of 32-bit loads / stores.
17739     SDValue LoAddr = Ld->getBasePtr();
17740     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17741                                  DAG.getConstant(4, MVT::i32));
17742
17743     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17744                                Ld->getPointerInfo(),
17745                                Ld->isVolatile(), Ld->isNonTemporal(),
17746                                Ld->isInvariant(), Ld->getAlignment());
17747     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17748                                Ld->getPointerInfo().getWithOffset(4),
17749                                Ld->isVolatile(), Ld->isNonTemporal(),
17750                                Ld->isInvariant(),
17751                                MinAlign(Ld->getAlignment(), 4));
17752
17753     SDValue NewChain = LoLd.getValue(1);
17754     if (TokenFactorIndex != -1) {
17755       Ops.push_back(LoLd);
17756       Ops.push_back(HiLd);
17757       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17758                              Ops.size());
17759     }
17760
17761     LoAddr = St->getBasePtr();
17762     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17763                          DAG.getConstant(4, MVT::i32));
17764
17765     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17766                                 St->getPointerInfo(),
17767                                 St->isVolatile(), St->isNonTemporal(),
17768                                 St->getAlignment());
17769     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17770                                 St->getPointerInfo().getWithOffset(4),
17771                                 St->isVolatile(),
17772                                 St->isNonTemporal(),
17773                                 MinAlign(St->getAlignment(), 4));
17774     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17775   }
17776   return SDValue();
17777 }
17778
17779 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17780 /// and return the operands for the horizontal operation in LHS and RHS.  A
17781 /// horizontal operation performs the binary operation on successive elements
17782 /// of its first operand, then on successive elements of its second operand,
17783 /// returning the resulting values in a vector.  For example, if
17784 ///   A = < float a0, float a1, float a2, float a3 >
17785 /// and
17786 ///   B = < float b0, float b1, float b2, float b3 >
17787 /// then the result of doing a horizontal operation on A and B is
17788 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17789 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17790 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17791 /// set to A, RHS to B, and the routine returns 'true'.
17792 /// Note that the binary operation should have the property that if one of the
17793 /// operands is UNDEF then the result is UNDEF.
17794 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17795   // Look for the following pattern: if
17796   //   A = < float a0, float a1, float a2, float a3 >
17797   //   B = < float b0, float b1, float b2, float b3 >
17798   // and
17799   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17800   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17801   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17802   // which is A horizontal-op B.
17803
17804   // At least one of the operands should be a vector shuffle.
17805   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17806       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17807     return false;
17808
17809   MVT VT = LHS.getValueType().getSimpleVT();
17810
17811   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17812          "Unsupported vector type for horizontal add/sub");
17813
17814   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17815   // operate independently on 128-bit lanes.
17816   unsigned NumElts = VT.getVectorNumElements();
17817   unsigned NumLanes = VT.getSizeInBits()/128;
17818   unsigned NumLaneElts = NumElts / NumLanes;
17819   assert((NumLaneElts % 2 == 0) &&
17820          "Vector type should have an even number of elements in each lane");
17821   unsigned HalfLaneElts = NumLaneElts/2;
17822
17823   // View LHS in the form
17824   //   LHS = VECTOR_SHUFFLE A, B, LMask
17825   // If LHS is not a shuffle then pretend it is the shuffle
17826   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17827   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17828   // type VT.
17829   SDValue A, B;
17830   SmallVector<int, 16> LMask(NumElts);
17831   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17832     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17833       A = LHS.getOperand(0);
17834     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17835       B = LHS.getOperand(1);
17836     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17837     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17838   } else {
17839     if (LHS.getOpcode() != ISD::UNDEF)
17840       A = LHS;
17841     for (unsigned i = 0; i != NumElts; ++i)
17842       LMask[i] = i;
17843   }
17844
17845   // Likewise, view RHS in the form
17846   //   RHS = VECTOR_SHUFFLE C, D, RMask
17847   SDValue C, D;
17848   SmallVector<int, 16> RMask(NumElts);
17849   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17850     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17851       C = RHS.getOperand(0);
17852     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17853       D = RHS.getOperand(1);
17854     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17855     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17856   } else {
17857     if (RHS.getOpcode() != ISD::UNDEF)
17858       C = RHS;
17859     for (unsigned i = 0; i != NumElts; ++i)
17860       RMask[i] = i;
17861   }
17862
17863   // Check that the shuffles are both shuffling the same vectors.
17864   if (!(A == C && B == D) && !(A == D && B == C))
17865     return false;
17866
17867   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17868   if (!A.getNode() && !B.getNode())
17869     return false;
17870
17871   // If A and B occur in reverse order in RHS, then "swap" them (which means
17872   // rewriting the mask).
17873   if (A != C)
17874     CommuteVectorShuffleMask(RMask, NumElts);
17875
17876   // At this point LHS and RHS are equivalent to
17877   //   LHS = VECTOR_SHUFFLE A, B, LMask
17878   //   RHS = VECTOR_SHUFFLE A, B, RMask
17879   // Check that the masks correspond to performing a horizontal operation.
17880   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
17881     for (unsigned i = 0; i != NumLaneElts; ++i) {
17882       int LIdx = LMask[i+l], RIdx = RMask[i+l];
17883
17884       // Ignore any UNDEF components.
17885       if (LIdx < 0 || RIdx < 0 ||
17886           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17887           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17888         continue;
17889
17890       // Check that successive elements are being operated on.  If not, this is
17891       // not a horizontal operation.
17892       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
17893       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
17894       if (!(LIdx == Index && RIdx == Index + 1) &&
17895           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17896         return false;
17897     }
17898   }
17899
17900   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17901   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17902   return true;
17903 }
17904
17905 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17906 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17907                                   const X86Subtarget *Subtarget) {
17908   EVT VT = N->getValueType(0);
17909   SDValue LHS = N->getOperand(0);
17910   SDValue RHS = N->getOperand(1);
17911
17912   // Try to synthesize horizontal adds from adds of shuffles.
17913   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17914        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17915       isHorizontalBinOp(LHS, RHS, true))
17916     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17917   return SDValue();
17918 }
17919
17920 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17921 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17922                                   const X86Subtarget *Subtarget) {
17923   EVT VT = N->getValueType(0);
17924   SDValue LHS = N->getOperand(0);
17925   SDValue RHS = N->getOperand(1);
17926
17927   // Try to synthesize horizontal subs from subs of shuffles.
17928   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17929        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17930       isHorizontalBinOp(LHS, RHS, false))
17931     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17932   return SDValue();
17933 }
17934
17935 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17936 /// X86ISD::FXOR nodes.
17937 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17938   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17939   // F[X]OR(0.0, x) -> x
17940   // F[X]OR(x, 0.0) -> x
17941   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17942     if (C->getValueAPF().isPosZero())
17943       return N->getOperand(1);
17944   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17945     if (C->getValueAPF().isPosZero())
17946       return N->getOperand(0);
17947   return SDValue();
17948 }
17949
17950 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17951 /// X86ISD::FMAX nodes.
17952 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17953   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17954
17955   // Only perform optimizations if UnsafeMath is used.
17956   if (!DAG.getTarget().Options.UnsafeFPMath)
17957     return SDValue();
17958
17959   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17960   // into FMINC and FMAXC, which are Commutative operations.
17961   unsigned NewOp = 0;
17962   switch (N->getOpcode()) {
17963     default: llvm_unreachable("unknown opcode");
17964     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17965     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17966   }
17967
17968   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17969                      N->getOperand(0), N->getOperand(1));
17970 }
17971
17972 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17973 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17974   // FAND(0.0, x) -> 0.0
17975   // FAND(x, 0.0) -> 0.0
17976   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17977     if (C->getValueAPF().isPosZero())
17978       return N->getOperand(0);
17979   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17980     if (C->getValueAPF().isPosZero())
17981       return N->getOperand(1);
17982   return SDValue();
17983 }
17984
17985 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
17986 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
17987   // FANDN(x, 0.0) -> 0.0
17988   // FANDN(0.0, x) -> x
17989   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17990     if (C->getValueAPF().isPosZero())
17991       return N->getOperand(1);
17992   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17993     if (C->getValueAPF().isPosZero())
17994       return N->getOperand(1);
17995   return SDValue();
17996 }
17997
17998 static SDValue PerformBTCombine(SDNode *N,
17999                                 SelectionDAG &DAG,
18000                                 TargetLowering::DAGCombinerInfo &DCI) {
18001   // BT ignores high bits in the bit index operand.
18002   SDValue Op1 = N->getOperand(1);
18003   if (Op1.hasOneUse()) {
18004     unsigned BitWidth = Op1.getValueSizeInBits();
18005     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18006     APInt KnownZero, KnownOne;
18007     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18008                                           !DCI.isBeforeLegalizeOps());
18009     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18010     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18011         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18012       DCI.CommitTargetLoweringOpt(TLO);
18013   }
18014   return SDValue();
18015 }
18016
18017 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18018   SDValue Op = N->getOperand(0);
18019   if (Op.getOpcode() == ISD::BITCAST)
18020     Op = Op.getOperand(0);
18021   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18022   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18023       VT.getVectorElementType().getSizeInBits() ==
18024       OpVT.getVectorElementType().getSizeInBits()) {
18025     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18026   }
18027   return SDValue();
18028 }
18029
18030 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18031                                                const X86Subtarget *Subtarget) {
18032   EVT VT = N->getValueType(0);
18033   if (!VT.isVector())
18034     return SDValue();
18035
18036   SDValue N0 = N->getOperand(0);
18037   SDValue N1 = N->getOperand(1);
18038   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18039   SDLoc dl(N);
18040
18041   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18042   // both SSE and AVX2 since there is no sign-extended shift right
18043   // operation on a vector with 64-bit elements.
18044   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18045   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18046   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18047       N0.getOpcode() == ISD::SIGN_EXTEND)) {
18048     SDValue N00 = N0.getOperand(0);
18049
18050     // EXTLOAD has a better solution on AVX2,
18051     // it may be replaced with X86ISD::VSEXT node.
18052     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18053       if (!ISD::isNormalLoad(N00.getNode()))
18054         return SDValue();
18055
18056     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18057         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18058                                   N00, N1);
18059       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18060     }
18061   }
18062   return SDValue();
18063 }
18064
18065 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18066                                   TargetLowering::DAGCombinerInfo &DCI,
18067                                   const X86Subtarget *Subtarget) {
18068   if (!DCI.isBeforeLegalizeOps())
18069     return SDValue();
18070
18071   if (!Subtarget->hasFp256())
18072     return SDValue();
18073
18074   EVT VT = N->getValueType(0);
18075   if (VT.isVector() && VT.getSizeInBits() == 256) {
18076     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18077     if (R.getNode())
18078       return R;
18079   }
18080
18081   return SDValue();
18082 }
18083
18084 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18085                                  const X86Subtarget* Subtarget) {
18086   SDLoc dl(N);
18087   EVT VT = N->getValueType(0);
18088
18089   // Let legalize expand this if it isn't a legal type yet.
18090   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18091     return SDValue();
18092
18093   EVT ScalarVT = VT.getScalarType();
18094   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18095       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18096     return SDValue();
18097
18098   SDValue A = N->getOperand(0);
18099   SDValue B = N->getOperand(1);
18100   SDValue C = N->getOperand(2);
18101
18102   bool NegA = (A.getOpcode() == ISD::FNEG);
18103   bool NegB = (B.getOpcode() == ISD::FNEG);
18104   bool NegC = (C.getOpcode() == ISD::FNEG);
18105
18106   // Negative multiplication when NegA xor NegB
18107   bool NegMul = (NegA != NegB);
18108   if (NegA)
18109     A = A.getOperand(0);
18110   if (NegB)
18111     B = B.getOperand(0);
18112   if (NegC)
18113     C = C.getOperand(0);
18114
18115   unsigned Opcode;
18116   if (!NegMul)
18117     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18118   else
18119     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18120
18121   return DAG.getNode(Opcode, dl, VT, A, B, C);
18122 }
18123
18124 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18125                                   TargetLowering::DAGCombinerInfo &DCI,
18126                                   const X86Subtarget *Subtarget) {
18127   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18128   //           (and (i32 x86isd::setcc_carry), 1)
18129   // This eliminates the zext. This transformation is necessary because
18130   // ISD::SETCC is always legalized to i8.
18131   SDLoc dl(N);
18132   SDValue N0 = N->getOperand(0);
18133   EVT VT = N->getValueType(0);
18134
18135   if (N0.getOpcode() == ISD::AND &&
18136       N0.hasOneUse() &&
18137       N0.getOperand(0).hasOneUse()) {
18138     SDValue N00 = N0.getOperand(0);
18139     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18140       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18141       if (!C || C->getZExtValue() != 1)
18142         return SDValue();
18143       return DAG.getNode(ISD::AND, dl, VT,
18144                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18145                                      N00.getOperand(0), N00.getOperand(1)),
18146                          DAG.getConstant(1, VT));
18147     }
18148   }
18149
18150   if (VT.is256BitVector()) {
18151     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18152     if (R.getNode())
18153       return R;
18154   }
18155
18156   return SDValue();
18157 }
18158
18159 // Optimize x == -y --> x+y == 0
18160 //          x != -y --> x+y != 0
18161 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18162   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18163   SDValue LHS = N->getOperand(0);
18164   SDValue RHS = N->getOperand(1);
18165
18166   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18167     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18168       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18169         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18170                                    LHS.getValueType(), RHS, LHS.getOperand(1));
18171         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18172                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18173       }
18174   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18175     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18176       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18177         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18178                                    RHS.getValueType(), LHS, RHS.getOperand(1));
18179         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18180                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18181       }
18182   return SDValue();
18183 }
18184
18185 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18186 // as "sbb reg,reg", since it can be extended without zext and produces
18187 // an all-ones bit which is more useful than 0/1 in some cases.
18188 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18189   return DAG.getNode(ISD::AND, DL, MVT::i8,
18190                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18191                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18192                      DAG.getConstant(1, MVT::i8));
18193 }
18194
18195 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18196 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18197                                    TargetLowering::DAGCombinerInfo &DCI,
18198                                    const X86Subtarget *Subtarget) {
18199   SDLoc DL(N);
18200   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18201   SDValue EFLAGS = N->getOperand(1);
18202
18203   if (CC == X86::COND_A) {
18204     // Try to convert COND_A into COND_B in an attempt to facilitate
18205     // materializing "setb reg".
18206     //
18207     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18208     // cannot take an immediate as its first operand.
18209     //
18210     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18211         EFLAGS.getValueType().isInteger() &&
18212         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18213       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18214                                    EFLAGS.getNode()->getVTList(),
18215                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
18216       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
18217       return MaterializeSETB(DL, NewEFLAGS, DAG);
18218     }
18219   }
18220
18221   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
18222   // a zext and produces an all-ones bit which is more useful than 0/1 in some
18223   // cases.
18224   if (CC == X86::COND_B)
18225     return MaterializeSETB(DL, EFLAGS, DAG);
18226
18227   SDValue Flags;
18228
18229   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18230   if (Flags.getNode()) {
18231     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18232     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
18233   }
18234
18235   return SDValue();
18236 }
18237
18238 // Optimize branch condition evaluation.
18239 //
18240 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18241                                     TargetLowering::DAGCombinerInfo &DCI,
18242                                     const X86Subtarget *Subtarget) {
18243   SDLoc DL(N);
18244   SDValue Chain = N->getOperand(0);
18245   SDValue Dest = N->getOperand(1);
18246   SDValue EFLAGS = N->getOperand(3);
18247   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18248
18249   SDValue Flags;
18250
18251   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18252   if (Flags.getNode()) {
18253     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18254     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18255                        Flags);
18256   }
18257
18258   return SDValue();
18259 }
18260
18261 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18262                                         const X86TargetLowering *XTLI) {
18263   SDValue Op0 = N->getOperand(0);
18264   EVT InVT = Op0->getValueType(0);
18265
18266   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18267   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18268     SDLoc dl(N);
18269     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18270     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18271     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18272   }
18273
18274   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18275   // a 32-bit target where SSE doesn't support i64->FP operations.
18276   if (Op0.getOpcode() == ISD::LOAD) {
18277     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18278     EVT VT = Ld->getValueType(0);
18279     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18280         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18281         !XTLI->getSubtarget()->is64Bit() &&
18282         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18283       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18284                                           Ld->getChain(), Op0, DAG);
18285       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18286       return FILDChain;
18287     }
18288   }
18289   return SDValue();
18290 }
18291
18292 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18293 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18294                                  X86TargetLowering::DAGCombinerInfo &DCI) {
18295   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18296   // the result is either zero or one (depending on the input carry bit).
18297   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18298   if (X86::isZeroNode(N->getOperand(0)) &&
18299       X86::isZeroNode(N->getOperand(1)) &&
18300       // We don't have a good way to replace an EFLAGS use, so only do this when
18301       // dead right now.
18302       SDValue(N, 1).use_empty()) {
18303     SDLoc DL(N);
18304     EVT VT = N->getValueType(0);
18305     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18306     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18307                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18308                                            DAG.getConstant(X86::COND_B,MVT::i8),
18309                                            N->getOperand(2)),
18310                                DAG.getConstant(1, VT));
18311     return DCI.CombineTo(N, Res1, CarryOut);
18312   }
18313
18314   return SDValue();
18315 }
18316
18317 // fold (add Y, (sete  X, 0)) -> adc  0, Y
18318 //      (add Y, (setne X, 0)) -> sbb -1, Y
18319 //      (sub (sete  X, 0), Y) -> sbb  0, Y
18320 //      (sub (setne X, 0), Y) -> adc -1, Y
18321 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18322   SDLoc DL(N);
18323
18324   // Look through ZExts.
18325   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18326   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18327     return SDValue();
18328
18329   SDValue SetCC = Ext.getOperand(0);
18330   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18331     return SDValue();
18332
18333   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18334   if (CC != X86::COND_E && CC != X86::COND_NE)
18335     return SDValue();
18336
18337   SDValue Cmp = SetCC.getOperand(1);
18338   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18339       !X86::isZeroNode(Cmp.getOperand(1)) ||
18340       !Cmp.getOperand(0).getValueType().isInteger())
18341     return SDValue();
18342
18343   SDValue CmpOp0 = Cmp.getOperand(0);
18344   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18345                                DAG.getConstant(1, CmpOp0.getValueType()));
18346
18347   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18348   if (CC == X86::COND_NE)
18349     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18350                        DL, OtherVal.getValueType(), OtherVal,
18351                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18352   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18353                      DL, OtherVal.getValueType(), OtherVal,
18354                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18355 }
18356
18357 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18358 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18359                                  const X86Subtarget *Subtarget) {
18360   EVT VT = N->getValueType(0);
18361   SDValue Op0 = N->getOperand(0);
18362   SDValue Op1 = N->getOperand(1);
18363
18364   // Try to synthesize horizontal adds from adds of shuffles.
18365   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18366        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18367       isHorizontalBinOp(Op0, Op1, true))
18368     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18369
18370   return OptimizeConditionalInDecrement(N, DAG);
18371 }
18372
18373 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18374                                  const X86Subtarget *Subtarget) {
18375   SDValue Op0 = N->getOperand(0);
18376   SDValue Op1 = N->getOperand(1);
18377
18378   // X86 can't encode an immediate LHS of a sub. See if we can push the
18379   // negation into a preceding instruction.
18380   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18381     // If the RHS of the sub is a XOR with one use and a constant, invert the
18382     // immediate. Then add one to the LHS of the sub so we can turn
18383     // X-Y -> X+~Y+1, saving one register.
18384     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18385         isa<ConstantSDNode>(Op1.getOperand(1))) {
18386       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18387       EVT VT = Op0.getValueType();
18388       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18389                                    Op1.getOperand(0),
18390                                    DAG.getConstant(~XorC, VT));
18391       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18392                          DAG.getConstant(C->getAPIntValue()+1, VT));
18393     }
18394   }
18395
18396   // Try to synthesize horizontal adds from adds of shuffles.
18397   EVT VT = N->getValueType(0);
18398   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18399        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18400       isHorizontalBinOp(Op0, Op1, true))
18401     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18402
18403   return OptimizeConditionalInDecrement(N, DAG);
18404 }
18405
18406 /// performVZEXTCombine - Performs build vector combines
18407 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18408                                         TargetLowering::DAGCombinerInfo &DCI,
18409                                         const X86Subtarget *Subtarget) {
18410   // (vzext (bitcast (vzext (x)) -> (vzext x)
18411   SDValue In = N->getOperand(0);
18412   while (In.getOpcode() == ISD::BITCAST)
18413     In = In.getOperand(0);
18414
18415   if (In.getOpcode() != X86ISD::VZEXT)
18416     return SDValue();
18417
18418   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18419                      In.getOperand(0));
18420 }
18421
18422 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18423                                              DAGCombinerInfo &DCI) const {
18424   SelectionDAG &DAG = DCI.DAG;
18425   switch (N->getOpcode()) {
18426   default: break;
18427   case ISD::EXTRACT_VECTOR_ELT:
18428     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18429   case ISD::VSELECT:
18430   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18431   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18432   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
18433   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
18434   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
18435   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
18436   case ISD::SHL:
18437   case ISD::SRA:
18438   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
18439   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
18440   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
18441   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
18442   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
18443   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
18444   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
18445   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
18446   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
18447   case X86ISD::FXOR:
18448   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
18449   case X86ISD::FMIN:
18450   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
18451   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
18452   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
18453   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
18454   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
18455   case ISD::ANY_EXTEND:
18456   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
18457   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
18458   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18459   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18460   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
18461   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18462   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18463   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
18464   case X86ISD::SHUFP:       // Handle all target specific shuffles
18465   case X86ISD::PALIGNR:
18466   case X86ISD::UNPCKH:
18467   case X86ISD::UNPCKL:
18468   case X86ISD::MOVHLPS:
18469   case X86ISD::MOVLHPS:
18470   case X86ISD::PSHUFD:
18471   case X86ISD::PSHUFHW:
18472   case X86ISD::PSHUFLW:
18473   case X86ISD::MOVSS:
18474   case X86ISD::MOVSD:
18475   case X86ISD::VPERMILP:
18476   case X86ISD::VPERM2X128:
18477   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18478   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
18479   }
18480
18481   return SDValue();
18482 }
18483
18484 /// isTypeDesirableForOp - Return true if the target has native support for
18485 /// the specified value type and it is 'desirable' to use the type for the
18486 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18487 /// instruction encodings are longer and some i16 instructions are slow.
18488 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18489   if (!isTypeLegal(VT))
18490     return false;
18491   if (VT != MVT::i16)
18492     return true;
18493
18494   switch (Opc) {
18495   default:
18496     return true;
18497   case ISD::LOAD:
18498   case ISD::SIGN_EXTEND:
18499   case ISD::ZERO_EXTEND:
18500   case ISD::ANY_EXTEND:
18501   case ISD::SHL:
18502   case ISD::SRL:
18503   case ISD::SUB:
18504   case ISD::ADD:
18505   case ISD::MUL:
18506   case ISD::AND:
18507   case ISD::OR:
18508   case ISD::XOR:
18509     return false;
18510   }
18511 }
18512
18513 /// IsDesirableToPromoteOp - This method query the target whether it is
18514 /// beneficial for dag combiner to promote the specified node. If true, it
18515 /// should return the desired promotion type by reference.
18516 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18517   EVT VT = Op.getValueType();
18518   if (VT != MVT::i16)
18519     return false;
18520
18521   bool Promote = false;
18522   bool Commute = false;
18523   switch (Op.getOpcode()) {
18524   default: break;
18525   case ISD::LOAD: {
18526     LoadSDNode *LD = cast<LoadSDNode>(Op);
18527     // If the non-extending load has a single use and it's not live out, then it
18528     // might be folded.
18529     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18530                                                      Op.hasOneUse()*/) {
18531       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18532              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18533         // The only case where we'd want to promote LOAD (rather then it being
18534         // promoted as an operand is when it's only use is liveout.
18535         if (UI->getOpcode() != ISD::CopyToReg)
18536           return false;
18537       }
18538     }
18539     Promote = true;
18540     break;
18541   }
18542   case ISD::SIGN_EXTEND:
18543   case ISD::ZERO_EXTEND:
18544   case ISD::ANY_EXTEND:
18545     Promote = true;
18546     break;
18547   case ISD::SHL:
18548   case ISD::SRL: {
18549     SDValue N0 = Op.getOperand(0);
18550     // Look out for (store (shl (load), x)).
18551     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18552       return false;
18553     Promote = true;
18554     break;
18555   }
18556   case ISD::ADD:
18557   case ISD::MUL:
18558   case ISD::AND:
18559   case ISD::OR:
18560   case ISD::XOR:
18561     Commute = true;
18562     // fallthrough
18563   case ISD::SUB: {
18564     SDValue N0 = Op.getOperand(0);
18565     SDValue N1 = Op.getOperand(1);
18566     if (!Commute && MayFoldLoad(N1))
18567       return false;
18568     // Avoid disabling potential load folding opportunities.
18569     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18570       return false;
18571     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18572       return false;
18573     Promote = true;
18574   }
18575   }
18576
18577   PVT = MVT::i32;
18578   return Promote;
18579 }
18580
18581 //===----------------------------------------------------------------------===//
18582 //                           X86 Inline Assembly Support
18583 //===----------------------------------------------------------------------===//
18584
18585 namespace {
18586   // Helper to match a string separated by whitespace.
18587   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18588     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18589
18590     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18591       StringRef piece(*args[i]);
18592       if (!s.startswith(piece)) // Check if the piece matches.
18593         return false;
18594
18595       s = s.substr(piece.size());
18596       StringRef::size_type pos = s.find_first_not_of(" \t");
18597       if (pos == 0) // We matched a prefix.
18598         return false;
18599
18600       s = s.substr(pos);
18601     }
18602
18603     return s.empty();
18604   }
18605   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18606 }
18607
18608 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18609   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18610
18611   std::string AsmStr = IA->getAsmString();
18612
18613   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18614   if (!Ty || Ty->getBitWidth() % 16 != 0)
18615     return false;
18616
18617   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18618   SmallVector<StringRef, 4> AsmPieces;
18619   SplitString(AsmStr, AsmPieces, ";\n");
18620
18621   switch (AsmPieces.size()) {
18622   default: return false;
18623   case 1:
18624     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18625     // we will turn this bswap into something that will be lowered to logical
18626     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18627     // lower so don't worry about this.
18628     // bswap $0
18629     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18630         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18631         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18632         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18633         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18634         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18635       // No need to check constraints, nothing other than the equivalent of
18636       // "=r,0" would be valid here.
18637       return IntrinsicLowering::LowerToByteSwap(CI);
18638     }
18639
18640     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18641     if (CI->getType()->isIntegerTy(16) &&
18642         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18643         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18644          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18645       AsmPieces.clear();
18646       const std::string &ConstraintsStr = IA->getConstraintString();
18647       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18648       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18649       if (AsmPieces.size() == 4 &&
18650           AsmPieces[0] == "~{cc}" &&
18651           AsmPieces[1] == "~{dirflag}" &&
18652           AsmPieces[2] == "~{flags}" &&
18653           AsmPieces[3] == "~{fpsr}")
18654       return IntrinsicLowering::LowerToByteSwap(CI);
18655     }
18656     break;
18657   case 3:
18658     if (CI->getType()->isIntegerTy(32) &&
18659         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18660         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18661         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18662         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18663       AsmPieces.clear();
18664       const std::string &ConstraintsStr = IA->getConstraintString();
18665       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18666       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18667       if (AsmPieces.size() == 4 &&
18668           AsmPieces[0] == "~{cc}" &&
18669           AsmPieces[1] == "~{dirflag}" &&
18670           AsmPieces[2] == "~{flags}" &&
18671           AsmPieces[3] == "~{fpsr}")
18672         return IntrinsicLowering::LowerToByteSwap(CI);
18673     }
18674
18675     if (CI->getType()->isIntegerTy(64)) {
18676       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18677       if (Constraints.size() >= 2 &&
18678           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18679           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18680         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18681         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18682             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18683             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18684           return IntrinsicLowering::LowerToByteSwap(CI);
18685       }
18686     }
18687     break;
18688   }
18689   return false;
18690 }
18691
18692 /// getConstraintType - Given a constraint letter, return the type of
18693 /// constraint it is for this target.
18694 X86TargetLowering::ConstraintType
18695 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18696   if (Constraint.size() == 1) {
18697     switch (Constraint[0]) {
18698     case 'R':
18699     case 'q':
18700     case 'Q':
18701     case 'f':
18702     case 't':
18703     case 'u':
18704     case 'y':
18705     case 'x':
18706     case 'Y':
18707     case 'l':
18708       return C_RegisterClass;
18709     case 'a':
18710     case 'b':
18711     case 'c':
18712     case 'd':
18713     case 'S':
18714     case 'D':
18715     case 'A':
18716       return C_Register;
18717     case 'I':
18718     case 'J':
18719     case 'K':
18720     case 'L':
18721     case 'M':
18722     case 'N':
18723     case 'G':
18724     case 'C':
18725     case 'e':
18726     case 'Z':
18727       return C_Other;
18728     default:
18729       break;
18730     }
18731   }
18732   return TargetLowering::getConstraintType(Constraint);
18733 }
18734
18735 /// Examine constraint type and operand type and determine a weight value.
18736 /// This object must already have been set up with the operand type
18737 /// and the current alternative constraint selected.
18738 TargetLowering::ConstraintWeight
18739   X86TargetLowering::getSingleConstraintMatchWeight(
18740     AsmOperandInfo &info, const char *constraint) const {
18741   ConstraintWeight weight = CW_Invalid;
18742   Value *CallOperandVal = info.CallOperandVal;
18743     // If we don't have a value, we can't do a match,
18744     // but allow it at the lowest weight.
18745   if (CallOperandVal == NULL)
18746     return CW_Default;
18747   Type *type = CallOperandVal->getType();
18748   // Look at the constraint type.
18749   switch (*constraint) {
18750   default:
18751     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18752   case 'R':
18753   case 'q':
18754   case 'Q':
18755   case 'a':
18756   case 'b':
18757   case 'c':
18758   case 'd':
18759   case 'S':
18760   case 'D':
18761   case 'A':
18762     if (CallOperandVal->getType()->isIntegerTy())
18763       weight = CW_SpecificReg;
18764     break;
18765   case 'f':
18766   case 't':
18767   case 'u':
18768     if (type->isFloatingPointTy())
18769       weight = CW_SpecificReg;
18770     break;
18771   case 'y':
18772     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18773       weight = CW_SpecificReg;
18774     break;
18775   case 'x':
18776   case 'Y':
18777     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18778         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18779       weight = CW_Register;
18780     break;
18781   case 'I':
18782     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18783       if (C->getZExtValue() <= 31)
18784         weight = CW_Constant;
18785     }
18786     break;
18787   case 'J':
18788     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18789       if (C->getZExtValue() <= 63)
18790         weight = CW_Constant;
18791     }
18792     break;
18793   case 'K':
18794     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18795       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18796         weight = CW_Constant;
18797     }
18798     break;
18799   case 'L':
18800     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18801       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18802         weight = CW_Constant;
18803     }
18804     break;
18805   case 'M':
18806     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18807       if (C->getZExtValue() <= 3)
18808         weight = CW_Constant;
18809     }
18810     break;
18811   case 'N':
18812     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18813       if (C->getZExtValue() <= 0xff)
18814         weight = CW_Constant;
18815     }
18816     break;
18817   case 'G':
18818   case 'C':
18819     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18820       weight = CW_Constant;
18821     }
18822     break;
18823   case 'e':
18824     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18825       if ((C->getSExtValue() >= -0x80000000LL) &&
18826           (C->getSExtValue() <= 0x7fffffffLL))
18827         weight = CW_Constant;
18828     }
18829     break;
18830   case 'Z':
18831     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18832       if (C->getZExtValue() <= 0xffffffff)
18833         weight = CW_Constant;
18834     }
18835     break;
18836   }
18837   return weight;
18838 }
18839
18840 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18841 /// with another that has more specific requirements based on the type of the
18842 /// corresponding operand.
18843 const char *X86TargetLowering::
18844 LowerXConstraint(EVT ConstraintVT) const {
18845   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18846   // 'f' like normal targets.
18847   if (ConstraintVT.isFloatingPoint()) {
18848     if (Subtarget->hasSSE2())
18849       return "Y";
18850     if (Subtarget->hasSSE1())
18851       return "x";
18852   }
18853
18854   return TargetLowering::LowerXConstraint(ConstraintVT);
18855 }
18856
18857 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18858 /// vector.  If it is invalid, don't add anything to Ops.
18859 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18860                                                      std::string &Constraint,
18861                                                      std::vector<SDValue>&Ops,
18862                                                      SelectionDAG &DAG) const {
18863   SDValue Result(0, 0);
18864
18865   // Only support length 1 constraints for now.
18866   if (Constraint.length() > 1) return;
18867
18868   char ConstraintLetter = Constraint[0];
18869   switch (ConstraintLetter) {
18870   default: break;
18871   case 'I':
18872     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18873       if (C->getZExtValue() <= 31) {
18874         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18875         break;
18876       }
18877     }
18878     return;
18879   case 'J':
18880     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18881       if (C->getZExtValue() <= 63) {
18882         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18883         break;
18884       }
18885     }
18886     return;
18887   case 'K':
18888     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18889       if (isInt<8>(C->getSExtValue())) {
18890         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18891         break;
18892       }
18893     }
18894     return;
18895   case 'N':
18896     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18897       if (C->getZExtValue() <= 255) {
18898         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18899         break;
18900       }
18901     }
18902     return;
18903   case 'e': {
18904     // 32-bit signed value
18905     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18906       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18907                                            C->getSExtValue())) {
18908         // Widen to 64 bits here to get it sign extended.
18909         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18910         break;
18911       }
18912     // FIXME gcc accepts some relocatable values here too, but only in certain
18913     // memory models; it's complicated.
18914     }
18915     return;
18916   }
18917   case 'Z': {
18918     // 32-bit unsigned value
18919     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18920       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18921                                            C->getZExtValue())) {
18922         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18923         break;
18924       }
18925     }
18926     // FIXME gcc accepts some relocatable values here too, but only in certain
18927     // memory models; it's complicated.
18928     return;
18929   }
18930   case 'i': {
18931     // Literal immediates are always ok.
18932     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18933       // Widen to 64 bits here to get it sign extended.
18934       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18935       break;
18936     }
18937
18938     // In any sort of PIC mode addresses need to be computed at runtime by
18939     // adding in a register or some sort of table lookup.  These can't
18940     // be used as immediates.
18941     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18942       return;
18943
18944     // If we are in non-pic codegen mode, we allow the address of a global (with
18945     // an optional displacement) to be used with 'i'.
18946     GlobalAddressSDNode *GA = 0;
18947     int64_t Offset = 0;
18948
18949     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18950     while (1) {
18951       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18952         Offset += GA->getOffset();
18953         break;
18954       } else if (Op.getOpcode() == ISD::ADD) {
18955         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18956           Offset += C->getZExtValue();
18957           Op = Op.getOperand(0);
18958           continue;
18959         }
18960       } else if (Op.getOpcode() == ISD::SUB) {
18961         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18962           Offset += -C->getZExtValue();
18963           Op = Op.getOperand(0);
18964           continue;
18965         }
18966       }
18967
18968       // Otherwise, this isn't something we can handle, reject it.
18969       return;
18970     }
18971
18972     const GlobalValue *GV = GA->getGlobal();
18973     // If we require an extra load to get this address, as in PIC mode, we
18974     // can't accept it.
18975     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18976                                                         getTargetMachine())))
18977       return;
18978
18979     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18980                                         GA->getValueType(0), Offset);
18981     break;
18982   }
18983   }
18984
18985   if (Result.getNode()) {
18986     Ops.push_back(Result);
18987     return;
18988   }
18989   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18990 }
18991
18992 std::pair<unsigned, const TargetRegisterClass*>
18993 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18994                                                 MVT VT) const {
18995   // First, see if this is a constraint that directly corresponds to an LLVM
18996   // register class.
18997   if (Constraint.size() == 1) {
18998     // GCC Constraint Letters
18999     switch (Constraint[0]) {
19000     default: break;
19001       // TODO: Slight differences here in allocation order and leaving
19002       // RIP in the class. Do they matter any more here than they do
19003       // in the normal allocation?
19004     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19005       if (Subtarget->is64Bit()) {
19006         if (VT == MVT::i32 || VT == MVT::f32)
19007           return std::make_pair(0U, &X86::GR32RegClass);
19008         if (VT == MVT::i16)
19009           return std::make_pair(0U, &X86::GR16RegClass);
19010         if (VT == MVT::i8 || VT == MVT::i1)
19011           return std::make_pair(0U, &X86::GR8RegClass);
19012         if (VT == MVT::i64 || VT == MVT::f64)
19013           return std::make_pair(0U, &X86::GR64RegClass);
19014         break;
19015       }
19016       // 32-bit fallthrough
19017     case 'Q':   // Q_REGS
19018       if (VT == MVT::i32 || VT == MVT::f32)
19019         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19020       if (VT == MVT::i16)
19021         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19022       if (VT == MVT::i8 || VT == MVT::i1)
19023         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19024       if (VT == MVT::i64)
19025         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19026       break;
19027     case 'r':   // GENERAL_REGS
19028     case 'l':   // INDEX_REGS
19029       if (VT == MVT::i8 || VT == MVT::i1)
19030         return std::make_pair(0U, &X86::GR8RegClass);
19031       if (VT == MVT::i16)
19032         return std::make_pair(0U, &X86::GR16RegClass);
19033       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19034         return std::make_pair(0U, &X86::GR32RegClass);
19035       return std::make_pair(0U, &X86::GR64RegClass);
19036     case 'R':   // LEGACY_REGS
19037       if (VT == MVT::i8 || VT == MVT::i1)
19038         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19039       if (VT == MVT::i16)
19040         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19041       if (VT == MVT::i32 || !Subtarget->is64Bit())
19042         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19043       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19044     case 'f':  // FP Stack registers.
19045       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19046       // value to the correct fpstack register class.
19047       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19048         return std::make_pair(0U, &X86::RFP32RegClass);
19049       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19050         return std::make_pair(0U, &X86::RFP64RegClass);
19051       return std::make_pair(0U, &X86::RFP80RegClass);
19052     case 'y':   // MMX_REGS if MMX allowed.
19053       if (!Subtarget->hasMMX()) break;
19054       return std::make_pair(0U, &X86::VR64RegClass);
19055     case 'Y':   // SSE_REGS if SSE2 allowed
19056       if (!Subtarget->hasSSE2()) break;
19057       // FALL THROUGH.
19058     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19059       if (!Subtarget->hasSSE1()) break;
19060
19061       switch (VT.SimpleTy) {
19062       default: break;
19063       // Scalar SSE types.
19064       case MVT::f32:
19065       case MVT::i32:
19066         return std::make_pair(0U, &X86::FR32RegClass);
19067       case MVT::f64:
19068       case MVT::i64:
19069         return std::make_pair(0U, &X86::FR64RegClass);
19070       // Vector types.
19071       case MVT::v16i8:
19072       case MVT::v8i16:
19073       case MVT::v4i32:
19074       case MVT::v2i64:
19075       case MVT::v4f32:
19076       case MVT::v2f64:
19077         return std::make_pair(0U, &X86::VR128RegClass);
19078       // AVX types.
19079       case MVT::v32i8:
19080       case MVT::v16i16:
19081       case MVT::v8i32:
19082       case MVT::v4i64:
19083       case MVT::v8f32:
19084       case MVT::v4f64:
19085         return std::make_pair(0U, &X86::VR256RegClass);
19086       case MVT::v8f64:
19087       case MVT::v16f32:
19088       case MVT::v16i32:
19089       case MVT::v8i64:
19090         return std::make_pair(0U, &X86::VR512RegClass);
19091       }
19092       break;
19093     }
19094   }
19095
19096   // Use the default implementation in TargetLowering to convert the register
19097   // constraint into a member of a register class.
19098   std::pair<unsigned, const TargetRegisterClass*> Res;
19099   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19100
19101   // Not found as a standard register?
19102   if (Res.second == 0) {
19103     // Map st(0) -> st(7) -> ST0
19104     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19105         tolower(Constraint[1]) == 's' &&
19106         tolower(Constraint[2]) == 't' &&
19107         Constraint[3] == '(' &&
19108         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19109         Constraint[5] == ')' &&
19110         Constraint[6] == '}') {
19111
19112       Res.first = X86::ST0+Constraint[4]-'0';
19113       Res.second = &X86::RFP80RegClass;
19114       return Res;
19115     }
19116
19117     // GCC allows "st(0)" to be called just plain "st".
19118     if (StringRef("{st}").equals_lower(Constraint)) {
19119       Res.first = X86::ST0;
19120       Res.second = &X86::RFP80RegClass;
19121       return Res;
19122     }
19123
19124     // flags -> EFLAGS
19125     if (StringRef("{flags}").equals_lower(Constraint)) {
19126       Res.first = X86::EFLAGS;
19127       Res.second = &X86::CCRRegClass;
19128       return Res;
19129     }
19130
19131     // 'A' means EAX + EDX.
19132     if (Constraint == "A") {
19133       Res.first = X86::EAX;
19134       Res.second = &X86::GR32_ADRegClass;
19135       return Res;
19136     }
19137     return Res;
19138   }
19139
19140   // Otherwise, check to see if this is a register class of the wrong value
19141   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19142   // turn into {ax},{dx}.
19143   if (Res.second->hasType(VT))
19144     return Res;   // Correct type already, nothing to do.
19145
19146   // All of the single-register GCC register classes map their values onto
19147   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
19148   // really want an 8-bit or 32-bit register, map to the appropriate register
19149   // class and return the appropriate register.
19150   if (Res.second == &X86::GR16RegClass) {
19151     if (VT == MVT::i8 || VT == MVT::i1) {
19152       unsigned DestReg = 0;
19153       switch (Res.first) {
19154       default: break;
19155       case X86::AX: DestReg = X86::AL; break;
19156       case X86::DX: DestReg = X86::DL; break;
19157       case X86::CX: DestReg = X86::CL; break;
19158       case X86::BX: DestReg = X86::BL; break;
19159       }
19160       if (DestReg) {
19161         Res.first = DestReg;
19162         Res.second = &X86::GR8RegClass;
19163       }
19164     } else if (VT == MVT::i32 || VT == MVT::f32) {
19165       unsigned DestReg = 0;
19166       switch (Res.first) {
19167       default: break;
19168       case X86::AX: DestReg = X86::EAX; break;
19169       case X86::DX: DestReg = X86::EDX; break;
19170       case X86::CX: DestReg = X86::ECX; break;
19171       case X86::BX: DestReg = X86::EBX; break;
19172       case X86::SI: DestReg = X86::ESI; break;
19173       case X86::DI: DestReg = X86::EDI; break;
19174       case X86::BP: DestReg = X86::EBP; break;
19175       case X86::SP: DestReg = X86::ESP; break;
19176       }
19177       if (DestReg) {
19178         Res.first = DestReg;
19179         Res.second = &X86::GR32RegClass;
19180       }
19181     } else if (VT == MVT::i64 || VT == MVT::f64) {
19182       unsigned DestReg = 0;
19183       switch (Res.first) {
19184       default: break;
19185       case X86::AX: DestReg = X86::RAX; break;
19186       case X86::DX: DestReg = X86::RDX; break;
19187       case X86::CX: DestReg = X86::RCX; break;
19188       case X86::BX: DestReg = X86::RBX; break;
19189       case X86::SI: DestReg = X86::RSI; break;
19190       case X86::DI: DestReg = X86::RDI; break;
19191       case X86::BP: DestReg = X86::RBP; break;
19192       case X86::SP: DestReg = X86::RSP; break;
19193       }
19194       if (DestReg) {
19195         Res.first = DestReg;
19196         Res.second = &X86::GR64RegClass;
19197       }
19198     }
19199   } else if (Res.second == &X86::FR32RegClass ||
19200              Res.second == &X86::FR64RegClass ||
19201              Res.second == &X86::VR128RegClass ||
19202              Res.second == &X86::VR256RegClass ||
19203              Res.second == &X86::FR32XRegClass ||
19204              Res.second == &X86::FR64XRegClass ||
19205              Res.second == &X86::VR128XRegClass ||
19206              Res.second == &X86::VR256XRegClass ||
19207              Res.second == &X86::VR512RegClass) {
19208     // Handle references to XMM physical registers that got mapped into the
19209     // wrong class.  This can happen with constraints like {xmm0} where the
19210     // target independent register mapper will just pick the first match it can
19211     // find, ignoring the required type.
19212
19213     if (VT == MVT::f32 || VT == MVT::i32)
19214       Res.second = &X86::FR32RegClass;
19215     else if (VT == MVT::f64 || VT == MVT::i64)
19216       Res.second = &X86::FR64RegClass;
19217     else if (X86::VR128RegClass.hasType(VT))
19218       Res.second = &X86::VR128RegClass;
19219     else if (X86::VR256RegClass.hasType(VT))
19220       Res.second = &X86::VR256RegClass;
19221     else if (X86::VR512RegClass.hasType(VT))
19222       Res.second = &X86::VR512RegClass;
19223   }
19224
19225   return Res;
19226 }